Part 8 of 12 · Databases

Why isn't a Redis lock enough?

A Redis lock is a lease: it expires whether or not its holder is done. Measured with Redis 7.4 and PostgreSQL 17: a paused holder overwriting newer data, a release that frees someone else's lock, a cron job running twice, and what fixes each.

A chain and padlock across a green wooden door

The verdict, which the reconstructions below will earn: because a Redis lock is a lease. It expires after its TTL whether or not the holder has finished. If the holder pauses for longer than the TTL (a GC pause, a VM migration, a slow disk, a network blip), someone else takes the lock, and for a while two processes both believe they hold it. Neither process can tell this is happening. The fixes:

  • Make the resource reject stale holders with a fencing token.
  • Take the lock in the same database you write to: a PostgreSQL advisory lock or row lock lives and dies with the transaction.
  • Claim the work with a unique row instead of locking around it.

Case file

The case A job guarded by a lock ran twice, and customers got two invoices
Suspects The job code, a broken release, a missing “still mine?” check
Culprit The lock is a lease: a paused holder wakes up after its TTL and still writes
The fix Fencing tokens, a PostgreSQL advisory lock in the writing transaction, or claim a row
Evidence Redis 7.4 and PostgreSQL 17.11 (make dlock)

The case #

The job was guarded by a lock. The lock worked in every test. And yet the job ran twice, and two customers got two invoices each. Who let the second process in?

This case changes how you think about time in distributed systems. The bug isn’t in anyone’s code; it lives in the gap between “I checked” and “I acted”, and once you see that gap you start spotting it everywhere.

A Redis lock is fine for efficiency (don’t do the same work twice, usually). It isn’t enough for correctness (never do it twice). I reproduced each failure with Redis 7.4 and PostgreSQL 17. The evidence is in database-tradeoffs-lab, and make dlock reruns every number below.

The suspects at a glance #

Redis lease (SET NX PX) Lease + fencing token PostgreSQL advisory lock Claim a row (INSERT … ON CONFLICT DO NOTHING)
Held until The TTL runs out The TTL runs out, but stale holders are rejected at write time The transaction (or session) ends Forever: the row is the record of who took it
Paused holder Wakes up and overwrites newer data Its write is rejected Keeps the lock; everyone else waits Nothing to lose: the work is already claimed
Holder dies Lock frees itself after the TTL Same Lock freed when the connection drops, and its uncommitted writes are rolled back Claim stays; needs a lease column to reclaim
Costs Correctness under pauses Every resource must check the token Locks only things in that database; a hung holder blocks others A table; reclaim logic for crashed claimers
Pick it when Avoiding duplicate work (stampedes, rate of polling) You must use a lease and the resource can compare a number The protected work writes to the same PostgreSQL “Run once per X” jobs and work queues

Use case 1: the paused holder (any job that writes) #

Here’s the reconstruction, scripted step by step so it happens on every run:

  1. A takes the lock with a 200 ms lease.
  2. A pauses for 250 ms. The lease expires.
  3. B takes the lock and writes.
  4. A wakes up, still believing it holds the lock, and writes.
Strategy B got the lock while A thought it held it A’s write after the pause Final value
Redis lock (SET NX PX), safe release yes applied: overwrote B’s newer write A’s (stale)
Redis lock + fencing token yes rejected: token 1 < 2 B’s
PostgreSQL advisory lock in the writing transaction no applied, safely: A still held the lock; B waited and went second B’s
Advisory lock, A’s connection killed during the pause yes failed: A’s transaction died with its connection B’s

The first row is the crime, and the unsettling part is that nothing in A’s code is wrong: it took the lock, did its work and wrote. It can’t know that time passed. The obvious fix is a false lead: checking “do I still hold the lock?” before writing doesn’t help, because the pause can happen between the check and the write.

Sequence diagram: 200 ms leaseSequence diagram: 200 ms lease
Diagram source
sequenceDiagram
  participant A
  participant R as Redis
  participant B
  participant DB as Resource
  A->>R: SET NX PX (200 ms lease)
  Note over A: pauses 250 ms
  R->>R: lease expires
  B->>R: SET NX PX, granted
  B->>DB: write
  A->>DB: wakes up, writes stale data

Fencing tokens fix it when the resource can help. Every time the lock is granted, also hand out a number that only grows (INCR in Redis), and make every write carry it:

UPDATE resource SET value = $1, fence = $2
WHERE id = 1 AND fence < $2;   -- a holder with an older token changes nothing

The catch: every resource the holder touches must check the token. A database row can. An email, a call to a payment provider or a file in S3 usually can’t, unless it accepts an idempotency key, which is the same idea under another name (the payments case builds on it).

An advisory lock sidesteps the problem entirely because it isn’t a lease. pg_advisory_xact_lock(key) is held by the transaction until it commits or rolls back. A paused holder keeps it, so B waits. If A’s connection dies instead (row 4: a network partition, or the server cutting off an idle transaction), PostgreSQL releases the lock and rolls back A’s transaction together. A’s late write fails with the connection. Its lock and its writes can’t come apart, and that is the property a Redis lock can’t give you about a PostgreSQL write. I find that genuinely elegant: the problem isn’t solved so much as made impossible.

Use case 2: the release that frees someone else’s lock #

A common hand-written unlock is DEL lock. Replay the same story, but this time A releases at the end:

Release C can take the lock while B is still working
DEL lock yes: A deleted B’s lock
Compare-and-delete in Lua no

Store a random owner ID as the value and release only if it’s still yours, atomically:

if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
return 0

This is in the Redis documentation’s own locking pattern, and it’s the least you need. It stops A from freeing B’s lock; it doesn’t stop A from writing after its lease expired. That’s use case 1.

Use case 3: a cron job that must run once #

The scene: the same job (send invoices, roll up yesterday’s numbers) is scheduled on every instance of an app, and each instance tries to take a lock first. In the demo:

  • 3 instances start up to 50 ms apart, because clocks and schedulers never fire at exactly the same moment;
  • the job takes 5 ms;
  • 10% of executions pause for 60 ms, past a 30 ms lease;
  • every strategy also checks “has this run already been done?” before working, as real jobs do.
Strategy Runs where the job ran twice (of 300)
Redis lock + “already done?” check 6-16 (three runs)
PostgreSQL advisory lock + check, in one transaction 0
Claim the run: INSERT INTO claims (run_id) … ON CONFLICT DO NOTHING 0
Chart: Double runs of 300 (worst of three runs)Chart: Double runs of 300 (worst of three runs)
Diagram source
xychart-beta
  title "Double runs of 300 (worst of three runs)"
  x-axis ["Redis lock + check", "Advisory lock + check", "Claim a row"]
  y-axis "double runs"
  bar [16 , 0 , 0]

With the Redis lock, roughly one pause in three turned into a double run. Here’s how it happened. Instance A was paused past its lease. Instance B started late, took the expired lock, checked “done?”, saw no record because A hadn’t written it yet, and ran the job again. If the job sends invoices, those are duplicate invoices.

The two fixes that held up:

  • Advisory lock and done-check in one transaction. B can’t get the lock while A’s transaction is open. Once A commits, B sees the run is done and skips it.
  • Claiming the run with a unique row. This needs no lock at all: the INSERT either creates the claim or finds it already there, in one atomic step. It’s the simplest of the three, and the one I’d reach for first, because of one lovely property: the record of the work and the right to do it are the same row. Its gap is crashes: if the claimer dies after claiming, nobody runs the job. Real implementations store status and claimed_at, and let another instance reclaim a claim that’s been stuck too long. Reclaiming brings back the paused-holder problem, so give the claim a version number and fence the writes with it.

And if the job’s side effect is an external call (an email, a charge), pass the run ID as the provider’s idempotency key too. That’s the only protection that still works when your own process is the one that paused.

Use case 4: one worker per tenant, and leader election #

Serialising work per tenant (“only one import per customer at a time”) is a good fit for advisory locks keyed by tenant: pg_try_advisory_xact_lock(hashtext('import'), hashtext(tenant_id::text)) (the two-argument form takes two 32-bit integers, so hash a UUID; a rare hash collision only makes two tenants wait for each other). No extra infrastructure, and the lock is released with the transaction. Two things to know:

  • Session-level advisory locks don’t survive PgBouncer in transaction mode, because your next statement may run on a different server connection. Use the _xact_ variants, which are scoped to one transaction, or connect directly.
  • A holder that hangs without its connection dying blocks everyone queued behind it. Set idle_in_transaction_session_timeout (PostgreSQL 9.6+) and a lock_timeout so a stuck holder is eventually cut off.

Leader election (one instance runs the scheduler, the others stand by) is the same mystery with a longer lease. Use a coordination service built for it, such as etcd, ZooKeeper or Kubernetes’ Lease objects, and still fence the leader’s writes. etcd and ZooKeeper give you a number that grows with each change (etcd’s revision, ZooKeeper’s zxid), which can serve as the fencing token.

What about Redlock? #

Redlock acquires the lock on a majority of several independent Redis instances, so one Redis failing doesn’t break the lock. That solves a different case: Redis going away. A paused client is still the same problem, because the lock is still a lease. Martin Kleppmann’s How to do distributed locking (2016) makes this argument in detail; Redis’s author replied, and both are worth reading as a model of how to disagree about engineering. The practical conclusion doesn’t depend on who wins the argument: if correctness matters, the resource must reject stale holders.

Remember this

  • A Redis lock is a lease: it expires whether or not you’ve finished.
  • Correctness belongs to the resource: fence writes with a number that only grows.
  • For “run once” jobs, claim a row with a unique key.

What I’d do on Monday #

  1. For “run once” jobs: claim a row with a unique key (run ID, date, tenant + date). Add status and claimed_at if crashes must be recovered.
  2. For work that writes to PostgreSQL: an advisory lock (_xact_) or SELECT … FOR UPDATE in the same transaction as the writes. The lock and the writes commit or vanish together.
  3. For Redis locks: use them to avoid duplicate work, not to guarantee it never happens. Stampede protection, “don’t poll this API from two instances”: there, an occasional double is harmless. Always store an owner ID and release with compare-and-delete.
  4. When a lease is unavoidable (coordination across systems, leader election): fence every write with a growing token, and pass an idempotency key to anything external.

The idea I keep coming back to is that correctness belongs to the resource, not the lock. A single number that only grows, checked at the moment of writing, solves a problem no amount of clock-watching can. If you’re still deciding whether to lock at all, the lock or retry case is the place to start.

Checked on Redis 7.4.12, PostgreSQL 17.11 and go-redis 9.23.0 (Nov 2026), on one laptop, everything in Docker. Pauses are simulated with sleeps; real ones come from GC, VM migration, swapping, disk stalls and the network. Code and full results: database-tradeoffs-lab/06-redis-locks.

Like (sign in first) 0 likes 💬 0

Written by

Vishal Kumar

Associate Director at CapGrid, running product and engineering in a CPTO capacity. 10+ years building distributed, multi-tenant SaaS and AI platforms. AWS Certified Solutions Architect - Professional. Based in Gurugram.

Comments

No comments yet.

Sign in to comment. We'll email you a link; no password needed.