Skip to the page

Redis and caching · senior

Distributed locks with Redis

A Redis lock is useful to avoid duplicate work, but it cannot guarantee safety alone. For money, the database must enforce uniqueness.

The notes

What you must know

  • Acquire with one atomic command: SET lock:payout <random token> NX PX 60000. SETNX followed by EXPIRE is two commands, and a crash between them leaves a lock with no expiry.
  • No expiry means a crash leaves the lock forever.
  • Release only if the value is still yours: a compare-and-delete in a Lua script. A plain DEL can remove the lock of another worker if yours already expired.
  • For long jobs extend the lock while you work (a watchdog, as in Redisson), and never assume you still hold it.
  • A garbage-collection pause or a network stall can outlast the TTL. Replication is asynchronous, so a failover can lose the lock. Two holders at once is possible.
  • Redlock uses several independent Redis masters to reduce some risks. A well-known critique says real safety needs fencing tokens checked by the resource.
  • For payouts, enforce correctness in the database: a payout_runs row with a unique key on the date, unique keys per user payout, or a PostgreSQL advisory lock in the same database.
  • Use a Redis lock for efficiency (avoid duplicate work), not for correctness.

The red pen

Common traps: mistake → fix

  • Mistake: SETNX is a complete lock

    Fix: it needs an expiry, an owner token and a safe release.

  • Mistake: A lock guarantees exactly-once payouts

    Fix: it does not; use database unique keys.

  • Mistake: DEL is a safe release

    Fix: you may delete another worker's lock.

Easy to hard

Questions interviewers ask, easy to hard

  1. Review this code that uses SETNX and DEL for a payout lock.
  2. How do you release a Redis lock safely?
  3. Why can two workers hold the same lock?
  4. What do you use when money is involved?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview