Redis Design Patterns: A Practical Guide to Locks, Counters, CAS, and Lua
A field guide to Redis design patterns that actually hold up in production: distributed locks, atomic counters, rate limiters, compare-and-swap, cache-aside, pub/sub — with real redis-cli commands, Lua scripts, interactive diagrams, and the antipatterns that quietly take down clusters.
Redis runs one command at a time, so a single command (or a Lua script) is atomic and two separate commands never are. Almost every pattern here, from locks and counters to compare-and-swap and caches, comes down to getting the check and the write into one atomic step.
Redis looks simple enough that it's easy to reach for it without a plan: SET, GET, EXPIRE, done. Then production happens — two processes think they hold the same lock, a rate limiter lets through triple the allowed traffic, KEYS * freezes the cluster during a demo — and the gap between "Redis is easy" and "Redis is easy to misuse" becomes obvious.
This is a practical, pattern-by-pattern guide to the ways Redis actually gets used in real systems: distributed locks, counters, rate limiters, compare-and-swap, caching, pub/sub, and the Lua scripts that make several of those patterns safe instead of merely fast. Every pattern below ships with the actual redis-cli commands or Lua script, not pseudocode.
Redis executes one command at a time, on a single thread, from an in-memory dataset. That single fact is why SET key value NX is atomic (nothing else can run between the existence check and the write), why KEYS * freezes every other client (the one thread is busy scanning), and why persistence (RDB snapshots, AOF logs) happens around that thread rather than blocking it.
Two consequences fall directly out of this, and both explain why the patterns below look the way they do:
Any single command is automatically atomic — no other client's command can interleave with it. This is why SET lock NX EX 30 is safe on its own, but SETNX followed by a separate EXPIRE is not: two commands means a gap another client's command can land in.
A slow command blocks everyone — KEYS * on a 10-million-key database, HGETALL on a hash with a million fields, or a Lua script with a loop over an unbounded collection all hold the one thread hostage for their entire duration. Every antipattern in this guide traces back to forgetting this.
The problem: several processes across different machines need to agree that only one of them runs a critical section at a time — booking the last seat, processing a payment webhook exactly once, running a scheduled job on exactly one replica.
# SET with NX (only if not exists) + EX (expiry) in a single atomic commandSET lock:invoice:8842 "worker-7f3a" NX EX 30# → OK lock acquired, expires in 30s even if the holder crashes# → nil someone else already holds it
worker-7f3a must be a value unique to the caller (a UUID, or pod name + thread id) — not a constant like "1". That value is what makes a safe release possible.
lua
-- NEVER do this to release a lock:DEL lock:invoice:8842-- If your lock already expired and someone else acquired it, this deletes-- THEIR lock. You just handed the critical section to two processes at once.
EVAL "
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
else
return 0
end
"1 lock:invoice:8842 "worker-7f3a"# → 1 released (you were the owner)# → 0 not the owner — your lock already expired and was re-acquired
This has to be Lua, not two separate commands (GET then DEL), because a GET-then-DEL from the client leaves a gap: another process's lock can be acquired in between your check and your delete. Lua runs the whole thing as one atomic step inside the server.
Step through the failure, message by message:
≡
6 messages. Press Play, or pick one, to see exactly what is sent.
How an unsafe release deletes someone else's lock
That sequence is the actual failure mode behind the well-known Redlock controversy: even a "correct" locking protocol can't stop a paused process from acting on a lock it no longer holds. The fix isn't a cleverer lock — it's a fencing token: hand out a monotonically increasing number with the lock, and make the protected resource itself reject any write carrying an older token than the last one it saw. The lock tells you who should be acting; the fencing token is what the resource checks to make sure a stale acquirer's write can't land after a newer one already did.
-- Lock N keys atomically or lock none — no partial-lock deadlockslocal owner = ARGV[1]local ttl =tonumber(ARGV[2])for i =1,#KEYS doif redis.call('EXISTS', KEYS[i])==1thenreturn0-- at least one is taken; acquire noneendendfor i =1,#KEYS do redis.call('SET', KEYS[i], owner,'EX', ttl)endreturn1
Warning
A lock that's never released on the failure path is a lock that hangs the system, not a bug that just affects one request. Always set an EX on acquire — a lock with no TTL turns one crashed worker into a permanent outage for that resource.
The problem: many concurrent requests need to increment a shared count and make a decision (allow/deny) based on it — without two requests both reading "9" and both incrementing to "10" when the real answer should have been "11".
INCR metrics:orders:today # → 1, 2, 3... — no lost updates, everINCRBY metrics:revenue:today 4999# → atomic add, useful for totals in minor units
INCR alone is safe because it's one command on one thread. The moment you need "increment, and check a limit, and set an expiry the first time" — that's three decisions, and it needs Lua to stay atomic.
local current = redis.call('INCR', KEYS[1])if current ==1then redis.call('EXPIRE', KEYS[1], ARGV[1])-- only the first request sets the TTLendif current >tonumber(ARGV[2])thenreturn{0, redis.call('TTL', KEYS[1])}-- blocked, seconds until resetendreturn{1,0}-- allowed
Fixed windows are simple but let through up to 2x the intended rate right at the boundary — 100 requests in the last second of one window, then 100 more in the first second of the next, both technically "within limit."
The problem: update a value only if it hasn't changed since you last read it — the classic "read balance, check it's sufficient, deduct" sequence, where two concurrent deductions must never both succeed against a balance that only covers one of them.
Redis gives you two different tools for this, and picking the right one matters.
WATCH account:42:balance
GET account:42:balance # → "500" — read once, decide client-side# client checks: is 500 >= withdrawal amount (300)? yes, proceed.MULTI
DECRBY account:42:balance 300EXEC
# → if account:42:balance changed since WATCH, EXEC returns nil (transaction aborted)# → the client must detect the nil and retry the whole read-check-write sequence
watch
WATCH the key, then GET its current value
decide
client-side: is the precondition still true?
commit
MULTI + the write + EXEC
conflict
EXEC returned nil — another client changed it first — retry from watch
This is true CAS: optimistic, cheap when contention is low, but it costs a full round trip per attempt and can retry indefinitely under high contention on the same key.
local balance =tonumber(redis.call('GET', KEYS[1]))local amount =tonumber(ARGV[1])if balance >= amount then redis.call('DECRBY', KEYS[1], amount)return1-- successendreturn0-- insufficient funds, nothing changed
Same guarantee, zero round trips, and no retry loop — because nothing outside the script can run between the read and the write in the first place. There's nothing to conflict with.
WATCH/MULTI/EXEC
Lua (EVAL)
Where the "decide" logic runs
Client
Server
Round trips per attempt
3 (WATCH, GET, EXEC)
1
Behavior under conflict
Client must detect nil and retry
Never conflicts — it's already atomic
Best for
One-off transactions, simple precondition checks
Anything you'll call often, or with nontrivial logic
The practical rule: if you're about to write a client-side retry loop around WATCH, that's usually a sign the logic belongs in a Lua script instead.
GET cache:show:8842:metadata
# → nil (miss)SET loading_lock:show:8842 1 NX EX 5# → OK this process rebuilds the cache# → nil another process is already rebuilding — wait ~100ms and retry the GETSET cache:show:8842:metadata '{"title":"Avengers","screen":"IMAX"}' EX 300
No loading lock
Every concurrent miss queries the database
Hundreds of identical rebuilds at once
With loading_lock
Exactly one process rebuilds the value
Everyone else waits ~100ms and reads the cache
vs
Verdict: Put SET NX in front of the rebuild; a stampede costs far more than a short wait.
A hot key expires under heavy traffic
Without the loading_lock, a popular key expiring under heavy concurrent traffic causes a cache stampede — hundreds of requests all miss at once and all hammer the database to rebuild the same value simultaneously. The lock ensures exactly one rebuild happens; everyone else waits milliseconds and reads the freshly-populated cache instead.
HSET session:tok_abc123 user_id 42 username alice role admin created_at 1717890000EXPIRE session:tok_abc123 3600HMGET session:tok_abc123 user_id role # read only the fields you needEXPIRE session:tok_abc123 3600# sliding expiry on activitySADD user:42:sessions tok_abc123 # index for "log out everywhere"SMEMBERS user:42:sessions |xargs DEL # invalidate every session for a user
A hash beats one key per field (session:tok:user_id, session:tok:role, ...) for the same reason a struct beats five separate variables: one EXPIRE, one HGETALL, and the fields travel together.
ZADD leaderboard:weekly 5000"player:42"# set absolute scoreZINCRBY leaderboard:weekly 150"player:42"# or increment by a deltaZRANGE leaderboard:weekly 09 REV WITHSCORES # top 10, highest firstZREVRANK leaderboard:weekly "player:42"# 0-indexed rankZSCORE leaderboard:weekly "player:42"# current scoreZCOUNT leaderboard:weekly 1000 +inf # how many players above a threshold
ZRANGE ... REV and ZREVRANK are O(log N) — this is the whole reason a sorted set, not a sorted SQL query, backs almost every real-time leaderboard: ranking a million players stays fast because the structure keeps itself ordered on every write, instead of re-sorting on every read.
WebSocket worker pod 1forwards to connected browsers
WebSocket worker pod 2forwards to connected browsers
WebSocket worker pod 3forwards to connected browsers
Analytics subscriberlogs event, no delivery guarantee if offline
bash
PUBLISH seat-updates:SHOW8842 '{"seat":"A1","status":"LOCKED"}'# → 4 number of subscribers that received it, right now
SUBSCRIBE seat-updates:SHOW8842
PSUBSCRIBE "seat-updates:*"# one connection, all shows
Warning
Pub/Sub has no persistence and no replay — a subscriber that's disconnected for even a second misses every message published during that gap, permanently (the gap offline delivery in a chat system has to close). If a consumer being briefly offline and missing an update is unacceptable (order events, financial updates), that's not a Pub/Sub problem — reach for Redis Streams (XADD/XREADGROUP) instead, which keeps a durable log with consumer-group offsets, or a real message queue.
The one property that makes this safe to use for gating (not just hinting): zero false negatives, some tunable rate of false positives. It will never wrongly say "definitely not seen" for something it has seen — it will occasionally say "probably seen" for something it hasn't, at a rate you control by allocating more bits. That asymmetry is exactly right for a blocklist check (a false positive costs one extra confirming lookup; a false negative would let a known-bad actor straight through) and exactly wrong for anything where a false positive silently drops real data (don't use it to decide whether to skip processing an item).
SET idempotency:req_abc123 "PROCESSING" NX EX 30# → OK first request — proceed with processing# → nil a duplicate arrived while the first is still in flight — return 202, don't reprocess# On completion, overwrite with the real result so retries get the cached response:SET idempotency:req_abc123 '{"booking_id":"BOOK123","status":"CONFIRMED"}' EX 86400
The NX on the first SET is what prevents two near-simultaneous retries (a client's own timeout-and-retry, or a webhook redelivery) from both starting to process the same request — one wins the SET, the other gets nil and knows to back off. A durable agent runtime uses idempotency keys the same way, so a retried step doesn't repeat its side effect.
Every pattern above that needed Lua needed it for the same underlying reason: the operation is "read a value, make a decision based on it, then write" — and that whole sequence has to be one atomic unit, not three separate round trips a competing client's command could land in between.
bash
# Load once, get a hash back — avoids re-sending the script body on every callSCRIPT LOAD "<lua source>"# → "e3f6b1..." (SHA1 of the script)EVALSHA e3f6b1... 1 lock:invoice:8842 "worker-7f3a"# → runs the cached script by hash — same atomicity, less bandwidth per call
Situation
Plain commands enough?
Needs Lua / EVAL
Increment a counter, no limit check
Yes — INCR alone is atomic
—
Increment, and enforce a limit + set TTL only once
—
Yes (Pattern 2)
Release a lock you might not own anymore
—
Yes (Pattern 1)
Read a balance and conditionally deduct it
WATCH/MULTI/EXEC works, with a client retry loop
Yes, if you want zero round trips or high contention (Pattern 3)
Read-and-reset a metric atomically
—
Yes — GET then SET 0 from the client has a gap
Set a key only if absent, with an expiry
No script needed
SET key val NX EX ttl is already one atomic command
The recurring signal: if your code would otherwise need WATCH, or a client-side "get, check, act" sequence, or two commands where a crash or a race between them would leave bad state — that's the shape of problem Lua exists for.
Scans the entire keyspace on the single thread — every other client stalls until it finishes
SCAN with a cursor — same result, doesn't block
SETNX then a separate EXPIRE for a lock
A crash between the two commands leaves a lock with no TTL — permanent
SET key val NX EX ttl — one atomic command
HGETALL / SMEMBERS on unbounded collections
A hash or set with a million fields blocks the thread for the entire read
HSCAN / SSCAN — cursor-based, doesn't block
Treating Redis as the source of truth for money/inventory
Redis optimizes for speed, not the durability guarantees a ledger needs
Redis as cache/lock/counter in front of an authoritative database
Large payloads in PUBLISH
The payload is copied to every subscriber connection — a 10MB message saturates the network N times over
Publish a small pointer/id; subscribers fetch the payload from a store
SELECT in cluster mode
Redis Cluster only has database 0 — this silently does nothing or errors
Namespace keys with prefixes instead of numbered databases
No maxmemory-policy set, then OOM under load
Default is noeviction — writes start failing hard the moment memory fills
Set an eviction policy (allkeys-lru, etc.) deliberately, matched to whether the data is a cache or must never be evicted
A single giant key (a hash with 5M fields, a list with 10M entries)
Any command touching it — even a single-field HGET in some cases, definitely HGETALL/DEL/expiry sweeps — takes proportionally longer and blocks the thread
Shard the collection across multiple keys (e.g. hash-tag by user id range)
Storing secrets/PII unencrypted
Redis is often reachable by anything inside the VPC, with no per-key encryption at rest
Encrypt sensitive fields before writing, or don't put them in Redis at all
A short checklist worth running through before committing to Redis for a new use case:
Durability tolerance — if the process holding this data restarted right now and lost everything, is that a shrug or an incident? Redis is happiest as the shrug case.
Memory economics — Redis prices your data in RAM, not disk; a dataset that's cheap in Postgres can be expensive in Redis at the same size.
Persistence trade-off — RDB snapshots are cheap but can lose the last few minutes of writes on a crash; AOF with fsync always loses far less but costs write throughput. Pick deliberately, not by default.
Eviction policy — decide explicitly whether this key space is allowed to be evicted under memory pressure (allkeys-lru) or must never be (noeviction, with capacity planned to match).
Blocking command exposure — audit for KEYS, unbounded HGETALL/SMEMBERS, and any Lua script with an unbounded loop; each one is a latency spike waiting to happen at scale.
Cluster-mode fit — multi-key operations (MULTI, most Lua scripts) need all keys in the same hash slot in cluster mode; design key names with hash tags ({user:42}:profile, {user:42}:sessions) up front if you'll ever shard.
Hot key risk — a single wildly popular key (a viral post's like counter, one celebrity's session; feeds meet it as the celebrity account problem) can saturate a single shard even when the cluster overall has headroom; know your access pattern's skew before it surprises you in production.
Check yourself
Q1Why must a lock release be one Lua script rather than GET then DEL?
Q2What actually stops a paused process from acting on a lock it no longer holds?
Q3What does the loading_lock in cache-aside prevent?
Cheat sheet
Redis design patterns
Why it behaves this way
One command at a time, on one thread, in memory: any single command is atomic.
A slow command (KEYS *, HGETALL on a huge hash) blocks every client.
Locks
Acquire with SET key unique-value NX EX ttl, one command, never SETNX then EXPIRE.
Release with a Lua script that checks ownership and deletes in one step.
Use a fencing token so a paused process can't act on a lock it lost.
Counters and compare-and-swap
INCR alone is atomic; increment plus limit plus expiry needs Lua.
WATCH / MULTI / EXEC retries on conflict; Lua decides in one step on the server.
Caching and fan-out
Cache-aside with a SET NX loading lock stops a stampede on a hot key.
Pub/Sub has no replay; use Streams when a missed message matters.
Bloom filters: no false negatives, so gate on them, but never skip work on them.
Avoid
KEYS *: use SCAN. Unbounded HGETALL / SMEMBERS: use HSCAN / SSCAN.
Redis as the only copy of money or inventory.
No maxmemory-policy: the default noeviction fails writes when memory fills.
Before you reach for it
Could you lose this data on a restart and shrug?
Does the working set fit in RAM, and are access patterns key-based?
Will you shard? Plan hash tags like {user:42} up front.
The guide on one page. Download it for your desk or your design doc.