Command Palette

Search for a command to run...

Hectal
Phase 12Advanced13 of 17 in Redis

Distributed Coordination

Locks with SET NX PX and safe unlock, the lock-expiry race and fencing tokens, Redlock and its critiques, idempotency keys, deduplication, and delayed-job scheduling.

Coordination is where Redis is most useful and most misused. A Redis lock is fast and good enough for efficiency (avoiding duplicate work), but it can't by itself guarantee correctness (never doing the work twice) when processes pause, clocks jump or a primary fails over.

This phase builds each primitive correctly, then shows exactly where it breaks and what you add (fencing, database constraints, idempotency) when correctness matters.

0/6 · 0%
6 topics ~56 min 15 code blocks & diagrams
Start with the first topic
1
12.1

Basic Locks and Safe Unlock

Acquire with SET lock:resource <unique-token> NX PX 30000: one atomic command that only succeeds if nobody holds the lock and always sets an expiry. Release with a Lua script that deletes the key only if it still holds your token, never with a blind DEL.

10 min 1 diagram 3 code practice

2
12.2

The Lock Expiry Race and Fencing Tokens

A lock holder can pause (GC, VM stall, network delay) past its TTL, and then act while another holder also acts. No TTL fixes that. Fencing tokens do: each acquisition gets a monotonically increasing number, and the protected resource rejects writes carrying an older token than it has already seen.

10 min 1 diagram 2 code practice

3
12.3

Redlock: Majority Locking and Its Critiques

Redlock acquires the same lock on a majority of N independent Redis masters within a time limit, to survive the failure of individual nodes. It improves availability over a single instance but relies on timing assumptions, and critics (notably Martin Kleppmann) argue it isn't safe for correctness without fencing.

9 min 1 diagram 1 code practice

4
12.4

Idempotency Keys: Stopping Double Payments

Clients send an Idempotency-Key with each operation; the server records the key before processing and stores the response, so retries and double clicks return the original result instead of repeating the operation. Redis makes the fast path cheap; the database makes it correct.

9 min 1 diagram 1 code practice

5
12.5

Event and Request Deduplication

SET event:{id} 1 NX EX <ttl> is a cheap way to drop repeated events, but it has gaps: the TTL window, marking before processing vs after, and Redis data loss. Durable deduplication belongs in the processing store, with Redis as a fast first filter.

8 min 1 code practice

6
12.6

Delayed Jobs, Retries, and Distributed Scheduling

A sorted set scored by run-at time is a delayed queue: workers atomically claim jobs whose score is ≤ now. Add exponential backoff with jitter for retries, a dead-letter set for poison jobs, idempotent handlers, and leader election or atomic claiming so schedules run once.

10 min 1 diagram 2 code practice