InterviewDryRun
Lesson 30 · 21 min video · free

Design a Distributed Lock Service

A distributed lock service lets many machines agree that only one of them holds a lock at a time, even when machines crash, pause and lose the network. The interview tests whether you understand why leases expire, why that alone is not safe, and how fencing tokens and a consensus cluster close the gap. This lesson walks through the whole 45-minute answer.

What you will learn

  • Ask whether the lock protects correctness or only efficiency; it decides how strong the design must be.
  • Tie locks to sessions with leases and keep alives, so a crashed client's locks are released automatically.
  • Use a five-replica consensus cluster that commits on a majority, so a failover can never grant a lock twice.
  • Measure leases with monotonic clocks, make clients give up early, and give sessions grace after a leader change.
  • A paused client can outlive its lease; only fencing tokens checked by the storage keep the data safe.
  • Queue waiters instead of waking them all, shard by lock name for scale, and spread replicas over three zones.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The interface
  5. Step 4: High-level design
  6. Step 5: Agreeing on who holds the lock
  7. Step 6: Leases, and what time really means
  8. Step 7: Fencing tokens
  9. Step 8: Scaling and failures
  10. Step 9: The parts people forget
  11. Step 10: The follow-up questions
  12. Recap
Practice this question with Max

The question

Welcome to lesson thirty of the InterviewDryRun system design course. Today we are designing a distributed lock service: a small, very reliable system that lets many machines agree that only one of them is doing a particular job at a time.

You need one more often than you would think. Only one worker should run the nightly billing job. Only one server should be the leader that writes to a shard. Only one process should rename a file in shared storage. On a single machine, a mutex does this. Across hundreds of machines that crash, pause and lose the network, it is one of the hardest problems in the field.

Max asks

“Design a lock service with lease expiry and fencing, like the coordination services large systems rely on.”

That is how Max, our AI interviewer, asks it. Two words in that sentence tell you where the interview is going: lease, and fencing. The interviewer already knows that a lock which never expires is dangerous, and that a lock which does expire is dangerous in a different way. Your job is to show that you see both dangers, and how to close them.

Here is the plan. We will clarify requirements, size the problem, and define the interface. Then we will draw the design, and go deep on the three hard parts: agreeing on who holds a lock when machines fail, leases and what time really means in a distributed system, and fencing tokens. We will finish with scaling, failure, the parts people forget, and Max's follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Acquire and releaseBy lock name; one holder at a time
  2. 02
    LeasesA lock expires if its holder stops renewing
  3. 03
    Fencing tokensA number that grows with every new holder
  4. 04
    Wait or fail fastTry once, or queue until the lock is free
  5. 05
    WatchBe told when a lock changes hands

As always, start with questions, not boxes. The first one is: what does a lock protect? If it protects correctness, like two workers both charging a customer, a mistake is a real bug. If it only protects efficiency, like two workers doing the same cache refresh, a rare mistake costs a little wasted work. The answer changes how strong the design must be, so ask it.

The core operations are simple. A client acquires a lock by name, like billing nightly run, does its work, and releases it. At most one client holds a given lock at any moment. We will support exclusive locks; mention that shared read locks are a possible extension, but keep them out of scope.

Next, what if the holder dies? A process that crashes while holding a lock can never release it. So every lock comes with a lease: it is held only for a limited time, say ten seconds, and the holder must keep renewing it. If renewals stop, the lease runs out and the lock becomes free.

Max asked for fencing, so it is a requirement. Every time a lock is granted, the service hands out a fencing token: a number that is larger than any token given before for that lock. We will see shortly why this number is the only thing that makes leases safe.

And two conveniences that real users ask for. A client should be able to try once and fail fast, or wait in a queue until the lock is free. And other clients should be able to watch a lock, to be told when it changes hands, for example to find the current leader without asking over and over.

Non-functional requirements
  1. 01
    Safety firstNever two holders that can both change data
  2. 02
    Highly availableSurvives a machine or a zone failing
  3. 03
    Low latencyA few milliseconds to acquire inside one region
  4. 04
    DurableGranted locks and tokens survive restarts
  5. 05
    FairWaiting clients get the lock in order

Now the qualities. Safety comes first: two clients must never both believe they hold the same lock, in a way that can damage data. A lock service that is fast but occasionally wrong is worse than useless, because people trust it.

Then availability. Many systems depend on this service to elect leaders, so if it goes down, they all stall. It must survive a machine failing, and ideally a whole availability zone. And note the tension now: in a network partition, we will choose safety over availability. The side without a majority refuses to grant locks rather than risk two holders.

Latency should be a few milliseconds inside one region, which rules out designs that need a round trip across continents for every lock. State must be durable, so a restart does not forget who holds what or reuse an old token. And waiting clients should get the lock roughly in the order they asked, so no one starves.

Step 2: Back-of-the-envelope estimates

Rough numbers
Clients10,000processes holding sessions
Locks held100,000names plus holder plus token
State size≈ 100 MBabout 1 KB per lock, fits in memory
Renewals≈ 3,000 / sone per session every 3 seconds
Acquires≈ 5,000 / speaks during deploys and failovers
Replicas5survives 2 failures

Let us size it, and you will see that this is not a big-data problem. Say the service supports a whole company: ten thousand client processes, holding about a hundred thousand locks between them at any moment.

Each lock needs its name, its holder, its lease expiry and its token: call it a kilobyte with overhead. A hundred thousand locks is about a hundred megabytes. That fits comfortably in memory on every replica, which is exactly what we want.

The traffic is mostly renewals. If each client renews one session every three seconds, covering all its locks at once, that is around three thousand writes a second. Acquires and releases add a few thousand more, with bursts when a big deploy restarts many services at once.

So the challenge is not size or throughput: one machine could handle the load. The challenge is correctness when machines fail. That tells us to use a small cluster, five replicas, that agree on every change. Five replicas means a majority is three, so the service keeps working with two replicas down.

Step 3: The interface

The lock API
openSession(ttl=10s)                  → { sessionId }
keepAlive(sessionId)                  → { expiresAt }

acquire(name, sessionId, wait=5s)     → { granted, token: 34 }
release(name, sessionId, token)       → ok

watch(name)                           → stream of { holder, token }

# Storage the lock protects:
write(key, value, fencingToken=34)    → ok | rejected: stale token

Here is the interface. A client first opens a session, which is how the service knows the client is alive. The session has a lease time, say ten seconds, and the client renews it with a keep alive every few seconds.

Locks are tied to the session, not held one by one. When a client acquires a lock, it names its session, and it either gets the lock with a fencing token, or waits up to the time it asked for. If the session expires, every lock it holds is released together. That way a client with fifty locks sends one keep alive, not fifty.

Release takes the token as well as the name, so a client that lost its lock a moment ago cannot accidentally release a lock that now belongs to someone else. And look at the last line: the storage the lock protects accepts the fencing token with every write. That line is the most important one on the screen, and we will spend a whole step on it.

Watch is worth a sentence too. Instead of clients polling who the leader is every second, which would multiply our traffic many times over, a client opens a long-lived stream for a lock name, and the service pushes an event whenever the holder changes. The event carries the new token, so the watcher can tell an old notification from a new one, even if they arrive out of order.

Step 4: High-level design

High-level design
acquirereplicatereplicatewrite + tokenCLIENTClientswith a lock librarySERVICELeader replicaorders every changeSERVICEFollowercopy of the logSERVICEFollowercopy of the logSTOREReplicated logon disk, majoritySTOREProtected storagechecks tokens

Now the picture. On the left, the clients: workers, schedulers and services that want locks. Each one runs a small client library that opens a session, sends keep alives in the background, and tells the application if its session is in danger.

The lock service itself is a cluster of five replicas, and one of them is the leader. Every request that changes state, an acquire, a release, a renewal, goes to the leader. Followers redirect clients there. Having one leader gives every change a single, clear order.

The leader does not just change its own memory. It appends the change to a replicated log and sends it to the followers. Only when a majority of the five, three including itself, have written the entry to disk does the leader apply it and answer the client. That is a consensus protocol, and it is the foundation of the whole design.

Each replica applies the log entries in order to the same simple state machine: a table of lock names, holders, lease expiry and the last token issued. Because every replica applies the same entries in the same order, they all end up with the same table.

And at the bottom, the storage the lock protects: a database, a file store, whatever the client is changing. It is not part of our service, but it is part of the design, because it checks the fencing token on every write. We will see why that is not optional.

One more thing on reads. Asking who holds a lock could be answered by any follower, but a follower might be slightly behind. For anything that matters, reads also go through the leader, which first confirms it is still the leader with a majority. Watches are served by any replica, since a notification arriving a few milliseconds late is fine.

Step 5: Agreeing on who holds the lock

Why simpler designs fail
  1. 01
    One serverSimple and fast, but one failure stops everything
  2. 02
    Primary with a copyCopying is async; a failover can lose a grant
  3. 03
    Key with expiry in a cacheSame problem, plus clocks and evictions
  4. 04
    Majority consensusSurvives failures without ever granting twice

The first deep dive: why do we need consensus at all? Interviewers often push here, because the obvious designs are simpler. Let us knock them down one by one, out loud.

One lock server is simple and correct, until it dies. Then nobody can acquire anything, and every system that depends on leader election stalls. And if it comes back from a disk that lost its last few writes, it might grant a lock that is already held.

A primary with a replica seems better. But if copying to the replica is asynchronous, the primary can grant a lock, crash before the copy arrives, and the replica takes over without knowing. It grants the same lock to someone else. Two holders. The same is true of setting a key with an expiry in a cache cluster: it is fine for efficiency locks, but a failover can lose the key.

Consensus fixes this with one rule: nothing counts until a majority has written it. Any two majorities of five share at least one replica. So when a new leader is elected, it must have the votes of a majority, and at least one of those voters has every committed entry. The new leader therefore always knows about every lock ever granted.

Leader election works like this. Followers expect regular heartbeats from the leader. If a follower hears nothing for, say, a second and a half, it starts an election with a higher term number and asks the others for votes. Each replica votes once per term, and only for a candidate whose log is at least as up to date as its own. The first to reach a majority becomes leader.

And during a network partition, the side with three replicas keeps working, and the side with two cannot reach a majority, so it refuses to grant anything. That is the trade-off we chose in the requirements: a short pause in a failure is acceptable, granting a lock twice is not.

One detail on the log: each replica writes an entry to disk, and forces it to the disk, before it acknowledges it. If replicas only kept entries in memory, a power cut across a zone could wipe out a majority's memory at once, and the cluster would forget grants it had already confirmed. This is why acquires take a few milliseconds rather than microseconds: we are paying for a disk flush on three machines, and that is the price of safety.

Step 6: Leases, and what time really means

Leases in practice
  1. 01
    Server-side timerThe leader measures lease time with its own clock
  2. 02
    Client marginThe client assumes it lost the lock early
  3. 03
    Monotonic clocksMeasure durations, never wall-clock time
  4. 04
    Leader changesA new leader extends leases before expiring them
  5. 05
    The pause problemA client can stop for longer than its lease

Now leases. The lease is how we handle a client that crashes: if it stops renewing, its locks are released after the lease time. Simple. But leases depend on time, and time is where distributed systems lie to you.

The leader decides when a lease expires, using its own clock. The client also tracks the lease, and it must be pessimistic. If the lease is ten seconds and the client last renewed successfully at time zero, it should treat its lock as lost at, say, eight seconds, not ten, to allow for network delay and clock drift between the two machines.

Both sides measure durations with a monotonic clock, one that only counts forward, never with the time of day. Wall clocks can jump when a machine syncs its time, by seconds or more, and a lease measured against a wall clock could expire instantly or never.

When the leader changes, the new one does not know exactly when each client last renewed. So it gives every session a fresh grace period, a full lease time, before expiring anything. Clients reconnect and renew during that window. Expiring early would be the dangerous mistake; expiring a little late only costs a few seconds.

And now the problem that leases cannot solve on their own. A client holds the lock and starts writing. Then its process freezes: a long garbage collection pause, the machine swapping, the virtual machine being paused by the host. Fifteen seconds go by. The lease expires, and the lock service, correctly, gives the lock to another client.

Then the first client wakes up. From its point of view, no time has passed. It still believes it holds the lock, and it finishes its write. Now two clients have written as the lock holder. No amount of checking the clock before writing fixes this, because the pause can happen between the check and the write. This is why Max asked for fencing.

Step 7: Fencing tokens

Fencing a paused client
token 33token 34write, 34: okwrite, 33: rejectedSERVICELock servicelease expiresWORKERClient Atoken 33, then pausesWORKERClient Btoken 34STOREStoragehighest token seen

Let us walk through it on a timeline. Client A acquires the lock and receives fencing token thirty-three. It starts its work.

Client A freezes. Its lease runs out, and client B asks for the same lock. The service grants it, with token thirty-four, because the token always grows by at least one with every grant.

Client B writes to storage, and it sends its token, thirty-four, with the write. The storage remembers the highest token it has seen for this resource, thirty-four, and accepts the write.

Now client A wakes up and sends its write, with token thirty-three. The storage compares: thirty-three is lower than thirty-four, which it has already seen. So it rejects the write. Client A learns that it lost the lock, and the data is safe. The paused client was fenced off.

The key insight to say out loud: the lock service alone can never guarantee mutual exclusion, because it cannot stop a paused client from acting. The guarantee comes from the lock service and the storage working together. The service issues an ever-growing number, and the storage refuses anything older than what it has already accepted.

This means the protected storage must support the check. A database can do it with a conditional write: update only if the stored token is lower than mine. An object store may support a version condition. If the storage cannot check tokens at all, say so honestly: then the lock is only good for efficiency, and the work itself must be safe to repeat.

And the token is cheap to produce correctly, because of consensus. The last token for each lock is in the replicated state, and every grant is a log entry, so a new leader always knows the highest token issued. Even after failovers and restarts, a token is never reused.

A subtle case to mention: what if one job writes to two different stores under the same lock? Then both stores must check the token, and each remembers the highest token it has seen independently. A store that does not check is the weak link, so list every resource the lock protects, and make sure each one either checks tokens or only receives writes that are safe to repeat.

Step 8: Scaling and failures

Scaling and failure
  1. 01
    Shard by lock nameIndependent clusters, each with its own leader
  2. 02
    Batch the logMany changes per disk write
  3. 03
    No thundering herdWake only the next waiter, in order
  4. 04
    Leader failureNew election in a second or two; sessions get grace
  5. 05
    Zone failureSpread five replicas over three zones

Now scale and failure. Start with throughput. All writes go through one leader, which is fine for a few thousand operations a second. If a company needs far more, we shard: several independent clusters, each owning a range of lock names by hash, with a small directory saying which cluster owns which range.

Within one cluster, batching matters most. The leader groups many changes into one log write and one round of replication, so a thousand renewals can cost a handful of disk writes. Renewals of the same session can even be merged, since only the newest one matters.

Watch out for the thundering herd. If a popular lock has a hundred waiters, and every one is woken when it is released, a hundred clients rush to acquire it, and ninety-nine fail. Instead, keep waiters in a queue in the replicated state and grant the lock directly to the next one in line. That is also what gives us fairness.

When the leader fails, followers stop getting heartbeats, and within a second or two a new leader is elected. During that gap no locks are granted, and clients retry. Thanks to the grace period, no session expires because of the failover itself. Clients see a short pause, never a wrong answer.

And place the replicas well. Five replicas spread over three availability zones, two, two and one, means losing any one zone still leaves a majority. Spreading across regions gives even more resilience but turns every write into a cross-region round trip, so most designs keep one cluster per region and keep locks local to that region.

Step 9: The parts people forget

Often forgotten
  1. 01
    Do you need a lock?Idempotent work or partitioned ownership may be simpler
  2. 02
    GranularityOne lock per resource, not one lock for everything
  3. 03
    DeadlocksAcquire in a fixed order, or set timeouts
  4. 04
    ObservabilityWho holds what, for how long, and who is waiting

A few things that strong candidates mention. First, ask whether a lock is the right tool at all. Often the problem can be redesigned so that the work is idempotent, or so that a single owner is assigned by partitioning. A lock you do not need is a failure you do not have.

Second, granularity. One big lock for all billing is easy but serialises everything. One lock per customer allows parallel work. Too many tiny locks, though, and the service fills up with state. Pick a natural unit, and say why.

Third, deadlocks. If a client needs two locks, and another client takes them in the opposite order, both wait forever. The usual answers are to always acquire locks in a fixed order, such as sorted by name, and to always use a wait timeout, so a stuck acquire fails instead of hanging.

And observability. When something is stuck at three in the morning, the first question is who holds this lock, since when, and who is waiting. The service should expose exactly that, along with metrics on lease expiries, which often reveal clients with long pauses before they cause damage.

And test the failure paths on purpose. Most lock bugs only appear when a client pauses, a network splits, or a leader dies at the worst moment. Good teams run tests that freeze client processes, drop packets between replicas, and kill the leader in the middle of a grant, then check that no two holders ever wrote with the same or older token. Saying that you would test this way shows you have operated such a system, not only drawn one.

Step 10: The follow-up questions

Max asks

“Why not just use a row in an ordinary database, with an expiry column, as the lock?”

For many teams, that is a perfectly good answer, if the database is itself replicated with synchronous commits and you use a transaction to check and set the row. Add a token column that you increment on every grant, and you have fencing too. What a dedicated service adds is sessions with keep alives, waiting queues, watches, and isolation from the load of the main database. Say that you would start simple if the scale allows it.

Max asks

“How would you use this service to elect a leader for a group of servers?”

Every server tries to acquire the same lock, say leader for shard seven. The one that gets it is the leader, and its fencing token doubles as its leadership term. The others watch the lock, so when the leader's session expires, they are told and one of them acquires it. Anything the leader writes carries its token, so a deposed leader that wakes up late cannot overwrite the new leader's work.

Max asks

“A client's network blips for twelve seconds, longer than its lease. What happens, and what should the client do?”

The service expires the session and releases its locks, and may grant them to others. The client library notices that renewals have failed past its safety margin, and tells the application that the lock is lost, before the lease actually runs out on the server. The application must stop work that needs the lock. When the network returns, the client opens a new session and acquires again, getting a new, higher token.

Max asks

“Could you run this with three replicas instead of five?”

Yes. Three replicas tolerate one failure, and writes are a little faster, because the majority is two. Five tolerate two failures, which matters during maintenance: with three, taking one replica down for an upgrade leaves no room for another failure. For a service that everything depends on, five is the usual choice. Going beyond seven only makes writes slower without much more safety.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsLeases, fencing, waits, watches; safety first
  2. 02
    5 to 10: estimates100 MB of state, thousands of writes, 5 replicas
  3. 03
    10 to 20: design and consensusLeader, replicated log, majority commits
  4. 04
    20 to 35: leases and fencingMonotonic clocks, client margin, tokens checked by storage
  5. 05
    35 to 45: scale and edgesShards, queues, failover, zones, deadlocks

Let us map it onto forty-five minutes. Five minutes of requirements, ending with acquire and release, leases, fencing tokens, waiting and watches, and the decision that safety beats availability. Five minutes of estimates, ending with: small state, a few thousand writes a second, so the hard part is failure, not scale.

Then around ten minutes on the design: sessions and keep alives, a five-replica cluster with a leader, and a replicated log that commits on a majority. Explain why a single server or an asynchronous copy can grant a lock twice.

Fifteen minutes on leases and fencing: server-side timers, a pessimistic client, monotonic clocks, grace after a leader change, and the paused client that wakes up still believing it holds the lock, stopped by a fencing token the storage checks. And the last ten minutes on scaling and the edges: sharding, waiter queues, failover, zones and deadlocks. Say the trade-offs out loud at each step, and you have a strong answer.

Knowing what a fencing token is, is the easy part. Explaining clearly why a lease alone is not enough, while someone asks you what happens when a client pauses for fifteen seconds, is the part that takes practice. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in the next lesson.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.