Core Concepts

Distributed Locking and Fencing Tokens

Follow an expired worker claim to the store that can reject its next write, then trace a safe handover to a new owner.

Free~20 min

A worker that stops responding can still be running when another worker takes over its job. A distributed lock coordinates which worker owns the job. The service that accepts writes needs a way to reject a delayed update from the previous owner.

Expiry ends permission

A shared authority records who may run a job or write to a storage shard. In the ChatGPT design, a turn is the work for one reply. Recovery can mark the turn as failed after the worker's claim expires. The reply store still has to reject any late chunk from that worker.

A lease gives that ownership a deadline. The owner can ask to renew it before it expires. If it crashes, the authority can eventually let the system recover without receiving an explicit release. A pause, a network partition, or a slow renewal can also cause expiration while the process is still alive. A delayed request can arrive after the lease ends even if the worker sent it earlier.

Checking the lease in the worker before sending a write leaves a gap. The lease can expire between the check and the destination applying the write. Put the check at the part of the system that can refuse that change. This is fencing. It protects the shared state even if the old worker keeps running. Chubby paper, section 2.4 on locks and sequencers

Check the current token where the write happens

For one store, the simplest check uses an ownership token, a distinct value assigned to a claim. Suppose a job record holds token k7 and a deadline. The store compares a write's token with its current live token and applies the write in the same transaction or atomic operation. After expiration, it can reject k7 even before a new owner exists. If a new lease has token m2, it rejects k7 by comparison. These tokens only need to distinguish grants in this design. They can be opaque strings.

Use the same check for renewal or release. A delayed release from the first owner must leave the second owner's lease in place. Evaluate expiry using the authority's time and the protected operation's ordering rule. In PostgreSQL, CURRENT_TIMESTAMP stays fixed from transaction start. When a transaction must wait for a lock, check the authority's current time after acquiring that lock, as part of the decision to write. Redis lock ownership and safe release · PostgreSQL current date and time

Order owners at a separate destination

Some protected stores cannot read the coordinator's current lease in the same operation as their write. We can give grants ordered numbers and require the destination to remember the highest number it has accepted for that resource. A monotone fencing token increases with each new grant. Every protected write carries its token. The destination authenticates it, compares it with the durable floor, and applies the write only if the token is at least that floor. Advancing the floor and applying an accepted write must be atomic. Chubby sequencer checks at the receiving server

For a storage shard, A holds token 41 and the shard has recorded 41. A pauses. The coordinator grants 42 to B. The shard still knows only 41, so an old request carrying 41 can still pass before the shard learns about 42. B first installs 42 at the shard, or makes a protected operation that records 42 there. B establishes that barrier before using the shard's state as the new owner. After the shard records it, the shard rejects delayed writes from A, including ones that left A before its lease expired.

This high-water check orders owners. If the store's floor is still 41, it cannot infer from 41 alone that the lease expired. If writes must stop immediately on expiry, have the destination enforce expiry or advance a fence on revocation. A token also leaves repeated writes by the same owner possible. Use a stable operation ID for deduplication or a separate sequence for updates within one ownership period. Keep the token sequence and the destination's recorded floor through failover. A restored store must recover its valid floor before serving writes.

Fence each ChatGPT output path

ChatGPT records a new token and deadline in PostgreSQL when a worker claims a turn. PostgreSQL checks that token and deadline again before accepting the final reply write. For live output, Redis holds a short-lived publishing lease for the same turn and token. Renew PostgreSQL first. Extend Redis only for that token, using an absolute Redis deadline earlier than the Postgres deadline by a bound on the two clocks' difference. If the clock bound is uncertain, the worker stops publishing.

When the worker appends a chunk, one Redis script checks the live token and writes to the existing reply stream. Using the same turn ID in braces places both keys in one Redis Cluster slot. Beginning with Redis 6.2, XADD NOMKSTREAM adds to an existing stream without creating a missing stream. PostgreSQL and Redis each fence their own operation. Redis script execution · Redis Cluster hash tags · Redis XADD options

When the claim expires, recovery marks the turn as failed. It uses the turn ID to check or cancel the model execution for that reply. The slot stays reserved until the model confirms work has stopped. Resending the original retry ID reports the failed turn. A new retry ID can start a new turn if there is capacity. That is a different handover from giving a new owner an increasing number for the same storage shard.

Keep coordination at the right boundary

If both the claim and its effects live in one database, a conditional transaction can provide all the coordination that operation needs. If clients use a separate coordinator, check how its grants survive failover. For example, asynchronous Redis replication can lose a lock acquisition that never reached the promoted replica. Redis documents a case in which two clients can then believe they hold the same lock. A failover plan must preserve the relevant authority or install a new fence before accepting protected writes. Redis on the failover limits of replicated locks · Data Replication

An external system needs a way to enforce the rule on its own effects. A token the destination ignores cannot stop an old request. If the vendor supports idempotency or a lookup for an uncertain result, use that contract. For other effects, the system may have to check what happened before repeating the work.

See also

  • Locking Strategies - use row locks and conditional writes when the database holds the contested state.
  • Idempotency - handle repeated operations from a valid owner.
  • Data Replication - consider how an old writer loses authority during a replica promotion.
  • Heartbeat and Health Checks - detect when a person or system should investigate an owner and consider recovery.

Used in

  • ChatGPT - an expired worker loses permission to append visible chunks and settle the old turn. Recovery keeps the capacity reservation until execution stops.
  • Web Crawler (Distributed) - the frontier gives fetchers renewable URL leases and requeues expired work. This illustrates recovery after expiry.

Done reading? Mark it so it sticks in your dashboard.

Discussion