TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท redis ยท locking ยท concurrency ยท distributed systems

Distributed locks with Redis

How several servers take turns on a shared resource using a Redis key as a lock. SET with NX and PX takes it, a token check releases it, the TTL frees it after a crash, and fencing tokens protect against holders that outlive their lease.

14 min6 animations

๐Ÿ“š Builds on๐Ÿ–Š๏ธ Threads, locks and race conditions๐ŸŽฝ Redis and Valkey

๐Ÿ–จ๏ธ Cheat sheet

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.

In-process locks vs one shared lock4 steps
๐Ÿ‘ฉAna๐Ÿ—๏ธAna's drawer key๐Ÿ‘จBen๐Ÿ—๏ธBen's drawer key๐ŸšชMeeting room
Press play and watch it happen!

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 30000
  • NX sets the key only if it doesn't exist, so exactly one caller gets OK and the others get a null reply.
  • PX 30000 gives it a TTL of 30 000 ms (EX takes 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.

Taking the lock with SET NX PX5 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐ŸชKey hook
Press play and watch it happen!

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] then2    return redis.call("del", KEYS[1])3else4    return 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.

Releasing only your own lock4 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐ŸชKey hook
Press play and watch it happen!

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 null replies from SET NX. Fix: retry with random backoff and jitter, cap the wait with tryLock(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's RLock subscribes to a pub/sub channel and wakes one waiter per JVM; RFairLock hands 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.

ChoiceYou gainYou pay
Short TTL (a long one flips both columns)A crashed holder frees the lock quicklySlow 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 replicaSurvives a failover or a minority of nodes; consensus adds fencing numbers and linearizable locksMore nodes to run and slower acquires; Redlock still gives no fencing token or protection from pauses and clock jumps
Idempotent design, no lockDuplicates become harmless, with no lease to expireEvery write must be safe to repeat, which not every operation allows
A paused holder and a fencing token5 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐ŸชKey hook๐Ÿ—„๏ธFiling cabinet
Press play and watch it happen!

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.

Redlock across five independent nodes4 steps
๐Ÿ‘ฉAna๐ŸชHook 1๐ŸชHook 2๐ŸชHook 3๐ŸชHook 4๐ŸชHook 5
Press play and watch it happen!
๐Ÿ”ง Going deeper

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 s3    try {4        chargeOrder(42);5    } finally {6        if (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) {3    return new RedisLockRegistry(cf, "orders", Duration.ofSeconds(30).toMillis());4}5 6Lock lock = lockRegistry.obtain("42");7if (lock.tryLock(10, TimeUnit.SECONDS)) {8    try { 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.

Redisson RLock with the watchdog4 steps
๐Ÿง‘โ€๐Ÿ’ผYou๐Ÿง‘โ€๐Ÿ”งHelper๐ŸชKey hook
Press play and watch it happen!

๐Ÿ”Ž Spot it in real code

This is the shared meeting-room key as real Java code. One borrower takes the key off the hook, does their work and hangs the key back. Pick a label, then tap the line where that happens.

Tap the line where you see: Your name on the tag.

0 of 5 placed

๐Ÿงฉ Finish the code

Set up the key yourself. One borrower at a time fills in the daily report, page by page. A borrower who finds the key taken must not wait, and a key not returned goes back on the hook by itself after thirty seconds. The ticket number must come with the key. The filing cabinet must refuse a page from an old borrower, but accept every page from the current one. When the work is done, the key goes straight back, without a fuss if the time on the tag already ran out. Pick the code for each gap.
  1. 1 Don't wait at the hook, give the key a thirty second time limit, and get its ticket number
  2. 2 The cabinet accepts a page only if its ticket number is not older than the one it has
  3. 3 Hang the key up only if the tag is still yours
1RFencedLock lock = redisson.getFencedLock("lock:report");2Long fence = lock.1;3if (fence != null) {4    try {5        for (String section : sections) {6            jdbc.update("UPDATE report SET body = body || ?, fence = ? "7                    + "WHERE id = 1 AND fence 2 ?", section, fence, fence);8        }9    } finally {10        if (lock.3) lock.unlock();11    }12}
0 of 3 gaps filled

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐ŸŽŸ๏ธDesign ticket bookingSell every seat exactly once while a million fans hit refresh.practice problem

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Distributed locks with Redis, told the same way as the story.
  1. Two teams each keep a room key in their own drawer. Why do they still end up in the room together?
  2. Ana's turn ran out and Ben now has the key. Ana comes back and hangs up the key. What should happen?
  3. Why does the key come with a time it must be back by?
  4. Ana dozes off in the room past her time, and Ben takes the key. What stops Ana's papers from mixing with Ben's when she wakes?
  5. Ben holds the key in the room. The hook that hands out keys is replaced by a spare that never heard Ben took it. What can happen?
Answer every question to check.Passing marks Distributed locks with Redis as done.
Got the hang of Distributed locks with Redis? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿงฐ Caching with Redis, Valkey and HazelcastStep 5 of 8

โ† Previous on the path๐Ÿซ Redis ClusterNext on the path โ†’๐Ÿ“ป Redis Streams and pub/sub