Try
↑ ↓ move↵ openesc close

Interview prep / Locks, leases and fencing

Mid · Locks, leases and fencing · System design interview question

A nightly billing job must run on only one of three scheduler instances. You use a lock with a lease for the election. After a failover, customers are billed twice. What happened, and how do you fix it?

Sketch your own answer first, then compare it with the one below.

A strong answer

A plausible sequence: instance A takes the lock, starts the job and is paused for longer than the lease, perhaps by a long garbage collection or a frozen VM. The lease expires, B takes the lock and starts the job. A wakes, still believes it is the leader, and continues. For some minutes two instances run the billing loop.

The lock never allowed two holders at the lock service. The problem is that nothing downstream checks who is the current holder. Fix it where the damage happens. Give each charge an idempotency key derived from the customer and the billing period, so a second attempt is detected and ignored. Better still, have the billing store reject writes from an older lock generation by carrying the fencing token through, and recording the highest token seen for the job.

Then add safeguards on the instance: stop the job if a renewal fails, and check the lease between batches. These shrink the window but only the idempotency key and token close it. For a job that moves money, the lock is a correctness lock and should be treated as one.

Sources

Learn it by running it

The locks, leases and fencing lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms