Resource Lease
Running multiple AI agents in parallel saves hours — right up until two of them edit the same shared spreadsheet, branch, API contract, or source file at the same time. The second worker resolves the conflict on its own, silently wipes out the first worker's work, and both workers report green while the combined result is broken.
Resource Lease lets only one job at a time modify a shared resource by issuing an expiring exclusive Lease paired with a monotonically rising fencing token. Active workers renew their lease as they make progress; if a worker freezes, the lease runs out automatically so waiting jobs proceed, while the rising token rejects any late write if the frozen worker ever wakes back up.
Lease
Why parallel edits and plain locks both break
Whenever two parallel jobs must touch the same shared artifact — a budget workbook, a shared staging database, a release branch, or a core code module — each worker begins from the same baseline copy. The first job lands cleanly; the second resolves the conflict by keeping its own version and quietly drops the first job's change.
Adding a naive lock solves overwrites only until a worker crashes: an ordinary lock stays held forever until a human notices and clears it manually. Making the lock expire solves crashes only until a paused worker wakes back up after expiry and still writes on top of the next holder's work.
Resource Lease closes all three gaps with three rules enforced in hub code:
-
At most one active lease per resource key. While a resource is held,
other callers receive
resource_heldnaming the holder and expiry time, so they work on uncontested tasks and park cleanly until notified. -
Leases expire on the hub's clock unless renewed by progress. Only the
named
attempt_idmay extendexpires_at; a frozen worker automatically loses the resource without human intervention, and expired leases never revive. -
Every write carries a rising fencing token checked atomically. Each
grant issues a strictly higher integer
token(41, 42, 43...). At the write boundary, the hub checks that the token matches the active lease in one transaction — rejecting revived zombies withstale_lease_token.
Why do you need both an expiry time and a fencing token? Expiry guarantees liveness — a stalled worker never blocks a shared resource indefinitely. The fencing token guarantees safety — even if a worker pauses for twenty minutes and sends a delayed write with its old token, the hub rejects it before it can touch the resource.
Architecture and participants
The Hub owns the Lease
table, allocates monotonically rising fencing tokens, and places a mandatory
Write check right at the boundary where changes become shared (such as a
merge step or shared-file commit). Workers edit locally freely, but nothing reaches the
shared resource without passing the token check.
Lease binds one shared resource key to one
Job, one Attempt, an
expiry timestamp, and a rising token. The hub checks that token atomically before any
write lands on the shared resource.
resource_key,
issues strictly rising tokens, enforces the write check atomically, expires stale
leases on its own clock, and wakes waiting jobs when a lease ends.
Lease records who may write and until when; the
Shared resource is a canonical file, branch, or interface keyed
consistently across all callers.
Execution flow
Toggle between the normal path — where two jobs take turns cleanly under tokens 41 and 42 — and the frozen-holder path — where Worker 1's lease expires automatically, Worker 2 lands its change under token 42, and Worker 1's late write with token 41 is fenced out.
Worker 1 holds token 41 while Worker 2 waits cleanly. Progress reports renew token 41 until Worker 1 lands its change and releases the lease; the hub immediately grants token 42 to Worker 2, which builds directly on top of Worker 1's update.
Same steps 1–4 as normal flow; begins while Worker 1 holds token 41 and Worker 2 is waiting.
When Worker 1 freezes, token 41 expires on the hub's clock with zero human action.
Worker 2 takes token 42 and lands its change. When Worker 1 later wakes up and submits
with token 41, the hub rejects it with stale_lease_token
so Worker 1 acquires token 43 and reapplies on top of Worker 2's change.
Concrete examples
Resource Lease protects any shared mutable asset where two agents working in parallel would otherwise overwrite each other's changes.
Example 1 — Shared Q4 operating budget workbook
No code or unit tests- Shared resource
-
finance:q4-operating-budget.xlsx, where headcount and infrastructure tabs both feed a shared cash-flow summary tab. - Serialized turns
-
Analyst agent 1 acquires token 18 (10-minute term) to update engineering headcount.
Analyst agent 2 requests the workbook to revise cloud spend, gets
resource_held, finishes its independent vendor quote tables, and waits. Once Analyst 1 saves and releases token 18, Analyst 2 receives token 19 and applies cloud-spend edits on top of the updated headcount totals. - Freeze safety
-
If Analyst 1's session hangs before saving, token 18 expires automatically after 10
minutes so finance close does not stall — and if Analyst 1 later reconnects, token 18
is rejected (
stale_lease_token) before it can overwrite Analyst 2's saved workbook.
Example 2 — Concurrent webhook retries and logging edits
Everyday engineering- Shared resource
-
acme/api:lib/acme/delivery.ex, which both the webhook-retry job (Worker 1) and the delivery-logging job (Worker 2) must edit. - Freeze & expiry
-
Worker 1 acquires token 41 until 2:10 p.m.; Worker 2 is refused at 2:05 p.m. and
waits. At 2:06 p.m., Worker 1's container freezes. At 2:10 p.m., the hub marks token
41
expired, grants token 42 to Worker 2, and merges Worker 2's logging change at 2:18 p.m. - Zombie fenced
-
At 2:30 p.m., Worker 1 wakes up and submits its diff carrying token 41. The hub
rejects the write with
stale_lease_token— leaving Worker 2's logging intact. Worker 1 acquires token 43, rebases onto the updated file, and lands retries cleanly so both features survive.
What this pattern is NOT — Disjoint files or auto-mergeable logs
Negative example- Request
- Two workers modifying completely separate modules, or appending independent lines to a changelog that version control merges safely without ambiguity.
- Why skip it
- Splitting work across disjoint resources is always faster than serializing behind a lease. And if no central service actually checks the token where writes land, a lease is merely a polite suggestion rather than an enforceable guarantee.
When to use and when to skip
Use Resource Lease when
- Parallel jobs must modify the same shared file, release branch, API contract, or test environment.
- Merging two concurrent edits mechanically is risky (e.g. migration sequences, shared config, financial models).
- Every write passes through one central hub or service capable of verifying the fencing token atomically.
Skip it when
- The lead agent can simply split work into non-overlapping files or modules (always try disjoint splits first).
- Automated merging handles concurrent additions safely without semantic conflict.
- No write boundary enforces the token — unchecked leases fail open the first time an agent forgets.
Data model and hub invariants
Resource Lease defines one durable table — leases —
referencing jobs and
attempts (defined by
Durable Job). Renewals extend
expires_at in place; re-acquiring a resource later always
creates a new row with a higher fencing token.
Lease belongs to one Job
and one Attempt of that job. Only the named attempt may
renew or write under that lease's fencing token.
Table: leases
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique lease identifier. |
| resource_kind | text | NOT NULL | CHECK (resource_kind IN ('file', 'branch', 'interface')). |
| resource_key | text | NOT NULL | Canonical resource name (e.g. acme/api:lib/acme/delivery.ex). |
| job_id | uuid | NOT NULL, FK | References jobs(id) holding the lease. |
| attempt_id | uuid | NOT NULL, FK | References attempts(id); only this attempt may renew or write. |
| token | bigint | NOT NULL | Monotonically increasing fencing token drawn from a Postgres sequence. |
| granted_at | timestamptz | NOT NULL | Hub timestamp when the lease was granted. |
| expires_at | timestamptz | NOT NULL | When the lease expires unless renewed; moved forward on progress renewal. |
| released_at | timestamptz | NULLABLE | Set when the lease ends (explicitly, on expiry, or on attempt replacement). |
| release_reason | text | NULLABLE | CHECK (release_reason IN ('finished', 'expired', 'job_closed', 'attempt_replaced', 'revoked')). |
Seven hub invariants
-
01At most one active lease per resource_key Database constraint
A partial unique index
UNIQUE (resource_key) WHERE released_at IS NULLplus expiry sweep before grant ensures no two jobs hold the same resource at once; contenders receiveresource_held. -
02Fencing tokens strictly increase across grants Database constraint
Allocated from a monotonic database sequence with
UNIQUE (resource_key, token)so every subsequent lease on a resource carries a strictly higher number. -
03The leased attempt belongs to the leased job Database constraint
Composite foreign key
(job_id, attempt_id)referencingattempts(job_id, id)prevents mismatched ownership; the hub rejects mismatches withattempt_job_mismatch. -
04Only the named attempt may renew; ended leases never revive Hub guard
renewrejects another attempt withlease_not_owned_by_attemptand rejects any expired or released lease withstale_lease_token. -
05Writes verify the active fencing token atomically Hub guard
commit_writeexpires overdue leases on the hub's clock, verifiestokenagainst the active lease, and executes the write callback inside the same guarded transaction — failing withstale_lease_tokenbefore touching the resource if the token is no longer current. -
06released_at and release_reason are always set together Database constraint
CHECK ((released_at IS NULL) = (release_reason IS NULL)). The first hub sweep or acquire afterexpires_atstampsrelease_reason = 'expired'. -
07Closing a job or replacing an attempt releases its leases atomically Hub guard
release_for_attemptcloses all active leases held by the outgoing attempt withjob_closedorattempt_replacedin the same transaction, freeing waiting jobs immediately.
Reference implementation
The same lease grant, progress renewal, expiry sweep, and fencing-token check in Lean, TypeScript, Python, and Elixir.
-- Hub guards for Resource Lease (expiring lock + monotonic fencing token)
import Std.Data.HashMap
inductive ResourceKind where
| file | branch | interface
deriving Repr, BEq, DecidableEq
inductive ReleaseReason where
| finished | expired | jobClosed | attemptReplaced | revoked
deriving Repr, BEq, DecidableEq
structure Lease where
id : String
resourceKind : ResourceKind
resourceKey : String
jobId : String
attemptId : String
token : Nat
grantedAt : Nat
expiresAt : Nat
releasedAt : Option Nat := none
releaseReason : Option ReleaseReason := none
deriving Repr
inductive HubError where
| attemptJobMismatch
| resourceHeld
| staleLeaseToken
| leaseNotOwnedByAttempt
deriving Repr, BEq, DecidableEq
structure LeaseHub where
nextToken : Nat := 41
leases : List Lease := []
attemptToJob : Std.HashMap String String := {}
namespace LeaseHub
def termSec : Nat := 600
def isOpen (l : Lease) : Bool := l.releasedAt.isNone
def activeFor (hub : LeaseHub) (key : String) : Option Lease :=
hub.leases.find? fun l => l.resourceKey == key && isOpen l
def activeByToken (hub : LeaseHub) (token : Nat) : Option Lease :=
hub.leases.find? fun l => l.token == token && isOpen l
-- Swap one lease (matched by its unique token) for its updated copy.
def replaceLease (hub : LeaseHub) (updated : Lease) : LeaseHub :=
{ hub with leases := hub.leases.map fun l => if l.token == updated.token then updated else l }
def sweepExpired (hub : LeaseHub) (nowSec : Nat) : LeaseHub :=
{ hub with
leases := hub.leases.map fun l =>
if isOpen l && l.expiresAt <= nowSec then
{ l with releasedAt := some l.expiresAt, releaseReason := some .expired }
else l }
def acquire (hub : LeaseHub) (kind : ResourceKind) (key jobId attemptId : String)
(nowSec : Nat) : Except HubError (Lease × LeaseHub) := do
-- `hub[k]?` looks a key up in the HashMap, giving an Option
unless hub.attemptToJob[attemptId]? == some jobId do throw .attemptJobMismatch
let hub := hub.sweepExpired nowSec
if (hub.activeFor key).isSome then throw .resourceHeld
let token := hub.nextToken
let lease : Lease := {
id := s!"lease-{token}", resourceKind := kind, resourceKey := key,
jobId, attemptId, token, grantedAt := nowSec, expiresAt := nowSec + termSec }
return (lease, { hub with leases := lease :: hub.leases, nextToken := token + 1 })
def renew (hub : LeaseHub) (token : Nat) (attemptId : String) (nowSec : Nat) :
Except HubError (Lease × LeaseHub) := do
let hub := hub.sweepExpired nowSec
let some lease := hub.activeByToken token | throw .staleLeaseToken
unless lease.attemptId == attemptId do throw .leaseNotOwnedByAttempt
let updated := { lease with expiresAt := nowSec + termSec }
return (updated, hub.replaceLease updated)
def release (hub : LeaseHub) (token : Nat) (reason : ReleaseReason) (nowSec : Nat) :
Except HubError (Lease × LeaseHub) := do
let hub := hub.sweepExpired nowSec
let some lease := hub.activeByToken token | throw .staleLeaseToken
let closed := { lease with releasedAt := some nowSec, releaseReason := some reason }
return (closed, hub.replaceLease closed)
-- Only .jobClosed or .attemptReplaced; the `h` argument makes the caller prove it.
def releaseForAttempt (hub : LeaseHub) (attemptId : String) (reason : ReleaseReason)
(_h : reason = .jobClosed ∨ reason = .attemptReplaced) (nowSec : Nat) : LeaseHub :=
let hub := hub.sweepExpired nowSec
{ hub with
leases := hub.leases.map fun l =>
if l.attemptId == attemptId && isOpen l then
{ l with releasedAt := some nowSec, releaseReason := some reason }
else l }
-- `apply` is the write itself; it runs only if `token` still holds the lease on `key`.
def commitWrite {α : Type} (hub : LeaseHub) (key : String) (token nowSec : Nat)
(apply : Unit → α) : Except HubError α :=
match (hub.sweepExpired nowSec).activeFor key with
| some active => if active.token == token then .ok (apply ()) else .error .staleLeaseToken
| none => .error .staleLeaseToken
-- A fresh hub's token counter starts at 41, as in the example trace.
theorem empty_next_token : ({} : LeaseHub).nextToken = 41 := rfl
end LeaseHub
// Hub guards for Resource Lease (expiring lock + monotonic fencing token)
type ResourceKind = "file" | "branch" | "interface";
type ReleaseReason = "finished" | "expired" | "job_closed" | "attempt_replaced" | "revoked";
interface Lease {
id: string;
resourceKind: ResourceKind;
resourceKey: string;
jobId: string;
attemptId: string;
token: number;
grantedAt: number;
expiresAt: number;
releasedAt: number | null;
releaseReason: ReleaseReason | null;
}
class LeaseHub {
private readonly termSec = 600;
private nextToken = 41;
private leases: Lease[] = [];
private attemptToJob = new Map<string, string>();
acquire(
kind: ResourceKind,
key: string,
jobId: string,
attemptId: string,
nowSec: number
): Lease {
if (this.attemptToJob.get(attemptId) !== jobId) {
throw new Error("attempt_job_mismatch");
}
this.sweepExpired(nowSec);
if (this.activeFor(key)) throw new Error("resource_held");
const token = this.nextToken++;
const lease: Lease = {
id: `lease-${token}`,
resourceKind: kind,
resourceKey: key,
jobId,
attemptId,
token,
grantedAt: nowSec,
expiresAt: nowSec + this.termSec,
releasedAt: null,
releaseReason: null
};
this.leases.push(lease);
return lease;
}
renew(token: number, attemptId: string, nowSec: number): Lease {
this.sweepExpired(nowSec);
const lease = this.leases.find((l) => l.token === token && l.releasedAt === null);
if (!lease) throw new Error("stale_lease_token");
if (lease.attemptId !== attemptId) throw new Error("lease_not_owned_by_attempt");
lease.expiresAt = nowSec + this.termSec;
return lease;
}
release(token: number, reason: ReleaseReason, nowSec: number): Lease {
this.sweepExpired(nowSec);
const lease = this.leases.find((l) => l.token === token && l.releasedAt === null);
if (!lease) throw new Error("stale_lease_token");
lease.releasedAt = nowSec;
lease.releaseReason = reason;
return lease;
}
releaseForAttempt(attemptId: string, reason: "job_closed" | "attempt_replaced", nowSec: number): void {
this.sweepExpired(nowSec);
for (const lease of this.leases) {
if (lease.attemptId === attemptId && lease.releasedAt === null) {
lease.releasedAt = nowSec;
lease.releaseReason = reason;
}
}
}
commitWrite<T>(key: string, token: number, nowSec: number, apply: () => T): T {
this.sweepExpired(nowSec);
const active = this.activeFor(key);
if (!active || active.token !== token) {
throw new Error("stale_lease_token");
}
return apply();
}
private activeFor(key: string): Lease | undefined {
return this.leases.find((l) => l.resourceKey === key && l.releasedAt === null);
}
private sweepExpired(nowSec: number): void {
for (const l of this.leases) {
if (l.releasedAt === null && l.expiresAt <= nowSec) {
l.releasedAt = l.expiresAt;
l.releaseReason = "expired";
}
}
}
}
# Hub guards for Resource Lease (expiring lock + monotonic fencing token)
from dataclasses import dataclass
from typing import Callable, Literal, Optional, TypeVar
T = TypeVar("T")
ResourceKind = Literal["file", "branch", "interface"]
ReleaseReason = Literal["finished", "expired", "job_closed", "attempt_replaced", "revoked"]
@dataclass
class Lease:
id: str
resource_kind: ResourceKind
resource_key: str
job_id: str
attempt_id: str
token: int
granted_at: int
expires_at: int
released_at: Optional[int] = None
release_reason: Optional[ReleaseReason] = None
class HubError(Exception):
pass
class LeaseHub:
TERM_SEC = 600
def __init__(self) -> None:
self.next_token = 41
self.leases: list[Lease] = []
self.attempt_to_job: dict[str, str] = {}
def acquire(
self, kind: ResourceKind, key: str, job_id: str, attempt_id: str, now_sec: int
) -> Lease:
if self.attempt_to_job.get(attempt_id) != job_id:
raise HubError("attempt_job_mismatch")
self._sweep_expired(now_sec)
if self._active_for(key) is not None:
raise HubError("resource_held")
token = self.next_token
self.next_token += 1
lease = Lease(
id=f"lease-{token}",
resource_kind=kind,
resource_key=key,
job_id=job_id,
attempt_id=attempt_id,
token=token,
granted_at=now_sec,
expires_at=now_sec + self.TERM_SEC,
)
self.leases.append(lease)
return lease
def renew(self, token: int, attempt_id: str, now_sec: int) -> Lease:
self._sweep_expired(now_sec)
lease = self._active_by_token(token)
if lease is None:
raise HubError("stale_lease_token")
if lease.attempt_id != attempt_id:
raise HubError("lease_not_owned_by_attempt")
lease.expires_at = now_sec + self.TERM_SEC
return lease
def release(self, token: int, reason: ReleaseReason, now_sec: int) -> Lease:
self._sweep_expired(now_sec)
lease = self._active_by_token(token)
if lease is None:
raise HubError("stale_lease_token")
lease.released_at = now_sec
lease.release_reason = reason
return lease
def release_for_attempt(
self, attempt_id: str, reason: Literal["job_closed", "attempt_replaced"], now_sec: int
) -> None:
self._sweep_expired(now_sec)
for lease in self.leases:
if lease.attempt_id == attempt_id and lease.released_at is None:
lease.released_at = now_sec
lease.release_reason = reason
def commit_write(self, key: str, token: int, now_sec: int, apply: Callable[[], T]) -> T:
self._sweep_expired(now_sec)
active = self._active_for(key)
if active is None or active.token != token:
raise HubError("stale_lease_token")
return apply()
def _active_for(self, key: str) -> Optional[Lease]:
return next((l for l in self.leases if l.resource_key == key and l.released_at is None), None)
def _active_by_token(self, token: int) -> Optional[Lease]:
return next((l for l in self.leases if l.token == token and l.released_at is None), None)
def _sweep_expired(self, now_sec: int) -> None:
for lease in self.leases:
if lease.released_at is None and lease.expires_at <= now_sec:
lease.released_at = lease.expires_at
lease.release_reason = "expired"
# Hub guards for Resource Lease (pure functional core)
defmodule LeaseHub do
@term_sec 600
defstruct next_token: 41, leases: [], attempt_to_job: %{}
def acquire(%LeaseHub{} = hub, kind, key, job_id, attempt_id, now_sec) do
hub = sweep_expired(hub, now_sec)
cond do
Map.get(hub.attempt_to_job, attempt_id) != job_id ->
{:error, :attempt_job_mismatch}
active_for(hub, key) != nil ->
{:error, :resource_held}
true ->
lease = %{
id: "lease-#{hub.next_token}",
resource_kind: kind,
resource_key: key,
job_id: job_id,
attempt_id: attempt_id,
token: hub.next_token,
granted_at: now_sec,
expires_at: now_sec + @term_sec,
released_at: nil,
release_reason: nil
}
{:ok, lease, %{hub | leases: [lease | hub.leases], next_token: hub.next_token + 1}}
end
end
def renew(%LeaseHub{} = hub, token, attempt_id, now_sec) do
hub = sweep_expired(hub, now_sec)
case Enum.find(hub.leases, &(&1.token == token and is_nil(&1.released_at))) do
nil ->
{:error, :stale_lease_token}
%{attempt_id: ^attempt_id} = lease ->
updated = %{lease | expires_at: now_sec + @term_sec}
{:ok, updated, replace_lease(hub, lease, updated)}
_other ->
{:error, :lease_not_owned_by_attempt}
end
end
def release(%LeaseHub{} = hub, token, reason, now_sec) do
hub = sweep_expired(hub, now_sec)
case Enum.find(hub.leases, &(&1.token == token and is_nil(&1.released_at))) do
nil ->
{:error, :stale_lease_token}
lease ->
closed = %{lease | released_at: now_sec, release_reason: reason}
{:ok, closed, replace_lease(hub, lease, closed)}
end
end
def release_for_attempt(%LeaseHub{} = hub, attempt_id, reason, now_sec)
when reason in [:job_closed, :attempt_replaced] do
hub = sweep_expired(hub, now_sec)
leases =
Enum.map(hub.leases, fn lease ->
if lease.attempt_id == attempt_id and is_nil(lease.released_at),
do: %{lease | released_at: now_sec, release_reason: reason},
else: lease
end)
{:ok, %{hub | leases: leases}}
end
def commit_write(%LeaseHub{} = hub, key, token, now_sec, apply_fn)
when is_function(apply_fn, 0) do
case active_for(sweep_expired(hub, now_sec), key) do
%{token: ^token} -> {:ok, apply_fn.()}
_ -> {:error, :stale_lease_token}
end
end
defp active_for(hub, key),
do: Enum.find(hub.leases, &(&1.resource_key == key and is_nil(&1.released_at)))
defp replace_lease(hub, old, updated),
do: %{hub | leases: [updated | List.delete(hub.leases, old)]}
defp sweep_expired(hub, now_sec) do
leases =
Enum.map(hub.leases, fn l ->
if is_nil(l.released_at) and l.expires_at <= now_sec,
do: %{l | released_at: l.expires_at, release_reason: :expired},
else: l
end)
%{hub | leases: leases}
end
end
Freeze, expiry, and stale-token trace
Walking Example 2 (concurrent webhook retries and logging edits) through
these guards shows token 41 expiring cleanly when Worker 1 freezes, Worker 2 landing under
token 42, and Worker 1's revived write rejected with
stale_lease_token:
// at("HH:MM") converts clock time to seconds since midnight (at("14:00") = 50400; term = 600s)
1. lease_a = hub.acquire("file", "acme/api:lib/acme/delivery.ex", job_retry, attempt_a1, at("14:00"))
-> ok (token = 41; expiresAt = at("14:10") = 51000)
2. hub.acquire("file", "acme/api:lib/acme/delivery.ex", job_logging, attempt_b1, at("14:05"))
-> error: resource_held (held by job_retry until 14:10; job_logging parks)
3. // Worker 1 freezes at 14:06; lease expires automatically at 14:10 (51000s)
lease_b = hub.acquire("file", "acme/api:lib/acme/delivery.ex", job_logging, attempt_b1, at("14:10"))
-> ok (token 41 marked released/expired; granted token = 42; expiresAt = at("14:20"))
4. hub.commitWrite("acme/api:lib/acme/delivery.ex", 42, at("14:18"), () => mergeDiff(loggingDiff))
hub.release(42, "finished", at("14:18"))
-> ok (token 42 verified atomically with mergeDiff; lease released)
5. // Worker 1 wakes up at 14:30 and submits its old diff with token 41
hub.commitWrite("acme/api:lib/acme/delivery.ex", 41, at("14:30"), () => mergeDiff(retryDiff))
-> error: stale_lease_token (mergeDiff never runs; Worker 2's change untouched)
6. lease_a2 = hub.acquire("file", "acme/api:lib/acme/delivery.ex", job_retry, attempt_a1, at("14:31"))
-> ok (token = 43; Worker 1 rebases onto logging and lands retries cleanly)
Tradeoffs and practical guidance
Resource Lease trades parallel throughput on contested assets for guaranteed conflict-free writes. Weigh three honest tradeoffs:
- Forced serialization on hot resources: the broader the leased resource (e.g. an entire branch versus one file), the more jobs queue up behind it.
- Lease duration is a balancing act: a term that is too short risks revoking a slow but healthy worker; a term that is too long forces waiting jobs to idle behind a frozen session.
- Protects the resource, not whole-system coherence: two jobs editing different files never contend on a lease yet can still clash semantically — Orchestrator-Workers' integration job is still required.
Practical implementation notes
- Enforce the token where changes become shared: a worker can always edit its own local checkout; the hub must verify the fencing token at merge, commit, or write time using its own clock.
- Renew on concrete progress, not bare pings: tying renewals to Progress Heartbeat reports prevents a worker stuck in a pointless retry loop from holding a file forever.
- Acquire multi-resource leases in one atomic request: if a job needs two files, grant both together or neither — acquiring leases one by one invites classic AB/BA deadlocks.
-
Choose canonical keys: normalize resource keys
(
repo:path) so two jobs targeting the same file never accidentally mint two different keys. - Handle half-finished shared environments explicitly: files only mutate at merge, so expiry leaves nothing dirty; if a lease guards a shared staging database, route expired leases to the lead agent for cleanup before re-granting.
Known uses and related patterns
- Kubernetes Leases: coordinates leader election across replicas using time-limited lease objects with explicit duration and renewal timestamps; Resource Lease applies the same timed turn-taking to agent jobs sharing mutable artifacts.
- Git LFS file locking: reserves binary files under one user and rejects pushes from non-holders on supporting servers; Resource Lease adds automatic expiry and fencing tokens so dead sessions never leave permanent locks.
- Claude Code agent teams: recommends assigning disjoint files to parallel teammates to avoid overwrites; Resource Lease handles the cases where two jobs genuinely must touch the same file or contract.
- Volgenic: uses expiring leases and monotonically fenced tokens across distributed machine jobs and build publication, alongside serialized base-branch merge queues.
- Unmesh Joshi's Lease, Martin Kleppmann's Fencing Token & Martin Fowler's Pessimistic Offline Lock: classic distributed-systems and enterprise-architecture foundations combined here for asynchronous agent execution.
Related patterns
- Durable Job — most easily confused with Resource Lease; Durable Job tracks who owns a unit of work, while Resource Lease controls which job may mutate a shared resource right now.
- Progress Heartbeat — drives progress-based lease renewals and detects stalled sessions in parallel with expiry.
- Resumable Wait — parks a job that receives
resource_heldagainst theresource_keyand wakes it automatically when the lease ends. - Orchestrator-Workers — identifies shared resources at split time and verifies combined coherence after leased edits land.