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.

Group Work structure
Also known as Expiring Lock, Lock with Fencing Token, Exclusive Checkout
Core rule Only the active lease's fencing token may write; expired leases never revive
Defines records 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:

  1. At most one active lease per resource key. While a resource is held, other callers receive resource_held naming the holder and expiry time, so they work on uncontested tasks and park cleanly until notified.
  2. Leases expire on the hub's clock unless renewed by progress. Only the named attempt_id may extend expires_at; a frozen worker automatically loses the resource without human intervention, and expired leases never revive.
  3. 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 with stale_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.

Uncoordinated parallel edits Worker 1 & Worker 2 start Both edit same copy of shared resource Worker 1 lands change first Worker 2 still holds outdated copy Worker 2 resolves conflict alone Keeps own version; drops Worker 1 Silent regression ships live Both local checks looked green Resource Lease Worker 1 holds lease (token 41) Worker 2 gets resource_held & waits Hub checks token 41 & lands Lease ends (or expires if frozen) Worker 2 gets token 42 Builds on latest; old token 41 fenced Both changes survive cleanly Zero deadlocks; zero late overwrites
Without a lease, two parallel workers edit the same baseline and the second quietly drops the first worker's changes. Resource Lease serializes access to the shared resource with expiring tokens so every change builds on the latest state.

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.

Lead agent Names shared resources Hub Grants & expires leases Write check token == active lease? Hub durable lease & ownership records Job Holds 0..n leases Attempt Only owner may renew Lease key, token, expires_at Worker 1 (Holder) Writes with token 41 Worker 2 (Waiting) Wakes when lease ends Shared resource File, branch, interface
Each 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.
Lead agent
Identifies shared resources when splitting a request (avoiding shared resources whenever disjoint splits work) and can explicitly revoke a lease early.
Hub
Maintains at most one active lease per 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.
Workers (Worker 1, Worker 2)
Acquire a lease before editing a shared resource, renew it through real progress reports, and attach their fencing token to every write.
Lease & Shared resource
The 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 Hub Worker 2 Shared resource 1. Acquire lease on resource 2. Grant token 41 (10m term) 3. Acquire lease on same key 4. Refuse: resource_held (waits) 5. Report progress; renew token 41 6. Submit change with token 41 7. Verify 41; apply & release lease 8. Grant token 42 & wake Worker 2 9. Build on latest; send token 42 10. Verify 42; apply both changes

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.

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.

Job PK id (Durable Job) Attempt PK id FK job_id (Durable Job) 1 n Lease PK id resource_kind (file|branch|interface) resource_key FK job_id FK attempt_id token (monotonic bigint) granted_at expires_at released_at? release_reason? 1 n 1 n
Each 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

  1. 01
    At most one active lease per resource_key Database constraint

    A partial unique index UNIQUE (resource_key) WHERE released_at IS NULL plus expiry sweep before grant ensures no two jobs hold the same resource at once; contenders receive resource_held.

  2. 02
    Fencing 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.

  3. 03
    The leased attempt belongs to the leased job Database constraint

    Composite foreign key (job_id, attempt_id) referencing attempts(job_id, id) prevents mismatched ownership; the hub rejects mismatches with attempt_job_mismatch.

  4. 04
    Only the named attempt may renew; ended leases never revive Hub guard

    renew rejects another attempt with lease_not_owned_by_attempt and rejects any expired or released lease with stale_lease_token.

  5. 05
    Writes verify the active fencing token atomically Hub guard

    commit_write expires overdue leases on the hub's clock, verifies token against the active lease, and executes the write callback inside the same guarded transaction — failing with stale_lease_token before touching the resource if the token is no longer current.

  6. 06
    released_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 after expires_at stamps release_reason = 'expired'.

  7. 07
    Closing a job or replacing an attempt releases its leases atomically Hub guard

    release_for_attempt closes all active leases held by the outgoing attempt with job_closed or attempt_replaced in 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

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:

Execution trace: Example 2 (delivery.ex freeze and stale-token rejection)
// 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_held against the resource_key and wakes it automatically when the lease ends.
  • Orchestrator-Workers — identifies shared resources at split time and verifies combined coherence after leased edits land.