SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

Distributed Locks

Let only one machine do a job at a time, across many machines (and why that is hard).

⏱ 14 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A distributed lock lets only one machine at a time do a certain job or touch a certain piece of data, even when many machines run the same code.

  • A normal lock lives inside one program. A distributed lock lives in a shared service (Redis, ZooKeeper, etcd, a database) that every machine can reach.
  • Because machines can crash or freeze, a lock is given for a limited time (a lease). If the owner disappears, the lock expires by itself.
  • The danger: an owner that was only paused can wake up and act after its lock has gone to someone else. A fencing token protects against this.

02Concept: What is it?

Inside one program, a mutex stops two threads from changing the same thing together. With many servers, there is no shared memory, so a mutex does not work. If two servers both read a balance of 100, both subtract 30 and both write back 70, you lost a payment. You need something that all servers agree on to say "it is my turn".

A distributed lock is a record in a shared store: "resource X is owned by server A until time T". A server acquires the lock by creating that record if nobody else has. It releases it by deleting the record. If it crashes, the record expires after its time-to-live (TTL), so the system does not get stuck forever.

That expiry is also the source of the hardest problem. The owner might be slow, not dead: a long garbage collection pause, a busy CPU or a network delay. Its lock expires, another server takes it, and then the first one wakes up and keeps working, still believing it holds the lock. Now two servers act at once.

Acquire, work, release
🖥️Server Awants the lock
→↓1. acquire (TTL 10 s)
🔐Lock serviceRedis, etcd, ZooKeeper
→↓2. granted
⚙️Do the jobwhile holding it
→↓3. release
🔓Freenext server can take it
The lock service is the shared referee. It must itself be reliable.
🧠A lock with a timeout is only a hint
When a lock can expire, holding it does not prove you are alone. To be truly safe, the thing you are protecting must also check a fencing token.

03Real-Life Example

🍵The Key to the Only Meeting Room
A company has one meeting room and one key on a hook at reception. Whoever takes the key can use the room. To stop people keeping the key forever, reception says "you may keep it for one hour". If someone loses track of time, after an hour reception gives the key to the next person. Now picture the first person falling asleep inside the room. When they wake up, they still think the room is theirs and carry on, while the new person is also inside. To fix it, the door has a counter: every new key is stamped with a bigger number, and the door only opens for the newest number. The sleeper's old key stops working.
Meeting room
Distributed lock
The meeting room
The protected resource
The key on the hook at reception
The lock record in the lock service
Reception
The lock service (Redis, etcd, ZooKeeper)
Keep it for one hour at most
Lease or TTL
Asking for the key again before time is up
Renewing the lease
The person who fell asleep
A paused client (GC pause, slow network)
The number stamped on each key
Fencing token
The door that only accepts the newest number
Storage that rejects old tokens
What the fencing token does
😴Old ownertoken 33
→↓write (33)
🚪Storagealready saw 34
⇢⇣rejected
✅New ownertoken 34 accepted

04Why Do We Need It?

🚫Stop double work
A job like sending the daily email or charging a card must not run twice.
🧮Protect shared data
Two servers must not update the same record at the same moment and overwrite each other.
🔁Safe retries and failover
If the owner dies, the lock expires and another server continues.
🧑‍🤝‍🧑Fair turns
Servers wait in line or retry. Only one is in the critical section at a time.
🧱Simple coordination
One small rule (take the key first) is easier than a full consensus design.
🛡️Resource protection
Limit access to a fragile resource such as a legacy system that cannot take parallel calls.
When many machines can do the same thing, a distributed lock says "one at a time, please". It is useful, and it is also easy to get subtly wrong.

05Where Do We Use It?

⏰Scheduled jobs
Run the nightly report once, even if ten servers have the same cron.
🧊Cache refresh
Let one request rebuild an expired cache entry while the others wait (helps against a cache stampede).
💳Payments and inventory
Stop two requests spending the same stock or money. Often better done with database transactions.
📦File and batch processing
Only one worker takes a file or a batch.
🗂️Migrations and admin tasks
A schema migration or cleanup must run on one node at once.
👑Leader election
Holding a lock that you keep renewing is a simple way to be the leader.

06Types / Parts / How It Works

Where the lock can live

Common lock services
Database
🗄️Row lock or advisory lock
👍Simple if you have one DB
Redis
⚡SET key NX with TTL
👍Fast. Weaker guarantees
Consensus store
🔐etcd, ZooKeeper, Consul
🛡️Strongest. Slower
Pick by how strict you must be, and by what you already run.
OptionHow it worksGood and bad
Database lock (SELECT FOR UPDATE, advisory lock)Use a lock inside the database that already stores the dataSimple and strongly consistent with the data. Does not span several databases and holds a connection
Redis single instance (SET NX PX)Set a key only if it does not exist, with an expiry. Release with a check on the owner valueVery fast and easy. If Redis fails over, the lock can be lost or given twice
Redlock (several Redis nodes)Take the lock on a majority of independent Redis nodesMore fault tolerant. Depends on clocks and has no fencing token, so critics say it is unsafe for correctness
ZooKeeper (ephemeral nodes)Create an ephemeral sequential node. The lowest number owns the lock. It vanishes if the session diesStrong, with ordering you can use as a token. A heavier system to run
etcd or Consul (lease + key)Create a key attached to a lease. A revision number acts as a fencing tokenBuilt on Raft. Good safety. A new dependency
Cloud services (DynamoDB conditional writes, GCS, Kubernetes Lease)A conditional write to a managed storeLittle to run. Tied to the cloud product

Two reasons to lock

GoalMeaningWhat you need
EfficiencyAvoid doing the same work twice (for example sending the same email twice would just waste money)A simple lock is fine. An occasional double run is acceptable
CorrectnessTwo owners would corrupt dataA real consensus-based lock with fencing tokens, or better, avoid the lock with a transaction or a conditional write
VisualizerA lock with a lease: what happens when the owner freezes?Make client A freeze for longer than the lease and see B take the lock. Then turn on fencing tokens and watch the storage reject the stale write from A.
Does the storage check the fencing token?

A freezes right after taking the lock (a long GC pause, a slow disk or a network stall). It cannot renew the lease while frozen. B retries every second.

Lock service: who owns the lock (token)
A owns (33)
B owns (34)
Client A
frozen, still thinks it owns the lock
✎
Client B
retrying every second
✎
0 s4 s8 s12 s16 s
What the storage received, in time order:
t = 6 s: B writes with token 34 → accepted
t = 9 s: A writes with token 33 → accepted
Lease ended before A wrote?
Yes
A wrote at 9 s, lease 5 s
Last accepted write
A (stale)
Result
Corrupted
A was frozen for 9 s but its lease ended at 5 s, so B was given the lock and wrote. A woke up, still believing it owned the lock, and wrote too. Nothing checked, so the stale write from A replaced B's newer data. Turn on fencing tokens.

07How to Use It / Steps / Implementation

Using distributed locks safely

  1. 1
    First ask: can I avoid the lock?
    A database transaction, a unique key, a conditional write (compare and set) or an idempotent job is often safer and simpler than a lock.
  2. 2
    Pick the right store
    For correctness use a consensus-backed store (etcd, ZooKeeper, Consul). For simple efficiency locks, Redis is often enough.
  3. 3
    Always set a TTL
    Never take a lock with no expiry. A crashed owner would block everyone forever.
  4. 4
    Acquire with one atomic command
    Use SET key value NX PX ttl in Redis, or create-if-absent in etcd. Never check and then set in two steps.
  5. 5
    Store a unique owner value
    Put a random id in the lock. When releasing, delete it only if the value is still yours, using one atomic script.
  6. 6
    Renew while working
    Run a heartbeat that extends the lease while the job runs. Stop the job right away if renewal fails.
  7. 7
    Use fencing tokens for correctness
    Get a rising number with the lock. Send it with every write. The storage rejects any write with a number lower than one it has seen.
  8. 8
    Keep the critical section short
    Do the least possible work under the lock. Do not call slow services while holding it.
💡Release in a finally block
Always release the lock in finally (or with a language-level with block), so an error does not hold it until the TTL.
⚠️Never rely on clocks being exact
Machines have clock drift and clock jumps. Measure how long you hold the lock with a monotonic timer, and give a safety margin before the TTL ends.

08Key Terms to Know

TermMeaning in easy words
MutexA lock that lets one thread at a time into a section of code
Critical sectionThe code that only one owner may run at a time
LeaseA lock that is valid only for a limited time
TTL (time to live)How long a lock record lives before it expires by itself
Acquire / releaseTake the lock, and give it back
Renewal / heartbeatExtending the lease while the owner is still working
Fencing tokenA number that rises with each lock grant. Storage rejects lower numbers
Ephemeral nodeA ZooKeeper entry that is removed when the session of its owner ends
RedlockA Redis algorithm that takes the lock on a majority of independent nodes
DeadlockTwo owners wait for the locks of the other forever
StarvationA waiter that never gets its turn because others keep winning

09Pros, Cons and Trade-offs

✅ Pros
  • Easy idea: one key says whose turn it is
  • Prevents duplicate work and conflicting updates
  • A crashed owner is replaced automatically through the lease
  • Many tools and libraries exist
  • Works across many languages and servers
⚠️ Cons
  • An expired lock can still be used by a paused owner
  • The lock service becomes a dependency and a possible single point of failure
  • Clocks and network delays can break the assumptions
  • Waiting owners add latency and can starve
  • Easy to use as a lazy fix when a transaction would be better

Trade-offs

ChoiceWe gainWe lose
Long TTLFewer expiries during slow workA crashed owner blocks others for longer
Short TTLQuick recovery after a crashA slow owner loses the lock mid-job, so you need renewals
Redis lockSpeed and simplicityWeaker safety on failover or pauses
etcd or ZooKeeper lockStrong safety and tokensMore to run and a little slower
Fencing tokensSafe even with paused ownersThe storage must check tokens, which not all systems can do
No lock, use a conditional writeNo extra system and no expiry problemOnly works if the resource supports it

10Common Problems and Mistakes

Common mistakes

  1. No TTL. A crash leaves the lock held forever.
  2. Releasing someone else's lock. Your lock expired, another server took it, and your delete then removes theirs. Always check the owner value first.
  3. Assuming the lock is still yours. After a long pause, the lease may be gone. Check or use fencing tokens.
  4. Check, then set. Two steps give a gap where two servers both pass the check. Use one atomic command.
  5. Using a single Redis for correctness. A failover can lose the key, and a second owner is granted the lock.
  6. Holding the lock during slow calls. Everyone else waits, and the TTL may run out.
  7. Locking when a unique constraint would do. A database constraint or idempotency key is simpler and safer.

Things to watch

😴Process pauses
Garbage collection or a stalled VM can freeze an owner past its lease.
🕰️Clock problems
Clock jumps and drift can shorten or lengthen a lease.
🔒Deadlock
Always take several locks in the same order, and use timeouts.
🐘Thundering herd
When the lock frees, every waiter retries at once. Use a queue or random backoff.

11Real-World Examples

🐒ZooKeeper and Curator
Lock recipes use ephemeral sequential nodes. Many big data systems used them.
🗂️etcd locks
Used in Kubernetes tooling, with leases and revision numbers.
🔴Redis (Redisson, redis-py lock)
Popular for jobs and cache rebuilds, where an occasional double run is OK.
🐘PostgreSQL advisory locks
Used to make sure only one worker runs a migration or a job.
☁️DynamoDB lock client
Uses conditional writes with a lease and a heartbeat.
☸️Kubernetes Lease
Controllers use a Lease object to hold a lock for leadership.
📝Note
There is a well known debate about whether Redlock is safe for correctness. The common advice: use a lock for efficiency, and for correctness add fencing tokens or use a consensus store.
Mini case: only one server sends the daily emails
🖥️10 serversall wake at 9:00
→↓try lock
🔐Redis lockSET NX, TTL 60 s
→↓1 wins
📧Server 4sends the emails
Lock service The one owner
Ten servers have the same schedule, one gets the lock.

12Related Topics to Read Next

Leader Election→

Keeping a lock alive is a simple way to be the one leader.

Raft→

The consensus that makes etcd locks safe.

Consensus Algorithms→

What a strong lock service is built on.

Idempotency→

Often a better answer than a lock: make doing it twice harmless.

Cache Stampede→

A lock lets one request rebuild the cache.

ACID Transactions→

A database transaction can replace many locks.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: one key in a shared store says which machine may do a job right now.
  • ✔Acquire: one atomic command (SET NX PX), with a unique owner value.
  • ✔TTL: always set it, so a crashed owner frees the lock. Renew while working.
  • ✔Release: only if the value is still yours (atomic check and delete).
  • ✔Danger: a paused owner wakes up after expiry and still writes.
  • ✔Fix: fencing tokens. The storage rejects any write with an old number.
  • ✔Choose: etcd or ZooKeeper for correctness, Redis for efficiency.
  • ✔One line: “A lock is a lease, and a lease can end while you are still working, so check the token.”
← Previous
ZooKeeper and etcd
Next →
Fencing Tokens