Make sure only one worker does it
Two workers both try to match the same driver, run the same job, or process the same file.
Say it like this
Two matchers must never offer the same driver, so I take a short Redis lease per driver with SET NX and a TTL, and the trip store rejects any write carrying a stale fencing token.
Basic solution
Take a lease: SET key NX with a TTL, do the work, release. Or route all work for a key to a single owner.
Lease with a fencing token
Worker A pauses after taking the lease; it expires and worker B takes it with a higher token. When A wakes and writes, the store rejects the stale token, so only B wins.
How it works
- The worker tries SET lock:driver:42 <token> NX PX 20000. NX means "only set if the key is absent", so only one caller can win; PX 20000 sets a 20 second expiry so the key disappears on its own if the holder dies.
- If the reply is OK the worker holds the lease. If the reply is nil, someone else already holds it, so the worker skips this driver or waits and retries.
- It does the work quickly, well inside the 20 second TTL, so the lease is still valid when it finishes.
- It releases with a script that deletes the key only if the stored value still equals its own token. That check means a worker never deletes a lease that expired and was since taken by someone else.
- For long work it extends the lease with a heartbeat: every few seconds it runs a script that pushes the expiry forward, again only if the token still matches.
- Any write the lease protects carries a fencing token, a number from the lock service that increases with every lease granted. The store remembers the highest token it has accepted and rejects any write carrying a lower one, so a worker whose lease silently expired cannot overwrite a newer holder's work.
Why the token on release
- Without the token check, a worker whose lease expired could run a plain DEL and delete the lease the next worker now holds, and two workers would run the critical section at once.
Worked example
Ride matching, one driver offered to one rider
- A region has 5,000 available drivers and 200 match requests per second.
- Each match locks the chosen driver for the offer window: SET lock:driver:{id} NX PX 15000, so the driver cannot be offered to a second rider for 15 seconds.
- Contention is low: at 200 locks/s over 5,000 drivers, the chance two matchers pick the same driver in the same second is small but real, and a double offer is a product bug that both riders notice.
- Redis cost: 200 SET + 200 DEL per second, trivial. Lock memory: at most 5,000 × 60 B = 300 KB, one key per locked driver.
- On accept, the trip row is written with the fencing token: UPDATE trips SET driver_id = 42, token = 1187 WHERE id = ? AND token < 1187. A stale matcher still carrying token 1186 changes zero rows.
Variants and when each wins
Single Redis lease (SET NX PX)
Consensus-backed lock (ZooKeeper, etcd)
- An ephemeral node or a lease tied to a client session, with a revision number that increases on every change and doubles as the fencing token. It wins when correctness is non-negotiable, at the cost of higher latency and another cluster to run.
Database row lock
- SELECT ... FOR UPDATE inside a transaction holds the row until commit, so the database itself serialises the writers. It wins when the protected data lives in the same database; it holds a connection open while waiting.
Single owner per key
- Route all work for a key to one consumer: one Kafka partition per region, one matcher process per city. There is no lock at all; the partition is the lock. It wins whenever the workload is naturally partitionable by the key you would have locked.
Avoid the lock if you can route to a single owner; otherwise a Redis lease with fencing for most cases, and a consensus lock when correctness is non-negotiable.
Failure modes
Lease expires mid-work
- Two workers both finish the same job and both write their result. It happens because a garbage-collection pause or a slow dependency pushed the first worker past the TTL, the lease lapsed, and a second worker acquired it. Fix it with fencing tokens checked by the store, so the first worker's late write is rejected, plus a heartbeat that extends the lease while the work is genuinely still running.
Releasing someone else's lock
- Three workers end up inside a critical section meant for one. It happens because a worker released with a plain DEL after its own lease had already expired, deleting the lease the next worker held. Fix it with compare-and-delete: a Lua script that deletes the key only if the value equals the caller's token.
Redis failover loses the lock
- A lock that was held on the old primary does not exist on the newly promoted replica, so a second worker acquires it. It happens because Redis replication is asynchronous and the SET had not reached the replica. Fix it by accepting the window and fencing every protected write, or by using a consensus store for the lock when that window is unacceptable.
Deadlock across two locks
- Workers wait forever and throughput drops to zero. It happens because one worker locks A then B while another locks B then A, and each waits for the other. Fix it by always acquiring locks in a fixed global order, and keep TTLs on every lock so a stuck holder eventually loses its lease.
Lock as a bottleneck
- Throughput is capped by how long each holder keeps the lock. It happens because the key being locked is too coarse, the whole region instead of one driver, so unrelated work waits in line. Fix it by locking the smallest entity that actually needs exclusivity.
Interviewer follow-ups
Answer out loud before you open each one.
What is a fencing token and why does the lock alone not suffice?
A fencing token is a number that increases with every lease granted. The protected resource stores the highest token it has seen and rejects writes with a lower one. The lock alone cannot stop a paused worker that still believes it holds the lease; only the resource checking the token can.
How do you choose the TTL?
Longer than the slowest expected run of the work, including retries of its dependencies, but short enough that a crashed holder does not block others for long. Typical values are seconds to tens of seconds, with a heartbeat extending it if the work is unpredictable.
Why is a single Redis lock not safe under failover, and does it matter?
Replication is asynchronous, so a lease granted on the primary just before it dies may not exist on the promoted replica, and a second client can acquire it. It matters only if the work cannot be fenced; with fencing at the store, the second holder simply wins and the first write is rejected.
How would you avoid needing a lock at all?
Partition the work so each key has exactly one owner: one consumer per Kafka partition, one matcher process per region, one actor per driver. Exclusivity then comes from routing rather than coordination, which is both faster and simpler to reason about.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Worker A, Worker B | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Trip store | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |