One room, one key
An office has one meeting room, and only one team should use it at a time. Each team used to keep a key in its own drawer. That works while there's one team. With two teams there are two drawers and two keys, so both teams walk into the room at once and talk over each other.
The fix is to have one key on one hook by the front door. Whoever wants the room takes the key off the hook. If the hook is empty, someone else has the room, and you wait. Because everybody uses the same hook, nobody can get in while someone else is inside. This shared key is called a distributed lock.
Why in-process locks aren't enough
A synchronized block or a ReentrantLock (see threads and locks) only coordinates
threads inside one JVM. Run two instances of the same service, and each has its own lock object: both can enter
the critical section at the same moment, so a scheduled job runs twice or two requests charge the same order.
A distributed lock moves the lock out of the process into something every instance can reach. Redis (see Redis and Valkey) is a common choice because it runs commands one at a time, is fast, and often already deployed: the lock is just a key. Whoever creates the key holds the lock; everyone else sees it exists and backs off or retries.
Taking the key, with a tag
Taking the key is one quick move: "give me the key, but only if it's on the hook". Two people can't both grab it, because the hook hands it to whoever asked first and tells the other one "taken".
The key comes with a tag. You write your name on it and a time it must be back by, say ten minutes from now. That time is the key's expiry. If you trip on the stairs and never come back, the key doesn't stay lost: when the time on the tag runs out, it goes back on the hook by itself, and the next person can take it.
Acquiring: SET NX PX
Take the lock with one atomic command:
1SET lock:order:42 9f1c6a7e-... NX PX 30000NXsets the key only if it doesn't exist, so exactly one caller getsOKand the others get a null reply.PX 30000gives it a TTL of 30 000 ms (EXtakes seconds). If the holder crashes, Redis deletes the key when the TTL runs out, so a dead process can't block everyone forever.- The value is a token unique to this acquisition, typically a random UUID. It identifies the holder.
Setting and expiring must be one command. The old pattern of SETNX followed by EXPIRE leaves a window where
a crash between the two creates a lock that never expires.
Choose the TTL longer than the work normally takes, with margin. Too short and the lock expires mid-task; too long and a crash blocks others for that long. Losers either fail fast or retry with a small random backoff.
Giving it back, but only yours
Ana takes the key and gets held up. Her time runs out, the key goes back on the hook, and Ben takes it. Then Ana finally walks back and hangs "her" key up, which is really Ben's. Now the hook looks empty while Ben is still in the room, and a third person could walk in on him.
So the rule is: the person at the hook reads the name on the tag first. If it still says Ana, she may hang it up. If it says Ben, Ana's turn is already over and nothing happens. Reading the tag and hanging up the key happen in one go, so nobody can swap the tag in between.
Releasing: compare-and-delete
Releasing with a plain DEL is a bug: if your lock already expired and another client took it, you delete
theirs. Release only if the value is still your token, and do the check and the delete atomically. The usual
way is a Lua script, which Redis runs without interleaving other commands:
1if redis.call("get", KEYS[1]) == ARGV[1] then2return redis.call("del", KEYS[1])3else4return 05end
A GET from the client followed by a DEL would not do: the key could expire and be re-taken between the two
round trips. Redis 8.4 adds DELEX key IFEQ token, which does the same compare-and-delete in one command.
A return value of 0 means you no longer held the lock, which your code should treat as a warning.
When the room goes wrong
Dozing off. Ana takes the key and sits down in the room, then dozes off for twenty minutes. She doesn't know she slept. Her tag ran out, the key went back on the hook, and Ben is now in the room too. Ana wakes up and carries on filing papers as if it were still her turn.
The fix lives in the room itself. Every time the key is lent out, the tag gets a ticket number that only ever goes up, called a fencing token: Ana got 33, Ben got 34. The filing cabinet in the room remembers the highest number it has seen. When Ana wakes and hands it a paper stamped 33, the cabinet says "I've already had 34" and refuses it.
Hanging up someone else's key. If Ana hangs up the key without reading the tag, she cancels Ben's turn. That is why the person at the hook always reads the name first.
A crowd at the door. When Ben hangs the key up, ten people rush the hook at once. Only one gets it, and the rest waste their trip. The office asks people to wait a random moment before trying again, so they don't all arrive together.
Choosing the time on the tag. A short time means a slow worker loses the room mid-task. A long time means a borrower who vanishes blocks everyone for ages. A helper who keeps pushing the time later while you are awake gets the best of both, but can't help if you are asleep. And if the work can safely be done twice, you may not need the key at all.
What can go wrong
A TTL makes the lock a lease: it is only valid for a while, and the holder can't tell exactly when it ran out. Five failures follow from leases, crashes and contention; failover and Redlock get their own topic below.
- A pause outlives the TTL, so two clients act as holders. A stop-the-world GC pause, a suspended VM, page
faults or a slow downstream call stall the holder past its TTL. The lock expires, another client acquires it,
and the first one resumes and keeps writing. Symptom: duplicate or interleaved writes, a failed release, or
unlock()reporting the lock was lost. Checking "do I still hold it?" before each write doesn't help, because the pause can happen right after the check. The fix has to live at the resource: a fencing token is a number that increases with every acquisition. The client sends it with every write, and the storage remembers the highest token it has accepted and rejects anything lower. - Releasing someone else's lock. With a plain
DEL, a client whose lock expired deletes the lock of the client that took it next, and a third client can then enter. Symptom: overlap with no pause in sight. Fix: store a unique token as the value and release with compare-and-delete (see Releasing above). - A crash leaves work half done. The holder dies mid-task and the TTL frees the lock, but the first half of the job is already written. The next holder starts on top of it. Symptom: partial rows, a charge without an order. Fix: make each step idempotent or transactional, so the next holder can finish or redo it.
- Clock jumps change expiry. Redis TTLs use the Redis server's wall clock, so stepping that clock forward (an NTP step, a misbehaving VM) can expire a lock early, and stepping it back keeps a lock alive too long. Symptom: locks vanishing early with no pause on the client. Fix: keep clocks slewed rather than stepped, give TTLs margin, and still use fencing for correctness.
- Contention and thundering herd. When a popular lock is released, every waiter retries at once, and a tight
retry loop hammers Redis. Symptom: spikes in Redis command rate and latency on release, many
nullreplies fromSET NX. Fix: retry with random backoff and jitter, cap the wait withtryLock(wait, unit)(passing a lease time too turns off the watchdog), or use a lock that waits for a release notice instead of polling (Redisson'sRLocksubscribes to a pub/sub channel and wakes one waiter per JVM;RFairLockhands the lock out in arrival order).
A plain Redis SET NX doesn't produce a fencing token; INCR on a counter key in the same Lua script that sets the lock can, as can a lock that provides
one (Redisson's RFencedLock), a database sequence, or a consensus system's revision. Fencing only works if the
resource can check it: a database with a conditional update can, a third-party email API usually can't.
| Choice | You gain | You pay |
|---|---|---|
| Short TTL (a long one flips both columns) | A crashed holder frees the lock quickly | Slow work loses the lock mid-task |
Watchdog renewal (Redisson lock() with no lease time) | The lock lasts as long as the work, and a crash frees it within lockWatchdogTimeout (30 s default) | A background renewal task, and a paused JVM renews nothing |
| Redlock or a consensus store (etcd, ZooKeeper) instead of one primary with a replica | Survives a failover or a minority of nodes; consensus adds fencing numbers and linearizable locks | More nodes to run and slower acquires; Redlock still gives no fencing token or protection from pauses and clock jumps |
| Idempotent design, no lock | Duplicates become harmless, with no lease to expire | Every write must be safe to repeat, which not every operation allows |
Five hooks, and an honest argument
What if the hook itself falls off the wall? A spare hook in the same building might not have heard that the key was taken. So some offices use five hooks in five separate buildings, a plan called Redlock. To book the room you must collect the key from at least three of them, quickly. Nobody else can get three at the same time, so losing one or two hooks for good doesn't stop anyone or let two people in.
Not everyone trusts this. One well-known expert pointed out that it still relies on clocks keeping good time and on nobody dozing too long, and that it hands out no ticket numbers. The inventor replied that, for most offices, those things are rare enough. Even the hook makers' own guide now says: if a double booking would be a disaster, use ticket numbers, or a proper committee that votes on every loan.
Failover, Redlock and the debate
With one Redis primary and an async replica, the lock is lost on failover: a client acquires it on the primary, the primary dies before replicating the key, the replica is promoted, and a second client acquires the same lock.
Redlock, proposed by Redis's creator, uses N independent primaries (typically 5, no replication between
them). The client records the time, tries SET NX PX with the same token on each with a short timeout, and holds
the lock only if it got a majority (N/2 + 1) and the elapsed time is less than the TTL. Its validity is the
TTL minus the elapsed time minus an allowance for clock drift. On failure it releases on all instances.
A node that restarts without its data can let a second client win a majority, so Redlock needs fsync'd persistence or delayed restarts.
Martin Kleppmann's 2016 critique, "How to do distributed locking", argues Redlock is unsafe for correctness: it assumes bounded network delay, bounded process pauses and clocks that don't jump, and it produces no fencing token, so a GC pause or a clock jump can still give two holders. Salvatore Sanfilippo replied that those assumptions are reasonable in practice and that Redlock does not need synchronised clocks, only similar clock rates, and that a pause after acquiring hurts any lease-based lock, not only Redlock. The Redis docs now advise fencing tokens for correctness and note that Redis TTLs use the wall clock, so a clock jump can still give two holders. A fair summary: Redis locks are fine for efficiency (avoiding duplicate work, where a rare overlap costs a bit of waste); for correctness, where overlap corrupts data, add fencing or use something built on consensus.
Use the database's own lock when the resource is rows in a relational database. SELECT ... FOR UPDATE
inside a transaction or a transaction-scoped advisory lock such as PostgreSQL's
pg_advisory_xact_lock holds the lock exactly as long as the transaction; an optimistic
UPDATE ... WHERE version = ? avoids the lock altogether. Neither needs a second system.
Use a consensus system (etcd, ZooKeeper, Consul) for correctness-critical coordination such as leader
election. Their locks are tied to a session or lease that ends when the client stops heartbeating, and they
expose monotonically increasing numbers (etcd's revision, ZooKeeper's zxid or sequential znodes) that work
as fencing tokens. They are slower than Redis and another cluster to run.
Reach for Redis when the lock is about efficiency, it's already in your stack, and an occasional overlap is survivable, or when the resource checks fencing tokens.
Letting a helper fetch the key
You don't have to walk to the hook yourself. A helper does it: you say "get me the room key, wait up to ten seconds for it, and book it for thirty". If you'd rather not guess how long you'll need, the helper can keep going back to the hook while you work and write a later time on the tag, as long as you're still awake. When you finish, it hangs the key back up for you.
Locks from Java: Redisson and Spring Integration
Redisson gives you RLock, which implements java.util.concurrent.locks.Lock, is reentrant, and stores
the holder's identity so only the owner can unlock:
1RLock lock = redisson.getLock("lock:order:42");2if (lock.tryLock(10, 30, TimeUnit.SECONDS)) { // wait up to 10 s, lease 30 s3try {4chargeOrder(42);5} finally {6if (lock.isHeldByCurrentThread()) lock.unlock();7}8}
With an explicit lease time the lock simply expires. Call lock() or tryLock(waitTime, unit) without one
and Redisson's watchdog keeps extending the TTL while the JVM is alive (lockWatchdogTimeout, 30 s by
default). That handles slow work, but not a long pause: a frozen JVM renews nothing, so fencing still matters.
Redisson has deprecated its RedLock object in favour of RLock and RFencedLock.
Spring Integration's RedisLockRegistry hands out plain Lock objects by key, with a registry-wide expiry
(60 s by default):
1@Bean2RedisLockRegistry lockRegistry(RedisConnectionFactory cf) {3return new RedisLockRegistry(cf, "orders", Duration.ofSeconds(30).toMillis());4}56Lock lock = lockRegistry.obtain("42");7if (lock.tryLock(10, TimeUnit.SECONDS)) {8try { chargeOrder(42); } finally { lock.unlock(); }9}
If the lock expired before unlock(), it throws ConcurrentModificationException (IllegalStateException before Spring Integration 6.4): the protected work may have overlapped
with another holder, so log it loudly.