Single-Active Worker Coordination with Expiring Redis Locks
System DesignModel answerLast updated
Design a way for a fleet of identical workers to pick exactly one active instance using Redis expiring keys, covering failover, fencing, pauses, clock assumptions and Redis outages.
Choosing One Active Worker with Redis
A fleet of up to 50 identical, stateless service instances runs the same code. Exactly one of them should be active at any moment and run a singleton job (for example, a scheduler that fires periodic tasks, the sole writer for a data partition, or the only consumer of a queue). All other instances stay on standby and must be ready to take over.
Design a time-limited lease protocol that uses Redis to decide which instance is active. A single primary Redis endpoint is acceptable. You may use any Redis feature, such as SET NX PX, Lua scripts or Pub/Sub.
What your design must cover
- Election: at most one active instance at any time.
- Failover: if the active instance crashes or becomes unhealthy, another instance takes over within a bounded time.
- Lease and renewal: activity is time-bounded and continuously extended while the holder is healthy.
- Correctness: how you prevent or limit split brain, a dead holder blocking progress, dependence on clocks, and the effects of network glitches and long GC or stop-the-world pauses.
- Operations: which metrics and logs you would add, and how the system behaves when Redis is unreachable.
Deliverables
- A precise description of the algorithm or protocol.
- The Redis data model: keys, values and TTLs.
- Behavior in edge cases and failure modes.
Constraints and assumptions
- Up to about 50 instances, each running the same election loop.
- One primary Redis endpoint. Redis is not a consensus (CP) system, so state clearly where that limits your safety guarantee.
- Load on Redis is tiny (a few small keys, a low rate of acquire and renew calls). Throughput is not the concern; failover time and safety are.
- Partitions, packet loss and process pauses are all in scope.
- Having no active instance for a short time is acceptable. Having two instances doing conflicting work is not. Safety takes priority over availability.
- Do not assume synchronized wall clocks across instances.
Questions worth raising with the interviewer
- Does the singleton job write to an external system that could check a fencing token, or is it purely in-memory so that idempotency is the only protection?
- What is the failover target after a hard crash? This sets the TTL.
- How bad is a short overlap of two active instances: is the work idempotent, or would a stale action corrupt data?
- Is Redis really a single primary, or is there an asynchronously replicated standby to reason about?
- Is TTL-bounded takeover good enough, or is near-instant handover required?
Hints
Hint 1
One key holding a unique instance ID, created only if absent and with an expiry, gives you both mutual exclusion and automatic release after a crash. Think about what must be atomic when you extend or delete it.
Hint 2
Distinguish three renewal outcomes: renewed, definitely lost the lease, and could not reach Redis. Each requires a different reaction, and the third must make the instance stop acting before its own deadline passes.
Hint 3
A lease alone cannot stop a paused process from acting after it has lost leadership. Look for a monotonically increasing number that the downstream resource can check and use to reject stale writers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Use one Redis key as an expiring lock. Whoever holds it is the active instance. Expiry gives automatic failover, and NX gives mutual exclusion. Everything else is about making renewal and release safe, and being honest about what a lease cannot guarantee.
Data model
| Key | Value | TTL | Purpose |
|---|---|---|---|
lease:job | unique instance ID (hostname + random UUID generated at process start) | T (e.g. 15 s) | The lock itself |
lease:job:epoch | integer counter | none | Fencing token source |
lease:job:released (optional) | Pub/Sub channel | n/a | Wake standbys early on graceful shutdown |
Protocol
Acquire (standby, every T/3 plus random jitter):
SET lease:job <myId> NX PX 15000
If it succeeds, run a small Lua script that atomically does INCR lease:job:epoch and returns the new value. This is the instance's fencing token. (Better still, do both steps in one script so the epoch cannot be skipped.)
Renew (active instance, every R = T/3, about 5 s), as a Lua script so check and extend are atomic:
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('PEXPIRE', KEYS[1], ARGV[2])
else
return 0
end
Release on graceful shutdown: compare-and-delete in Lua, then optionally publish a message so standbys try immediately. Never use a bare DEL, since it could remove a successor's lease.
Three renewal outcomes
- Renewed (1): record a local deadline
t_start + Tusing a monotonic clock, measured from before the request was sent. - Lost (0 or a different value): step down immediately, stop the job and cancel in-flight work.
- Error or timeout: do not assume you still lead. Keep acting only until the local deadline from the last success, minus a safety margin; then step down. Retry quickly in the meantime.
Treating case 3 like case 1 is the classic source of split brain; treating it like case 2 immediately causes needless flapping on a single dropped packet.
TTL sizing
- Worst-case failover after a hard crash is about
Tplus one poll interval, so roughlyT + T/3. - Renewal interval
Rshould satisfyR ≤ T/3, so two consecutive renewals can fail before the lease expires. - Small
Tgives faster failover but more flapping under GC pauses and network jitter. For a 20 s failover SLO,T = 15 sandR = 5 sis a reasonable start. - The active instance's self-imposed deadline should be shorter than the Redis TTL (e.g.
T - margin) to absorb latency.
Fencing tokens
A timeout lease cannot by itself guarantee one effective leader. Example: instance A obtains the lease, then freezes in a 20 s GC pause. The key expires, B takes over, and then A wakes up and believes it is still active. A's local deadline check helps only if A runs it right before every side effect, and even then there is a window between the check and the write.
The fix is a fencing token enforced at the resource:
- Each acquisition gets a larger epoch from
lease:job:epoch. - Every write to the downstream system carries the epoch.
- The resource rejects any write with an epoch lower than the highest it has seen (e.g. a conditional update
WHERE epoch <= :myEpoch, or a stored max-epoch check).
If the resource cannot check tokens (a pure in-memory job, or a third-party API), fall back to idempotent operations, short critical sections, and checking the local deadline immediately before each side effect. State plainly that this narrows the window but does not close it.
Clock assumptions
- No cross-instance clock sync is needed. Each instance measures elapsed time with its own monotonic clock; expiry is decided only by Redis's clock.
- Residual risks: a wall-clock jump on the Redis host, or an instance whose monotonic clock runs noticeably fast or slow. Use NTP slewing on the Redis host and leave margin between
R,Tand the local deadline.
Failure modes
| Scenario | Behavior |
|---|---|
| Active instance crashes | Key expires after at most T; a standby wins SET NX. |
| Partition: active cut off from Redis | Renewals error; the instance stops at its local deadline. Standbys take over after expiry. Gap with no leader is acceptable. |
| Partition: standby cut off | It simply never acquires. No harm. |
GC or VM pause longer than T | Lease expires and a new leader is chosen. The old one resumes; its next renewal returns "lost", and downstream fencing rejects any stale write in between. |
| Redis down | Fail closed: nobody can renew, so every instance steps down at its deadline. Work halts rather than risking two leaders. |
| Redis restart without persistence | Key vanishes and a new leader may start while the old one is within its local deadline. Mitigate with a startup grace period (do not allow acquires for T after Redis boots) and fencing. The epoch counter must survive restarts, or be replaced by a timestamp-seeded value. |
| Async replica promoted after primary failure | The replica may lack the latest lease or epoch, so two holders are possible. This is the fundamental weakness of Redis here. |
| Thundering herd on expiry | Jitter the standby polling interval; the load is tiny anyway with 50 instances. |
| Instance restarts with the same ID | Use a fresh random ID per process so a restarted process cannot mistake an old lease for its own. |
Observability
- Gauge
is_leaderper instance, and a fleet-wide alert if the sum is not 1 for longer thanT. - Counters for renewal outcomes:
renew_ok,renew_lost,renew_error. - Histograms for acquire and renew latency; time-to-elect after a leader loss.
- Flap rate (leadership changes per hour) and alert on spikes.
- Fencing rejections at the downstream resource. Any nonzero rate means a stale leader is acting.
- Structured logs on every transition with instance ID, epoch and reason.
Limits and alternatives
Single-node Redis is not a consensus system, so the lease is a liveness and efficiency tool, not a safety proof. Safety comes from fencing plus idempotency. For safety-critical singletons, use the same protocol on etcd or ZooKeeper (linearizable leases, ephemeral nodes, revision numbers as fencing tokens). Multi-node Redlock is controversial and still needs fencing, so it does not remove the need for the design above.
Common mistakes
- Using
SETthenEXPIREas two steps (a crash in between leaves an immortal key). - Renewing or deleting without checking ownership.
- Treating a renewal timeout as success.
- Relying on wall-clock timestamps in the key value.
- Setting
Rclose toT. - Claiming the lease alone prevents split brain.