Distributed Locks & Leases
- Distinguish locks for efficiency from locks for correctness, and recognize when no lock is needed at all
- Implement a Redis lock correctly (token,
SET NX PX, compare-and-delete) and explain its failure modes - Summarize the Redlock debate between Martin Kleppmann and Salvatore Sanfilippo (antirez) and what it means for your design
- Use leases with fencing tokens, and etcd/ZooKeeper lock recipes, for correctness-critical mutual exclusion
- Use database row locks and advisory locks when the protected data lives in the same database
TL;DR
- Ask first: do you need a lock, or an atomic conditional write? Most money and stock problems are solved by
UPDATE … WHERE balance >= $amount, unique constraints, optimistic versioning or a single writer per key. - Efficiency locks (avoid doing the same work twice; a rare double execution is tolerable) are fine on a single Redis instance with
SET key token NX PX ttl. - Correctness locks (double execution corrupts data or moves money twice) need a consensus-backed lock service (etcd, ZooKeeper, Consul) and fencing tokens checked by the resource.
- Every distributed lock is really a lease: it expires. A GC pause, VM stall or network delay can make the holder act after expiry. Only the protected resource can reject a stale holder — via a monotonically increasing fencing token.
- Redlock (lock on a majority of independent Redis nodes) depends on timing assumptions and provides no fencing token; Kleppmann argued it is unsafe for correctness, antirez disagreed. Practical takeaway: don't use it where correctness depends on the lock.
- When the data you protect lives in one database, a database lock (
SELECT … FOR UPDATE, advisory locks) shares fate with the data and needs no fencing — often the best option.
Why it matters
A bank runs a merchant payout job on six instances. If two instances process the same merchant's payout batch, the merchant gets paid twice and the bank must claw the money back. A team adds a Redis lock with a 30-second TTL. One day a stop-the-world GC pause on instance A lasts 40 seconds. A's lock expires, instance B acquires it and starts the payout, then A wakes up — still believing it holds the lock — and sends its payout file too.
In e-commerce, the opposite mistake is common: a flash sale protects stock with a distributed lock per SKU. Every purchase now serializes through a network round trip to the lock service, throughput collapses to a few hundred orders per second for the hottest SKU, and the lock service becomes the bottleneck — when an atomic decrement would have done the job (see Inventory & Flash Sales).
Interviewers ask about distributed locks to see whether you know their limits: leases, pauses, fencing, and when not to use one.
Core concepts
Efficiency vs correctness
Martin Kleppmann's framing is the most useful one:
- Efficiency: the lock prevents wasted work — e.g., two instances regenerating the same product-feed export or warming the same cache. If the lock occasionally fails and the work happens twice, you lose a little compute.
- Correctness: the lock prevents corruption — e.g., two payout runs, two concurrent balance adjustments, two allocations of the same IBAN or seat. If the lock fails, money or data is wrong.
The bar for correctness is much higher, and most designs that need correctness can avoid relying on a lock entirely.
When you don't need a lock
Patterns that replace locks:
- Conditional writes:
UPDATE accounts SET balance = balance - 200 WHERE id = 42 AND balance >= 200— check the affected row count. Atomic, no lock service. - Optimistic concurrency: read
version, writeWHERE version = $read, retry on conflict. - Unique constraints: allocation of a voucher code or reference is an
INSERTthat only one caller can win. - Single writer: route all operations for an account to one Kafka partition and one consumer thread; ordering and exclusion come for free.
- Idempotency: if the operation is idempotent, running it twice is harmless — see Idempotency & Exactly-Once.
Redis: SET NX PX
The single-instance Redis lock, done correctly:
SET lock:payout:merchant-981 3f2c9e1a-... NX PX 30000
NX: only set if the key does not exist (acquire).PX 30000: expire after 30 s, so a crashed holder doesn't block forever.- The value is a random token unique to this holder, so you only release your own lock.
Release must be atomic compare-and-delete (a Lua script), otherwise you may delete a lock that expired and was re-acquired by someone else:
package lock
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"time"
"github.com/redis/go-redis/v9"
)
var ErrNotAcquired = errors.New("lock: not acquired")
var releaseScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0`)
type Lock struct {
rdb *redis.Client
key string
token string
}
func Acquire(ctx context.Context, rdb *redis.Client, key string, ttl time.Duration) (*Lock, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return nil, err
}
token := hex.EncodeToString(b)
ok, err := rdb.SetNX(ctx, key, token, ttl).Result()
if err != nil {
return nil, err
}
if !ok {
return nil, ErrNotAcquired
}
return &Lock{rdb: rdb, key: key, token: token}, nil
}
func (l *Lock) Release(ctx context.Context) error {
return releaseScript.Run(ctx, l.rdb, []string{l.key}, l.token).Err()
}
Failure modes of this approach:
- Expiry while working: if the work takes longer than the TTL (or the process pauses), the lock expires and someone else acquires it. Renewing ("watchdog" extension with a compare-and-
PEXPIREscript) reduces but doesn't remove the risk — a paused process can't renew. - Failover loses locks: Redis replication is asynchronous. A lock written to the primary can be lost if the primary fails before replicating; the promoted replica lets a second client acquire it.
- No ordering: a random token tells you who holds the lock, not which grant is newer, so the resource can't reject a stale holder.
For efficiency locks these are acceptable. For correctness they are not.
Redlock and the debate
Redlock, proposed by antirez, uses N (typically 5) independent Redis primaries. A client tries SET NX PX on all of them with the same token, and holds the lock if it succeeds on a majority within a time well under the TTL; the remaining validity is the TTL minus the elapsed acquisition time minus an allowance for clock drift.
In 2016, Martin Kleppmann's post "How to do distributed locking" argued Redlock is unsuitable for correctness:
- No fencing tokens. Like any lease, the holder can be paused (GC, page faults, VM migration) or its messages delayed past expiry. Without a monotonically increasing token, the resource cannot tell a stale holder from the current one.
- Timing assumptions. Safety depends on bounded network delay, bounded process pauses and bounded clock drift. If one Redis node's clock jumps forward, its key expires early, and two clients can each hold a majority.
antirez replied in "Is Redlock safe?" that: the random token can be used for check-and-set at the resource; a system able to check fencing tokens linearizably may barely need a lock at all; the post-acquisition elapsed-time check handles delays during acquisition; and clock jumps can be prevented operationally (no manual changes, slewing NTP, monotonic time). The two never fully converged.
What an architect should take from it:
- If double execution is merely wasteful, a single Redis lock is simpler than Redlock and good enough.
- If double execution corrupts money or data, use a consensus-based lock service and make the resource enforce fencing (or, better, make the operation itself conditional/idempotent). Redlock gives you neither the linearizable foundation nor the token.
Leases and fencing tokens
Every lock with a timeout is a lease: the holder has the right to act until a deadline. Rules for using leases safely:
- Check remaining lease time with a monotonic clock, and stop well before expiry (safety margin for drift and in-flight requests).
- Renew in the background, and abort work (cancel contexts) when renewal fails.
- Accept that this still cannot prevent a paused process from acting late — hence fencing.
The resource stores the highest token it has seen per protected key and rejects lower ones:
UPDATE merchant_payout_state
SET fence_token = $2, batch_id = $3, status = 'RUNNING'
WHERE merchant_id = $1 AND fence_token < $2;
-- 0 rows affected => a newer holder exists; abort
If the resource cannot check tokens (an external bank API, an SFTP drop), you cannot fully fence it — compensate with idempotency at that boundary (a deterministic batch reference the receiver deduplicates) and reconciliation.
etcd locks
etcd gives you the right primitives: leases (TTL, kept alive by the client), transactions (compare-and-swap), revisions (a cluster-wide, monotonically increasing counter) and watches. The concurrency package's Mutex:
- Creates a key under the lock prefix attached to the session's lease. Its create revision orders waiters.
- The waiter with the lowest create revision holds the lock; others watch the key just before theirs.
- If the holder's session lease expires (process dead or partitioned), etcd deletes its key and the next waiter proceeds.
- The holder's key revision is a natural fencing token.
func withPayoutLock(ctx context.Context, cli *clientv3.Client, merchantID string,
fn func(ctx context.Context, fence int64) error) error {
sess, err := concurrency.NewSession(cli, concurrency.WithTTL(15))
if err != nil {
return err
}
defer sess.Close()
m := concurrency.NewMutex(sess, "/locks/payout/"+merchantID)
if err := m.Lock(ctx); err != nil {
return err
}
defer m.Unlock(context.WithoutCancel(ctx))
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
<-sess.Done() // lease lost
cancel()
}()
return fn(ctx, m.Header().Revision) // pass as fencing token to the payout store
}
Because etcd is Raft-replicated and linearizable, a lock grant cannot be lost by failover in the way an async-replicated Redis key can. Consul sessions provide a similar mechanism.
ZooKeeper locks
The classic recipe (implemented by Apache Curator's InterProcessMutex):
- Each contender creates an ephemeral sequential znode, e.g.,
/locks/payout-981/lock-0000000042. - The one with the lowest sequence number holds the lock.
- Each other contender watches only its predecessor (avoiding a thundering herd when the lock is released).
- If the holder's session expires, its ephemeral node is deleted automatically.
- The znode's zxid (or sequence number) can serve as a fencing token.
Database locks
When the protected state lives in a single database, use the database:
- Row locks:
SELECT … FROM accounts WHERE id = $1 FOR UPDATEinside a transaction serializes writers to that row; the lock is released on commit or rollback — it cannot outlive the transaction or be held by a paused process after the transaction aborts. AddNOWAITto fail fast, orSKIP LOCKEDfor work queues ("claim the next unclaimed job"). - Advisory locks (PostgreSQL):
pg_advisory_xact_lock(hashtext('payout:981'))takes an application-defined lock tied to the transaction;pg_try_advisory_lockreturns immediately. Prefer the transaction-scoped variants; session-scoped advisory locks interact badly with connection poolers in transaction mode (the lock stays on a pooled connection someone else now uses). - MySQL:
GET_LOCK('payout:981', 5)for named locks;SELECT … FOR UPDATEfor rows.
The big advantage: the lock and the data share fate. The write that the lock protects commits in the same transaction, so there is no window for a stale holder. The cost: lock waits hold connections; heavy contention on a hot row serializes throughput (see Locking & Concurrency Control).
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| No lock: conditional write / constraint | Atomic, fast, no extra system | Must fit a single-row or single-DB condition | Balance debits, stock decrements, unique allocations |
| Single writer per key | No contention logic; natural ordering | Requires partitioned routing; hot keys limit throughput | Per-account ledgers, per-SKU stock, order state |
Redis SET NX PX | Simple, fast, cheap | Lost on failover; expiry under pauses; no fencing | Efficiency: dedupe jobs, cache stampede protection |
| Redlock | Survives some Redis node failures | Timing assumptions; no fencing; debated safety | Rarely the best choice; efficiency at most |
| etcd / ZooKeeper / Consul lease + fencing | Linearizable grants; monotonic tokens; auto-release on session loss | Extra infrastructure; latency of consensus; still needs resource-side fencing | Correctness-critical singleton work across services |
DB row lock (FOR UPDATE) | Shares fate with data; no fencing needed | Contention holds connections; same database only | Read-modify-write on rows you then update |
| DB advisory lock | Named locks without a table; transaction-scoped | Same database only; pooling pitfalls for session locks | Serializing jobs or migrations that touch one DB |
In practice
- TTL sizing: choose a TTL several times longer than the expected critical section, and renew at about a third of the TTL. Cap the critical section with a context deadline shorter than the TTL.
- Abort on lease loss: wire lease loss to context cancellation (as in the etcd example) so in-flight database calls are cancelled.
- Hot-key locks are a smell: if one key's lock is contended thousands of times per second, redesign — atomic counters, sharded stock buckets, or a queue per key.
- Cache stampede protection is the classic good use of a Redis lock: one request recomputes an expired product page while others serve stale (see Caching).
- Observability: emit metrics for lock wait time, hold time, acquisition failures and lease losses; alert on lease losses for correctness-critical locks — each one is a near miss.
- Rough numbers (approximate): a Redis
SET NXround trip inside a data center is sub-millisecond; an etcd lock acquisition costs a Raft commit (a few ms within one region). Neither belongs on a per-request hot path at high throughput.
Common pitfalls
DELwithout checking the token. Worker A's lock expires, B acquires, A finishes and deletes B's lock; C acquires while B is still working. Symptom: occasional double processing.SETNXthenEXPIREas two commands. A crash in between leaves a lock that never expires. Use the singleSET … NX PXcommand.- Lock TTL shorter than the work. Symptom: double execution under load, when work slows down.
- Assuming the lock protects an external side effect. The payout file is sent after the lease expired. Fencing or idempotency at the receiver is required.
- Redis lock for money movement. Works for months; fails during a Redis failover or a long GC pause. Symptom: rare duplicate transfers.
- Session advisory locks behind PgBouncer. Symptom: locks "held" by connections nobody owns; jobs stall.
- Distributed lock instead of a conditional update. Symptom: a lock service at 100% CPU during a flash sale while the database is idle.
Interview angle
- Typical prompts: "Ensure a payout runs only once." "Prevent two concurrent withdrawals from overdrawing an account." "How would you implement a distributed lock with Redis — is it safe?"
- Strong answer: challenge the need for a lock (conditional update for the withdrawal); for singleton work use etcd/ZooKeeper leases with fencing tokens checked by the payout store, plus an idempotent batch reference; explain the GC-pause scenario; mention Redlock's debate and that you'd only use Redis locks for efficiency.
- Follow-ups: "What's a fencing token and who checks it?" "What happens when Redis fails over?" "How do you choose the TTL?" "What if the resource can't check tokens?"
- Red flags:
SETNX+EXPIRE; releasing without token check; claiming a lock guarantees mutual exclusion in the presence of pauses; using a lock per SKU in a flash sale.
Self-check
1. Why is every distributed lock effectively a lease, and what problem does that create?
A lock service must eventually release a lock whose holder crashed, so locks expire. But the service can't distinguish a crashed holder from a paused or slow one. A paused holder can wake after expiry, still believing it holds the lock, and act concurrently with the new holder.
2. What is a fencing token, and why must the resource check it rather than the client?
A number that increases with every lock grant (e.g., an etcd revision). The client is the party that may be wrong about whether it still holds the lock, so it can't be trusted to check. The resource sees the actual sequence of writes, remembers the highest token, and rejects any write with a lower one.
3. Summarize Kleppmann's two main objections to Redlock.
It doesn't produce fencing tokens, so it can't protect against holders acting after expiry due to pauses or delays. And its safety depends on timing assumptions — bounded delays, pauses and clock drift — so a clock jump on one Redis node can let two clients both believe they hold a majority.
4. Scenario: two withdrawals of $700 hit an account with $1,000 at the same time. Do you need a distributed lock?
No. Make the debit a single conditional write in the ledger database: UPDATE accounts SET balance = balance - 700 WHERE id = $1 AND balance >= 700, check rows affected, and insert the ledger entries in the same transaction (or lock the row with SELECT … FOR UPDATE). The database serializes the two; one succeeds and one fails for insufficient funds.
5. How does the ZooKeeper lock recipe avoid a thundering herd?
Each contender creates an ephemeral sequential znode and watches only the node immediately before its own, not the lock holder. When the holder releases, only the next contender is notified, rather than all waiters racing to acquire.
6. Why is a database row lock often safer than an external lock service?
The lock lives in the same transaction as the write it protects, so it shares fate with the data: if the holder stalls and its transaction aborts, its writes are rolled back too, and it cannot commit after losing the lock. There is no separate system whose state can diverge, so no fencing is needed.
Exercise
Reproduce the GC-pause failure and fix it:
- Implement a payout worker in Go that acquires a Redis lock (TTL 5 s), sleeps 8 s inside the critical section to simulate a pause, then writes a payout batch row.
- Run two workers and show that both write a batch for the same merchant.
- Replace the Redis lock with an etcd mutex, pass
Header().Revisionas a fencing token, and change the payout store write to the conditionalUPDATE … WHERE fence_token < $2. Show that the stale worker's write is rejected. - Finally, replace the whole lock with a
UNIQUE (merchant_id, payout_date)constraint and argue whether you still need the lock.
Done when: you can demonstrate the double payout, demonstrate fencing preventing it, and write a short ADR choosing between fencing and a unique constraint for this job.
Further reading
- Martin Kleppmann, "How to do distributed locking" (blog, 2016).
- Salvatore Sanfilippo (antirez), "Is Redlock safe?" (blog, 2016).
- Redis documentation: "Distributed Locks with Redis" (Redlock description) and the
SETcommand. - Mike Burrows, "The Chubby lock service for loosely-coupled distributed systems" (OSDI 2006).
- Apache ZooKeeper documentation: "ZooKeeper Recipes and Solutions" (locks).
- etcd documentation and
go.etcd.io/etcd/client/v3/concurrencypackage docs. - PostgreSQL documentation: "Explicit Locking" (row-level and advisory locks).
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 8 (process pauses, fencing).
Related
- Time, Clocks & Ordering — why leases depend on clocks and pauses.
- Consensus & Raft — the foundation under etcd and ZooKeeper locks.
- Locking & Concurrency Control — row locks, deadlocks, optimistic concurrency.
- Redis Deep Dive — replication and persistence behavior behind Redis locks.
- Inventory & Flash Sales — atomic decrements instead of per-SKU locks.
- Idempotency & Exactly-Once — making double execution harmless.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).