Distributed Locks in System Design Interviews: When to Use Them
When you talk about a distributed lock you are describing a coordination primitive that guarantees only one instance of a service can hold a lock at any time, even though the lock lives across many machines. The lock solves the classic multiple writers problem: several independent processes need to update the same piece of state without stepping on each other.
The Problem Illustrated
Imagine an e-commerce site that sells a limited edition sneaker. The inventory count lives in a database row. When the site receives a purchase request, it reads the count, decrements it, and writes the new value back. If two front-end servers read the same count simultaneously, both may think stock is still available and both will write a new count, resulting in overselling.
A distributed lock placed around the "read-modify-write" sequence ensures that only one server can execute that critical section at a time, preserving the invariant that the total sold never exceeds the stock.
How a Distributed Lock Works – Step by Step
Below is a minimal example using a DynamoDB table with a conditional write (the same pattern applies to Zookeeper, etcd, or Redis RedLock).
- Create a lock record – A table called
Lockshas a primary keyresource_id. The lock row contains aowner_idand a TTL (time-to-live) field. - Acquire – The client attempts a
PutItemwithConditionExpressionthat the item does not exist (or that the TTL has expired). If the condition succeeds, DynamoDB creates the row and the client becomes the lock holder. - Do work – The client performs the critical section, e.g., reads the inventory row, decrements the count, writes it back.
- Release – The client deletes the lock row (or updates the TTL to a past timestamp). If the client crashes, the TTL expires and another client can acquire the lock.
- Retry – If the acquire step fails because another holder exists, the client backs off and retries after a short delay.
The key pieces are the atomic conditional write that guarantees only one holder can succeed, and the lease (TTL) that prevents permanent deadlock if the holder disappears.
Where Distributed Locks Appear in Classic Design Questions
| Design Question | Where the Lock Appears | Reason for Using It |
|---|---|---|
| Ticket reservation system (e.g., airline seat booking) | Around the seat-allocation transaction | Prevent double-booking of the same seat |
| Leader election for a distributed scheduler | In the election service that picks the primary node | Ensure only one scheduler runs the job at a time |
| Cache invalidation with write-through | When updating a cached object that also lives in the DB | Avoid race between cache update and DB write |
In each case the lock sits at the boundary where multiple stateless workers could otherwise concurrently modify a single piece of state.
Trade-offs and the Alternative Interviewer Will Probe
| Aspect | Distributed Lock (strong consistency) | Optimistic Concurrency / Versioning |
|---|---|---|
| Latency | Extra round-trip to acquire/release; can add tens of ms per request. | No extra round-trip; only fails on conflict. |
| Failure handling | Need to handle lease expiration, split-brain scenarios. | Must detect write conflicts and retry, but no deadlock risk. |
| Throughput | Limited by lock contention; serializes the critical section. | Higher throughput when conflicts are rare. |
| Complexity | Requires a consensus service or careful TTL management. | Simpler; just store a version number with the record. |
Interviewers often ask, "What if the lock service itself becomes a bottleneck?" Expect to discuss sharding the lock space, using hierarchical locks, or falling back to a lock-free design when contention is low.
A 30-Second Pitch You Can Say Out Loud
"A distributed lock is a coordination primitive that guarantees exclusive access to a shared resource across multiple machines. You typically implement it with a consensus service like Zookeeper or a conditional write in DynamoDB. It solves problems like overselling inventory or leader election by serializing the critical section, but it adds latency, creates a single point of contention, and requires careful lease handling. In interviews you should also mention optimistic concurrency as an alternative and be ready to discuss failure modes."
Common Mistakes Candidates Make
- Treating the lock as free – Claiming that acquiring a lock is negligible in latency. In reality, each acquire adds a network call and possible retry.
- Ignoring lease expiration – Forgetting to set a TTL, which can cause permanent deadlock if the holder crashes.
- Over-locking – Placing a lock around large chunks of code instead of the minimal critical section, dramatically reducing throughput.
- Assuming strong consistency everywhere – Not recognizing that many cloud services provide only eventual consistency; a lock built on top of such a store may not be reliable.
- Skipping failure paths – Not describing what happens if the lock service itself fails or partitions, which is a key part of a robust design.
How to Practice This
- Study the worked design – System Design AI has a worked design on contention, where thousands of requests race for the same item. Review the step-by-step diagram and the notes on lock acquisition.
- Sketch your own board – On the practice canvas, draw the request flow for an inventory-decrement scenario, marking where the lock lives and what fallback logic you would add.
- Run a mock interview – Explain the lock’s purpose, walk through the acquire-work-release steps, and discuss the trade-offs. Ask the interviewer to probe failure modes to reinforce your understanding.
Questions people ask
Do I always need a distributed lock for any shared state?
No. If the shared state can tolerate occasional conflicts, optimistic concurrency or version checks are simpler and faster.
How does a lock differ from a leader election?
A lock grants exclusive access for a short period, while leader election selects a permanent coordinator. Both use similar consensus primitives but serve different purposes.
Can I use Redis alone for a distributed lock?
Redis can provide a lock via the RedLock algorithm, but you must handle network partitions and ensure the Redis nodes are sufficiently replicated to avoid split-brain.
What is the typical timeout for a lock lease?
It depends on the operation’s expected duration; a common pattern is a few seconds plus a safety margin, with automatic renewal if the holder needs more time.