SteelReed

Search

Search posts, questions…

7. System Design

Reviewing a Redis distributed lock: six common bugs

A close read of a sample Redis distributed lock: a constant lock value with a blind DEL, a TTL multiplied by 1000 twice, parallel multi-key acquisition, async unlock, a broken retry loop, and leases that expire during failover. The rewrite, fencing tokens, and when to use the database's locks instead.

18 Nov 20268 min readSenior

–

1. The problem

A booking project's RedisService.lock(key) is setIfAbsent(key, 1, ttl) and unlock(key) is delete(key). A takes the lock with a 200 ms TTL, then hits a 300 ms GC pause; the lock expires and B takes it; A wakes up and unlock deletes B's lock; C takes it. B and C are both in the critical section.

2. Key idea

The first review question (after Martin Kleppmann): is this lock for efficiency (two pods sending the same email: failure wastes resources) or correctness (selling one seat to two people: failure corrupts data)?

A Redis lock is a timed reservation ticket: when time's up someone else can take it, even if you're not done. The correct primitive:

  • Acquire: SET lock:order:42 <random token> NX PX 30000, one atomic command.
  • Release and extend: a Lua script that checks the token first (if GET == token then DEL).

Even with every code bug fixed, the lock is still a lease: a client paused longer than the TTL, or a failover (the promoted replica lacks the lock because replication is asynchronous), gives two holders. The real fix is a fencing token: each acquisition gets an increasing number, and the resource rejects writes carrying an older number than it has seen.

2.1 What should do the locking?

Mechanism Use when Don't use when
Conditional statements, unique constraints, version writing the DB row itself: try this first the work lies outside the DB
SELECT ... FOR UPDATE, advisory locks read then decide within one transaction holding the lock across an external API call
A single-node Redis lock + token efficiency locks: jobs across pods correctness locks without fencing
Redis lock + fencing token work outside a DB transaction that must be correct the resource can't check tokens

3. In Java

JAVA
try (var lease = lock.tryAcquire("order:" + orderId, Duration.ofSeconds(30), Duration.ofSeconds(2))
        .orElseThrow(() -> new OrderBusyException(orderId))) {      // busy -> 409
    // critical section: short, every outbound call has a timeout
    int rows = jdbc.update("""
        UPDATE seat SET holder = ?, fence = ? WHERE id = ? AND fence < ?""",
        userId, lease.fence(), seatId, lease.fence());              // fencing token at the resource
    if (rows == 0) throw new StaleLeaseException(seatId);           // stale token: someone else wrote
}   // close(): Lua compares the token then DELs, synchronously
// B writes with token 2: true; A wakes up and writes with token 1: false

Lease is AutoCloseable, so you can't forget to release it. If Redis fails, tryAcquire throws rather than returning "busy". Redisson (RLock) has per-thread tokens and a renewing watchdog, but still doesn't do fencing for you.

Five common code bugs, Redlock and Redisson
Bug Consequence Fix
Constant value + DEL with no token check deletes other people's locks random token + Lua
TTL multiplied by 1000 twice ttl: 300000 (5 minutes) becomes 9.5 years Duration in @ConfigurationProperties (ttl: 30s)
Several locks in parallel, no order crossed holds, livelock; on failure releases locks it never got sort keys, acquire sequentially; or an all-or-nothing Lua script
Asynchronous unlock on a thread pool lock still held after the method returns, errors unseen synchronous unlock in finally
A retry loop that swallows errors, no jitter pointless sleeping, Redis errors become "busy" a deadline + jitter, throw exceptions
  • Redlock (locking a majority of N independent nodes) handles failover if its assumptions about clocks and delays hold. Kleppmann showed it can't save a paused client: no time-based lock can.
  • Redisson's watchdog renews every lockWatchdogTimeout/3 (30 seconds by default) when no lease time is set. It lowers the risk of expiry for long work, but when the JVM pauses, the watchdog pauses too.
  • Measured: a Redis lock with a 5 ms TTL around 10 ms of work sold 311 tickets for a 100-seat flight; adding a version check on write (acting as a fencing token) sold exactly 100.
  • Multiple locks on Cluster in one Lua script: every key must share a slot, so use hash tags {flight:9}:seat:1.
  • newCachedThreadPool has no thread limit: when Redis is slow, every release adds a thread until the service runs out.

4. Working with AI

Delegate to AI: a RedisLock class with tokens and Lua, a pause scenario test (200 ms TTL, 300 ms sleep), a test with two requests whose lock sets overlap.

Check yourself:

  • The lock value is a random token; unlock and extend compare it in Lua.
  • The TTL is a Duration with units, not a hand-multiplied long.
  • Multiple locks are acquired in sorted order; on failure, only held locks are released.
  • Unlock is synchronous in finally or try-with-resources.
  • Correctness locks have a fencing token, or are replaced by a conditional statement in the DB.

5. Exercises

Exercise 1: Choose the locking mechanism for seat holds

An API holds 1–4 seats per request; seats live in seat(flight_id, seat_no, holder, held_until) on PostgreSQL. AI proposes "a Redis lock per seat". Is it needed?

Solution to Exercise 1

No. Holding seats is writing those very DB rows, so let the DB lock them:

SQL
BEGIN;
SELECT seat_no FROM seat
WHERE flight_id = :f AND seat_no = ANY(:seats) AND (holder IS NULL OR held_until < now())
ORDER BY seat_no            -- fixed order: no deadlocks between overlapping requests
FOR UPDATE;
-- enough seats: UPDATE ... SET holder = :user, held_until = now() + interval '10 minutes'; otherwise ROLLBACK
COMMIT;

For one seat, a single UPDATE ... WHERE holder IS NULL plus a row-count check is enough. A Redis lock is only needed if holding seats also calls an external system outside the transaction; then add a fencing token stored in the seat table.

Exercise 2: Read a lock-stuck-all-night incident

After a pod was OOM-killed at 23:00, every booking request for flight FA634 returns "busy" until morning. PTTL lock:flight:FA634 returns 299999987654. The config says ttl: 300000, and the code does lockTTL = ttlInSecond * 1000 and then lock(key, lockTTL * 1000). Diagnose, act now, fix the root cause.

Solution to Exercise 2
  • Diagnosis: the TTL is multiplied by 1000 twice: 300,000 ms becomes 300,000,000,000 ms (~9.5 years). The pod died holding the lock, so nobody released it.
  • Now: DEL lock:flight:FA634 once you're sure nobody is processing that flight; scan lock:* keys for absurd PTTLs.
  • Root fix: configure a Duration (ttl: 30s), with @Validated bounds from 1 second to a few minutes so a wrong config stops the app from starting; a test that reads PTTL right after acquiring.

Summary

  • Acquire with SET token NX PX; release and extend with a token-checking Lua script.
  • Multiple locks: sorted order, release only what you hold.
  • TTLs are Durations with units; unlock synchronously.
  • A Redis lock is a lease: correctness locks need a fencing token.
  • For DB rows, use the DB's mechanisms, not a Redis lock.

Further reading: Optimistic and pessimistic locking.

Practice interview questions on this topic

All Caching & Redis questions →

Loading comments…
Next on the roadmapCaching in system design: cache tiers, the limits of Redis, and a 1-million-QPS counter case study