Bugpit

Lessons › Core concepts

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 level

Free 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.

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?

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?

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.

Try it yourself

More in Core concepts

← Two transfers, stuck forever The crawler that empties the cache →