The worker that woke up late
Workers rebuild each shop's invoices. Only one may work on a shop at a time, so each takes a lock first. Last week a worker froze for 40 seconds, woke up, and wrote an old invoice over the new one.
Play this levelFree with an account. It runs in your browser: build the design, press Run, and watch what breaks.
The lesson
A lock that never expires is dangerous: if its worker crashes, nobody can ever take it again. So locks come with a lease, say 30 seconds. If the worker doesn't renew it, the lock is freed and another worker takes over.
But a worker can freeze without crashing: a long garbage collection pause, a slow disk, a paused virtual machine. When it wakes, its lease ran out long ago, yet it still believes it holds the lock, and it writes.
A coordination service such as ZooKeeper or etcd hands out locks the machines agree on. Fencing tokens close the gap: each lock comes with a number that only goes up, and the database refuses a write carrying a number older than the last it saw.
The late worker carries token 33. The worker that took over has 34, and already wrote. The late write is refused, and the new invoice stays.
What you have to achieve
2,000 requests a second at the busiest hour, 10% of them writes.
- No broken or illegal connections
- Use Coordination
- A worker whose lock ran out can't overwrite newer work
- Workers clear the queue within the day
- Fewer than 0.1% of requests fail
What you learn
A lease keeps a crashed worker from holding a lock forever. A fencing token keeps a slow one from doing damage when it wakes. You need both, because you can't tell a dead worker from a slow one.
Check yourself
Why does a lock have a lease that runs out?
- To save memory
- So a crashed worker can't hold it forever
- So workers run faster
Show the answer
So a crashed worker can't hold it forever. Without a lease, a worker that dies while holding the lock blocks everyone else for good.
A worker froze past its lease, woke up and wrote. What stops that write?
- A longer lease
- A fencing token the database checks
- More workers
Show the answer
A fencing token the database checks. A longer lease only makes it rarer: any pause can outlast it. A token lets the database tell an old lock holder from the current one.