← Building blocks

Make an expired lease harmless

Consistency & coordinationstaff

A worker holding a lease pauses (GC, network), the lease expires, another worker takes it, then the first wakes up and writes anyway.

Say it like this

A lock cannot stop a paused worker that still thinks it holds the lease, so every lease carries an increasing token and the trip store rejects any write with a token older than the last one it accepted.

Basic solution

Issue a monotonically increasing token with each lease and have the storage reject writes carrying a token older than the latest it has seen.

fencing tokensZooKeeper zxidetcd revisionsconditional writes on version

The store, not the lock, stops the zombie

Token issuance is monotonic at the lock service. The protected row keeps the highest token it has accepted; A’s late write with token 1187 fails the predicate because 1188 was already applied.

How it works

  1. The lock service hands out a token with every lease, and the token is larger with every grant: a counter it increments, ZooKeeper's zxid (the transaction id of the write that created the lease), or etcd's revision (the commit number of that write).
  2. The worker includes the token in every write it makes to the protected resource while it believes it holds the lease, for example as an extra column value in the UPDATE.
  3. The resource stores the highest token it has accepted for that key. On each write it compares the incoming token with the stored one: if the incoming token is lower, it rejects the write without changing anything; otherwise it applies the write and records the new token as the highest.
  4. Now the dangerous sequence is harmless: worker A takes token 33, pauses, the lease expires, worker B takes token 34 and writes, so the resource records 34. A wakes and writes with 33; the resource compares 33 with 34 and rejects it.
  5. Expiry of the lease and rejection at the resource are independent, so the guarantee does not depend on how long A was paused or whether A ever notices the lease is gone. The resource enforces it on its own.
  6. For resources that cannot compare tokens (a third-party API, a file system), route the write through a service that can, or make the write idempotent and reconcile afterwards.

Where the token comes from

  • ZooKeeper: the zxid of the ephemeral node creation. etcd: the create revision of the key written with the lease attached. Redis: a counter incremented in the same script that grants the lease. A database: a sequence.

Worked example

Ride matching, the trip store as the fence

  • The regional matcher holds a lease on each driver it is offering. Leases are 15 seconds; matchers are JVM processes that occasionally pause for 2 to 20 seconds on garbage collection, during which they run no code and cannot renew anything.
  • Matcher A takes the lease on driver 42 with token 1187 and begins computing the offer. A 20-second GC pause hits. The lease expires at 15 seconds, while A is still frozen.
  • Matcher B takes the lease with token 1188, offers driver 42 to rider Y, rider Y accepts, and B writes the trip: UPDATE drivers SET trip = Y, fence = 1188 WHERE id = 42 AND fence < 1188. One row updated, and the row now records 1188.
  • A wakes, still believes it holds the lease, and writes its own match: UPDATE drivers SET trip = X, fence = 1187 WHERE id = 42 AND fence < 1187. The row's fence is 1188, so the predicate is false and zero rows are updated. A treats the zero as lost the lease and abandons its offer.
  • Cost: one integer column on the drivers table and one extra predicate per write. Token issuance is a Redis INCR inside the lease script, about 1 microsecond extra per lease.
  • Without the fence, driver 42 would have two trips, about once per thousand long GC pauses, which at fleet scale is daily.

Variants and when each wins

Monotonic token from the lock service

  • The lock service issues an always-increasing number with each lease and the resource rejects anything lower than the last it accepted. It wins whenever the resource is yours, because it is the only variant that orders lease holders correctly; the resource must store and compare the token per key.

Version number on the row (compare-and-set)

  • The resource's own version counter doubles as the fence: the worker reads the version, then writes WHERE version = expected. It wins when there is no lock service and the worker can afford to read first, but it cannot tell which of two lease holders came later.

Lease-bound session in the storage layer

  • Stores such as ZooKeeper and etcd tie each write to the session that holds the lease and reject writes from a session whose lease has expired. It wins when you are already using such a store, because the fence is built in and nothing extra is needed.

Idempotent writes plus reconciliation

  • When the resource cannot fence (an external API), make the operation idempotent on a key and run a reconciler that detects double execution and repairs it. It wins only when nothing else is possible, because it allows a window of double execution before the repair.

Recommendation: a monotonic token checked at the store whenever the store is yours; a built-in session fence when the store offers it; idempotency plus reconciliation only for external systems.

Failure modes

Token issued but not checked

  • You notice double execution despite having fencing tokens in the design. It happens because the resource stores the token, but one code path writes without the fence predicate, so the zombie writer's update goes through. Enforce the check in one data access layer that every write passes through, rather than at each call site.

Tokens not monotonic across failover

  • You notice a new lease receiving a lower token than an older one, so a legitimate holder is rejected or a zombie is accepted. It happens because the counter lived in a Redis primary that failed over to a replica which had not received the last increments. Issue tokens from a consensus store whose numbers survive failover, or build the token from a timestamp plus a counter so a failover cannot rewind it.

Per-key vs global token confusion

  • You notice a write rejected although nobody else held the lease. It happens because a global token from one lock was compared against a per-key high-water mark that a different lock had set higher. Use one token sequence per protected key, or one global sequence used consistently everywhere.

External resource cannot fence

  • You notice a notification sent twice by two workers that both believed they held the lease. It happens because the provider has no notion of your token and accepts both calls. Use a dedup key at the provider if it supports one; otherwise check a sent marker before the call and accept the short window between check and send.

Treating rejection as an error

  • You notice alerts firing every time a zombie writer is fenced. It happens because the rejected write is logged as a failure, when it is in fact the fence doing its job. Log a fenced write at info level and count it as a metric, so you can see the rate without being paged for it.

Interviewer follow-ups

Answer out loud before you open each one.

Why is the lease TTL alone not enough?

The TTL tells the lock service when to give the lease away, but it cannot reach into a paused process and stop it. When the process resumes it has no idea time passed. Only the resource being written can enforce that the writer is still the legitimate holder, and it needs the token to do that.

What makes ZooKeeper zxid or etcd revision good tokens?

They are assigned by a consensus log, so they are strictly increasing across the whole cluster and survive leader failover. A token from a single Redis node can go backwards after a failover to a replica that missed the last writes.

How does the resource know the highest token if it is sharded?

The token is stored per protected key, on the same shard as the key, so the comparison is a local conditional write. There is no global high-water mark; each driver row or each document carries its own last accepted token.

What should a worker do when its write is rejected?

Stop immediately and assume it no longer holds the lease: abandon the current unit of work, do not retry the write, and re-acquire a fresh lease if it wants to continue. Anything it already did outside the fenced store must be idempotent or compensated.

Connections

In study paths
Surviving a failed node
Pairs with
Make sure only one worker does it · Agree on one leader or one value · Detect conflicting updates · Make retries safe
Pulls against
Accept a short delay for scale
Used in
Ride Matching (Uber / Lyft) · Distributed Key-Value Cache (Redis / Memcached-like)

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.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingMatcher A, Matcher BCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad