Fencing Tokens for Distributed Agent Locks
Fencing tokens let the resource reject stale writes that an expired lease cannot stop.

Distributed agent locks need fencing tokens because a lease can expire without stopping the agent that held it. Leases restore progress after failure, but correctness depends on the protected resource rejecting stale work. Fencing tokens provide that distinction by ordering ownership and enforcing it where a write takes effect, rather than where an agent believes it has permission.
Why a distributed lock cannot protect a resource it cannot reach
Holding a lock feels like a guarantee of exclusive access. In a distributed system, that guarantee has a boundary. The lock service serializes acquisition, while a separate system accepts the resulting writes. Unless that resource participates in enforcement, the lock service’s decision about ownership cannot prevent an old holder from changing shared state.
Lease expiry tells the authority that the lease is no longer current while leaving the paused client, in-flight packets, and the database’s rules for judging the next write unaffected. This lets leases restore liveness after a crash without waiting forever for the holder that is gone. However, a client that was merely paused can resume after another client has acquired ownership. Leaving the resource out of the design creates a correctness gap that remains invisible until those executions overlap.
The exact failure sequence: how a paused client writes after its lease has expired
Consider W1 working under lease L-81 before it pauses. The authority expires L-81 at 09:00:30, and W2 receives lease L-82 at 09:00:31. W2 finishes and publishes the new report at 09:00:38. W1 resumes at 09:00:48 and sends its old result. Without resource-side enforcement, the store has no basis for distinguishing that stale result from an authorized write, so W1 can overwrite W2’s report.
The lock service has behaved correctly throughout this sequence. It expired the old lease and granted a new one, preserving progress while W1 remained paused. The failure comes from assuming that a client that owns the lock when it starts still has authority to make the final mutation. W1’s local state has not caught up with the coordinator’s decision, and a database unaware of the lock cannot resolve that disagreement.
A client-side ownership check does not close the gap. W1 can pass the check, pause before sending the mutation, and resume after its lease has expired. Even a check immediately before the write leaves an interval in which ownership can change. The decisive event is therefore not the client’s last successful check, but the resource’s acceptance of the effect.
Why TTL tuning and heartbeat keep-alives cannot close this gap
A longer TTL changes the pause required to trigger the failure while leaving the failure possible. There is no reliable limit on how long pauses and network delays can last, so a stale write can arrive after any chosen lease duration. Heartbeat keep-alives address the same ownership question by renewing the lease while communication succeeds. They cannot revoke work that resumes after renewal stops.
These controls improve liveness without establishing write correctness. Their role is to manage how long ownership persists and when another worker can proceed. The resource needs a different answer, namely whether the arriving write belongs to an owner older than one it has already accepted. Neither a TTL nor a heartbeat supplies that ordering at the point of mutation.
The distinction is especially important when choosing what a lock protects. If overlapping work only wastes computation, the lock serves efficiency. If overlap can corrupt shared state or duplicate a financial effect, the lock serves correctness, and lease management alone is insufficient. Tuning remains useful, but it cannot substitute for an acceptance rule at the resource.
What fencing tokens actually do: ordering authority at the resource boundary
A fencing token is an increasing value associated with ownership. The client presents that value with its write, and the resource compares it with the authority it has already recorded. Once the resource accepts a higher token, it rejects writes with lower tokens. Enforcement no longer depends on the old client discovering that it lost its lease.
In the fenced version of the report sequence, W2 receives token 42 with L-82. Its write reaches the store before W1 resumes, so the store records the newer authority. When W1 sends its old result at 09:00:48, the store rejects it as stale_owner, leaving W2’s file intact. The distinction is precise. Fencing rejects an older owner after newer authority has reached the resource, rather than turning lease expiry into a remote interrupt.
Ordering is stronger than a unique random identifier. A random identifier can prevent one client from deleting another client’s Redis lock at release time, but it cannot establish whether owner X precedes owner Y. Fencing needs to know which grant came before which. The resource needs increasing authority, so gaps in the token sequence are acceptable, while duplicates and reversals are not.
Where to generate a trustworthy fencing token and why the source matters
A token source must keep tokens in order even through the failures that make fencing necessary. ZooKeeper provides a globally ordered czxid for the lock znode. Its standard locking recipe also uses sequential ephemeral znodes with server-assigned, strictly increasing sequence numbers. Ordering is built into the coordination primitive. It does not depend on a worker constructing an apparently increasing value from local state.
Etcd revisions offer another basis for this design. The lock key’s ModRevision or CreateRevision comes from globally increasing, consensus-ordered writes within the cluster. Revision-based fencing should still be described as a design pattern, since it is not a documented native fencing feature. The relevant guarantee comes from serialized coordinator state.
A single Redis node’s INCR is weaker under failover. Its ordering remains useful only while the counter state survives, because promotion of a lagging replica can make the counter go backwards. A regressing fence may reject the legitimate new holder. Wall-clock timestamps are also poor substitutes because skew, disagreement between machines, and equal timestamps make ordering ambiguous. Implementations should prefer a token source derived from a consensus log.
Enforcing the token at the resource boundary: what the protected system must do
The protected resource must compare and persist the token atomically with the effect. It therefore needs to store both the protected data and the fencing authority it has accepted. A successful mutation advances them together. If the comparison happens first and the write occurs separately, another owner can intervene between those operations, recreating the original gap inside the storage path.
DynamoDB conditional expressions and Azure Cosmos DB ETags support atomic conditions at the point where state changes. A multicloud design using these systems can combine conditional writes with time-bound leases and fencing tokens. The token still needs a clear contract for how it will be enforced. Support for conditional writes alone does not set the ownership order that the application accepts.
Some targets cannot enforce that contract directly. A plain shared filesystem or third-party API without version preconditions cannot compare and store fencing authority when an effect arrives. An external write may instead need a gateway that owns durable fence state, the target’s version preconditions, or an idempotent workflow with reconciliation. These alternatives require careful scoping because fencing’s protection is limited to mutations. It does not freshen an old read, revoke an issued credential, or undo an external effect that already committed.
AI agents make the paused-client window dramatically larger
Traditional software threads operate with sub-millisecond execution windows, while a complex agent reasoning-and-tool step typically requires 3–30 seconds of inference and validation. When a lease is held across reasoning, slow inference, API throttling, and network delay can use up time even when the work makes no immediate storage operation.
A zombie agent is an old holder that resumes after that exposure has outlasted its lease. The coordinator has already granted ownership to a second agent, yet both agents believe they have exclusive authority. Their work can then conflict beyond individual database writes. Multi-agent concurrency failures can include reasoning corruption, circular delegation deadlocks, and cascading execution failures. Two triage agents handling the same refund show the financial risk when both check balance > 0 and both make external payment API calls.
Uncoordinated parallel agents can create merge conflicts that consume CI compute, spend token budgets on resolution attempts, and leave maintainers reconciling the remainder. The cost per landed change becomes a more useful measure than the number of PRs opened. The Semantic Mutex pattern addresses contention earlier by having the orchestrator request an exclusive lease on a target semantic token before prompt construction or an LLM API call. That keeps workflow coordination separate from database row locking, but protected mutations still need resource-side fencing.
How production systems have implemented fencing for agent workloads
Agent infrastructure is applying these controls at workflow boundaries as well as in storage. Gastown, an open-source multi-agent orchestrator, combines a coordinator, git-backed issue tracking, health watchdogs, and a serialized merge queue. Its sequential merge serialization acts as a structural equivalent of a fencing guard at the repository boundary. The repository receives changes through a controlled acceptance path. This illustrates boundary enforcement without claiming that a serialized queue and a numeric fencing token are identical mechanisms.
GitHub Actions OpenID Connect provides a complementary identity control. As of April 2, 2026, repository custom property claims in its OIDC tokens are generally available. These claims can support authorization-scoped identity traveling with cloud writes, but they do not establish increasing ownership order. Identity and freshness answer different questions at acceptance time. A write can present valid identity while originating from a holder whose lease is no longer current.
A watchdog checks health, a merge queue controls which changes enter the repository, and an identity token supports authorization. Proof that one of these controls works should not count as proof that another does. For a protected mutation, the acceptance boundary must be able to reject old authority, either by comparing tokens or by using a structural serialization rule that fits that boundary.
Where fencing tokens fit in a composable agent infrastructure stack
A composable Internal Developer Platform can make fencing an infrastructure responsibility rather than a separate implementation in every service. Components built for specific tasks connect through thin integration layers, and the coordination layer issues and validates tokens while sending production signals back to agents. Those signals include application logs, metrics, distributed traces, deployment status, and error rates. A standard interface connects execution to its operational consequences. The platform becomes a resource-side authority only where its validation actually governs acceptance of the write itself.
This favors tooling designed around agent concurrency and latency. A fencing-aware merge queue can enforce order at the repository boundary, while analysis of agent transcripts can show lost leases and retries that were not needed. High-performance code storage is another component, and its consistency semantics must fit the needs of cloud-native agents. These capabilities can be assembled as needed. Changing a human-first workflow does not provide these capabilities by itself, because coordination built for humans does not set the acceptance rules that paused agents need.
The resulting division of responsibility is explicit. Agents perform reasoning and tool work, coordinators assign ordered authority, and protected systems decide whether an effect is still admissible. Production feedback helps the platform show where coordination failed, but enforcement is still needed. Under that contract, an agent may pause, lose its lease, and remain unaware of the change without retaining the right to overwrite work accepted from a newer owner.


