Durable and Asynchronous Agent Work
Design agent runners for recovery with event logs, leases, idempotency keys, retries, deadlines, and reconciliation.
Language AI HandbookAll chapters Durable and Asynchronous Agent Work
Checkpoints, resumability, queues, idempotency, retries, deadlines, and state across long-running workflows.
You can finish three tool calls and crash before writing the fourth result. The next worker needs to know which steps are safe to run again and which external operations still have an unknown outcome. We will build a small runner that keeps those questions separate.
We will use a local SQLite runner to model recovery across crashes, expired claims, and retries. It replays a committed trace and rejects stale workers’ updates to task events and task state. The result cache is stored separately from that guarded transition. A worker can cache a result even if its subsequent task update is rejected.
- The checkpointer: how the agent's memory of "where I am" is persisted.
- The queue/lease layer: how work is dispatched to workers and reclaimed when a worker disappears.
- The external side-effect boundary handles operations outside the local task-state transaction. An external service may have its own transaction or idempotency contract.
An agent loop can stop between any two steps. Use an event record to resume work from the last committed step and account for any operation that may have run outside that record. Agent Architectures: Control Loops, State & Planning describes the underlying loop.
The plan:
- Motivate why long-running agent work needs explicit durability primitives.
- Build the concepts: the event log, checkpoints, leases, idempotency keys, retries with backoff, deadlines, and compensation.
- Walk a concrete worked example of a crash and a duplicate.
- Implement a local SQLite fixture for replay, lease expiry, retry budgets, idempotency, and reconciliation while the store remains open.
- Explain when retries can repeat an effect and which guarantees require cooperation from the service performing it.
Durable Progress Across Restarts
If your application keeps its plan only in process memory, another worker cannot recover it after a restart. A long task can lose a draft or repeat calls when its worker disappears. A persisted trace helps a replacement worker recover committed progress. These durations and counts are illustrations, and the notebook runs locally without calling any models or services.
- Make 30–80 model calls.
- Fetch 200 web pages, some slow or failing with 3-retry logic.
- Take 5–40 minutes of wall-clock time.
- Cost real money per model call.
If the container that's running it gets preempted (spot instances, deploys, OOM killers, kernel OOM, user closing the browser), everything in memory evaporates. Without durability you get one of two outcomes: silent loss (the task disappears and nobody knows) or duplicate work (the queue re-delivers the task to a new worker, which starts over from scratch). Both are bad, and the second can be catastrophic when the lost work includes a side effect like "pay this vendor".
Reassigning a worker helps the task make progress. Checking ownership and upstream outcomes helps avoid incorrect writes and repeated effects.
Durability turns occasional disaster into a routine, bounded cost. We want:
- Bounded rework: resume from recorded, completed steps and account for the in-flight operation.
- Duplicate effects: a receiving service can enforce one logical operation within its supported idempotency scope and lifetime.
- Accepted work: retain enough state to recover, complete, or report a terminal failure.
- Deadline awareness: skip a new step if its estimated cost exceeds the remaining budget.
These are testable goals under the service’s stated failure model. When an external outcome cannot be established, record it as unresolved and keep the identifying information for reconciliation.
These problems occur in queue-backed workflows. Amazon SQS standard queues can deliver a message more than once. Temporal records workflow events and replays them to rebuild state, using recorded completed activity results during replay. Our fixture is a single-machine example and implements its own much smaller protocol. Amazon SQS delivery Temporal durable execution
Temporal replays deterministic Workflow code using completed Activity results already recorded in Event History. If a Worker performs an Activity effect and crashes before Temporal records completion, the Activity can execute again when its retry policy permits. The recurring operation needs its own idempotency or reconciliation plan. Temporal Activity Definition
Persistence keeps data beyond a process lifetime. Durability here concerns committed state surviving the failure model. Keeping that state consistent with concurrent workers requires a separate concurrency protocol, and preventing duplicate external effects requires cooperation at their own boundary.
Imagine two workers both read the same snapshot, append a different event in memory, and overwrite the snapshot. The later write can drop the first addition. An atomic append or a checked state transition prevents that lost-update pattern.
Core concepts
Before any code, let's fix vocabulary. Each term maps to a specific failure it prevents.
The event log and checkpoints
The cleanest mental model for a durable agent is an append-only event log. Every meaningful step the agent takes is an event:
task_startedtool_called(tool="search", input=..., call_id="c1")tool_result(call_id="c1", output=...)model_response(step=3, text=...)task_completedtask_failed(reason=...)
An agent can reconstruct state by folding recorded events in order. This toy rebuilds its message trace and completed-step counter. A checkpoint stores a materialized state at a named offset so recovery can replay only later events. The toy replays the whole short log and does not persist a separate snapshot.
An append-only log preserves prior entries under the store’s transaction and integrity guarantees. The next worker uses committed events to reconstruct progress. A call may still have taken effect upstream before its result reached the log.
The timeline shows four positions in one serial step. The shaded region starts when the worker invokes the tool and ends when it commits the result. The result can be unknown throughout that region.
PythonIn [2]Expand
# Interval boundaries as normalized positions along the step timeline.
interval_bounds = [
("before tool_called", 0.0, 0.30, "safe_retry_shape"),
("between log and call", 0.30, 0.45, "safe_retry_shape"),
("call invoked, result uncommitted", 0.45, 0.78, "danger_shape"),
("after tool_result", 0.78, 1.0, "safe_retry_shape"),
]
crash_marks = [0.15, 0.38, 0.62, 0.90]VisualizationOut [3]Expand

Commit an intent record before making the external call. The next worker can then identify the operation, but the intent alone does not establish whether the effect occurred. A completion record, an upstream receipt, or a source-supported reconciliation step provides a different kind of evidence.
Before the intent is committed, this worker has not sent the call. Between intent and invocation, it has a record of intent without having sent the call. From invocation until result commit, a lost response can leave the external outcome uncertain. Use the upstream idempotency contract or verify the outcome before retrying when duplicate effects matter.
Leases: how a worker claims work
A long task can't be "owned" forever by an in-memory flag, because the worker might be dead. Instead a worker leases a task: it writes "worker W holds task T until time X" to the store. If it's still working at time X, it renews the lease. If it dies, the lease expires on its own, and another worker becomes eligible to claim and resume the task from the last hardened event.
A lease is just an optimistic lock with a time-to-live:
A claim needs an atomic check and update. In this toy the SQLite write transaction serializes both operations, then advances the ownership generation. A worker can renew the same generation while the lease is active. A later writer must check ownership again inside the transaction that changes durable state.
A slow worker can remain alive after a lease expires. Liveness is therefore not inferred from ownership. Reassignment gives a new ownership generation; a stale owner cannot write to the task store when that store validates the generation.
The two panels use different units. The left estimates how often a simulated live step outlasts a lease without renewal. The right models a crash immediately after claim, plus a fixed two-second scheduling delay. Their directions illustrate the trade-off without choosing an operating point.
PythonIn [4]Expand
import numpy as np
lease_seconds = np.linspace(1.0, 30.0, 120)
lease_rng = np.random.default_rng(11)
step_times = lease_rng.lognormal(mean=np.log(2.0), sigma=0.9, size=20_000)
false_reclaim_rate = np.array(
[(step_times > lease).mean() for lease in lease_seconds]
)
recovery_latency = lease_seconds + 2.0VisualizationOut [5]Expand

Idempotency keys: making retries safe
Idempotency concerns the intended effect of repeating an operation with the same semantics. Some APIs support a request key and replay a previous result. Check the provider's key scope, lifetime, and treatment of mismatched payloads before relying on that contract. HTTP idempotency does not imply that every log or internal side effect is identical. RFC 9110 §9.2.2
Reuse a stable operation key across attempts of the same logical step. This notebook derives it from the task identity, step, tool and sorted JSON input. A durable caller could also generate a key once and persist it before sending the request.
For the same operation and payload, reuse the same key. A fresh key per attempt can make a repeated request look like a separate operation to the upstream service.
An external operation must honor the key for external deduplication. A local cache can prevent calls after the local result has been recorded. It cannot establish the outcome of a call whose response did not arrive. Reconcile before automatically retrying an ambiguous operation without a suitable contract.
Retries and backoff
Classify failures before retrying. A temporary error can be retriable if the operation can safely be repeated and budget remains. Exponential delay plus random jitter spreads retries in time, and an attempt budget bounds repeated work. Google SRE, Addressing Cascading Failures
The cap applies to the nominal delay before jitter. With multiplicative jitter in the stated range, the maximum realized delay is one and a half times the nominal cap. A strict final cap would require a different formula or a final clamp.
A small simulation makes both effects visible: the cap flattens the curve, and jitter spreads the retry times that would otherwise land in lockstep.
PythonIn [6]Expand
import random
jitter_rng = random.Random(7)
attempts = np.arange(0, 9)
base, cap = 0.1, 5.0
deterministic_delay = np.minimum(cap, base * (2**attempts))
jittered_samples = np.array(
[delay * jitter_rng.uniform(0.5, 1.5) for delay in deterministic_delay]
)
lockstep_arrivals = np.full(60, deterministic_delay[-1])
jitter_arrivals = np.array(
[
jitter_rng.uniform(0.5, 1.5) * deterministic_delay[-1]
for _ in lockstep_arrivals
]
)VisualizationOut [7]Expand

A retry budget caps the total attempts per task (and ideally per operation) so a poison task cannot consume unbounded compute: the same reasoning as circuit breakers in general production systems (LLM Input Processing). A production policy can end attempts on a permanent error and record a terminal reason. The local runner propagates a stub exception to its caller. A permanent stub error here leaves a running task with its intent recorded and no completion.
Classify operation and response together. A timeout after possible execution leaves the outcome unknown. A backoff policy can respect a server retry hint when present, and it still needs a bound and a safe retry condition.
Deadlines and cancellation
A deadline is a time boundary used to decide whether further work should start. A separate cancellation or timeout protocol is needed to stop work that is already in progress.
- Absolute deadline: "complete by 14:00 UTC". Fixed point in time.
- Relative timeout: "at most 20 minutes from acceptance". Converted to an absolute deadline at intake.
A worker can compare the remaining time with a step budget before making the call. A percentile is an estimate rather than a guarantee. The toy checks only the task deadline at state-transition boundaries. It does not cancel an already executing stub or enforce an elapsed-time contract inside a remote service.
Converting a relative timeout to an absolute deadline at intake time, rather than carrying the relative form through the system, matters more than it looks. If each hop in a multi-hop pipeline resets a "20 minute" timeout, the total can grow without bound; pinning an absolute instant at submission makes the promise travel with the task and every hop measures against the same clock. This is why the runner's submit stores deadline as an epoch timestamp rather than a duration.
A budget is a generalization: cost budgets (dollars, tokens), step budgets (max ReAct iterations), and time budgets. Enforce them at step boundaries. This connects directly to the overthinking/step-efficiency discussion in Overthinking and Reasoning Efficiency: a task that's been going 40 minutes should probably be stopped whether or not it's "still making progress".
Idempotency at the side-effect boundary, and compensation
When the service offers no idempotency guarantee, plan for reconciliation and possible compensation.
- Order the work so non-idempotent steps happen last, after all reversible, retryable work has succeeded. Everything up to and including "prepare the email draft" is idempotent-by-construction; only "send email" is the final, singular effect.
- Compensate if it does go wrong. A compensating action reverses a side effect: refund a charge, send a correction, delete an uploaded file. Compensation is not a rollback (the effect already happened in the world); it's an explicit, logged corrective action. See the classic saga pattern for distributed transactions.
The notebook reports discrepancies between call intents, local result rows, and completion events. It leaves corrective action to an operator or a separate workflow. It does not execute any compensation.
Moving an irreversible operation late can shorten the time it is exposed to the worker’s failure. Earlier operations still need their own recovery rules. A crash during or immediately after the irreversible operation remains unresolved until the upstream outcome is established.
Worked example: a task that should be retried
Let's make a tiny task and walk it through a crash by hand. Our runner's model is:
Task = {
id, # stable identity
kind, # e.g. "draft_report"
input, # opaque
status, # pending | running | completed | failed
lease, # {worker, expiry} or null
attempts, # number of times started
deadline, # absolute time (epoch seconds) or null
events, # list of appended events
checkpoint, # materialized state snapshot at some offset (optional)
idempotency_log, # dict: key -> result for this task's side effects
}
Here's the crash sequence for a task that drafts a report by (a) searching the web, (b) summarizing, (c) emailing the summary.
| t | worker A does | durable store after write |
|---|---|---|
| 0 | claims task T, lease until 30 | status=running, lease=(A,30), attempts=1 |
| 1 | logs tool_called("search", …) | events=[…, tool_called] |
| 3 | search returns; logs tool_result | events=[…, tool_result] |
| 4 | logs model_response(step=1) (the summary plan) | events=[…, model_response] |
| 5 | crash | store has everything through step 4; T is running with a live-but-dead lease |
| 30 | lease expires | a scheduler notices T is running with lease.expiry <= now |
| 31 | worker B scans, sees T claimable, claims it, attempts=2, then replays the log: it recalls tool_result and the model response without re-calling either | status=running, lease=(B,61), attempts=2 |
| 32 | worker B logs tool_called("send_email", …), uses idempotency key T:2:send_email:sha(input), sends | events=[…, tool_called("send_email")] |
| 33 | logs tool_result("send_email", {"ok": true}) | events=[…, tool_result("send_email")] |
| 34 | logs task_completed, releases lease | status=completed |
Two things to notice. First, the search was executed once even though the agent ran on two workers: because the tool_result event was already in the log when B replayed. Second, the email went out once even though B's step-3 call was "new" to B, because the idempotency key is derived from the logical call, and the "send_email" step never happened on A (A crashed before reaching it). If B also crashed after sending but before logging the result, the key still protects us: the retry carries the same key, and the (hypothetical) email service deduplicates.
Notice, too, the deliberate gap between t=5 and t=30. For twenty-five seconds the task is in a state that looks stuck: status is running, but the worker is gone. Nobody is doing work, yet the system is not broken. This is the lease doing its job. It is a self-healing silence: the task is not lost, it is merely waiting for the lease to expire before a new worker may claim it. This is why choosing the lease duration is a tradeoff between recovery speed (short leases reclaim faster) and renewal traffic plus false-positive expiry (short leases also mistake slow workers for dead ones more often).
A lease can expire while the original worker is still executing. An incremented ownership generation lets the SQLite store reject writes from the old claim. That protection is local to the resource that checks the generation.
Each claim increments the stored generation for that task. When a worker with generation attempts a completion after another claim advanced the generation to , the transaction checks the mismatch and rejects the write. The ownership generation is distinct from the sequence number that orders events.
Building a durable task runner
The notebook keeps one open in-memory SQLite connection and simulates worker crashes and lease expiry as serial turns. This exercises transactions and stale-generation rejection with the database still running. Exiting the notebook discards the database; production restart recovery needs a persistent store independent of the worker process.
SQLite supplies real transactions, an ordered event log, and keyed lookup without a local file. A production store would need equivalent atomic ownership and transition checks under its own concurrency model.
The setup cell uses only Python standard-library modules.
PythonIn [8]Expand
import hashlib
import json
import os
import random
import sqlite3
import threading
import time
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable
DEMO_DB_URI = ":memory:"The schema
We need four things: tasks, events, leases (folded into tasks here for brevity), and an idempotency table. We'll keep everything in one open SQLite connection and use text JSON for events to keep the code legible.
PythonIn [9]Expand
SCHEMA = """
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
kind TEXT NOT NULL,
input TEXT NOT NULL,
status TEXT NOT NULL, -- pending | running | completed | failed
lease_worker TEXT,
lease_until REAL,
lease_epoch INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
deadline REAL,
created_at REAL NOT NULL
);
CREATE TABLE events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id TEXT NOT NULL,
seq INTEGER NOT NULL, -- per-task monotonic sequence
kind TEXT NOT NULL,
payload TEXT NOT NULL,
UNIQUE(task_id, seq)
);
CREATE TABLE idem (
key TEXT PRIMARY KEY,
result TEXT NOT NULL,
created_at REAL NOT NULL
);
"""
def init_db(location=DEMO_DB_URI):
connection = sqlite3.connect(location, isolation_level=None)
connection.executescript(SCHEMA)
return connection
DB = init_db()The event sequence constraint guards duplicate positions. Worker ownership is a separate rule. The worker checks identity, generation, deadline and live lease inside the transaction that writes events or a terminal state.
The tasks table stores current state, lease holder, generation, expiry, and the attempt count. Events are inserted at a task-local sequence position. The result cache maps an effect key to its recorded result. Its presence is evidence of a local record; the upstream service controls the actual effect.
The event log helpers
We write a small set of helpers: append an event, read events since a given sequence, and fold the log into state. Folding is the "replay" that reconstructs what the agent believed at any point.
PythonIn [10]Expand
@contextmanager
def tx():
DB.execute("BEGIN IMMEDIATE")
try:
yield DB
DB.execute("COMMIT")
except BaseException:
DB.execute("ROLLBACK")
raise
def append_in_transaction(con, task_id, kind, payload):
(seq,) = con.execute(
"SELECT COALESCE(MAX(seq), 0) + 1 FROM events WHERE task_id = ?",
(task_id,),
).fetchone()
con.execute(
"INSERT INTO events (task_id, seq, kind, payload) VALUES (?, ?, ?, ?)",
(task_id, seq, kind, json.dumps(payload)),
)
def apply_terminal(con, task_id, status, reason=None):
payload = {"reason": reason} if reason is not None else {}
append_in_transaction(con, task_id, f"task_{status}", payload)
con.execute(
"""UPDATE tasks SET status=?, lease_worker=NULL, lease_until=NULL WHERE id=?""",
(status, task_id),
)
def worker_commit(worker_id, task, entries, *, terminal=None):
task_id = task["id"]
with tx() as con:
now = time.time()
owned = con.execute(
"""SELECT deadline FROM tasks
WHERE id=? AND status='running' AND lease_worker=?
AND lease_epoch=? AND lease_until>?""",
(task_id, worker_id, task["lease_epoch"], now),
).fetchone()
if owned is None:
return "lost_lease"
(deadline,) = owned
if deadline is not None and deadline <= now:
apply_terminal(con, task_id, "failed", "deadline_exceeded")
return "failed:deadline"
for kind, payload in entries:
append_in_transaction(con, task_id, kind, payload)
if terminal is not None:
apply_terminal(con, task_id, terminal)
return "ok"
def read_events(task_id: str, after_seq: int = 0):
with DB as con:
rows = con.execute(
"SELECT seq, kind, payload FROM events WHERE task_id = ? AND seq > ? ORDER BY seq",
(task_id, after_seq),
).fetchall()
return [{"seq": s, "kind": k, "payload": json.loads(p)} for s, k, p in rows]BEGIN IMMEDIATE acquires the write lock at transaction start rather than deferring it, so the MAX(seq)+1 read and the INSERT are atomic: no two workers can pick the same seq.
BEGIN IMMEDIATE serializes writers before they perform the sequence read and insertion. The same write transaction validates the current task generation and lease before an event append. Sequence uniqueness detects collisions but does not authenticate the worker.
The fold: reconstructing agent state
The fold is one function per log kind. The reconstructed state is the minimum the agent needs to continue: the message list from prior tool calls, plus the number of the last completed step. If a model_response event is present for step i, we don't re-ask the model.
PythonIn [11]Expand
def fold_events(events):
state = {"messages": [], "completed_step": 0, "last_call": {}}
for e in events:
kind, p = e["kind"], e["payload"]
if kind == "tool_called":
state["last_call"][p["call_id"]] = {
"tool": p["tool"],
"input": p["input"],
}
elif kind == "tool_result":
cid = p["call_id"]
call = state["last_call"].pop(cid, None)
state["messages"].append(
{
"role": "tool",
"name": call["tool"] if call else p.get("tool"),
"content": p["output"],
}
)
elif kind == "model_response":
state["messages"].append(
{"role": "assistant", "content": p["text"]}
)
state["completed_step"] = max(state["completed_step"], p["step"])
elif kind == "task_completed":
state["status"] = "completed"
return stateThe fold marks the task as completed when it sees task_completed. The runner reads failure status from the tasks table rather than folding task_failed into state. At replay, the last model_response marker tells it which completed steps to skip.
The fold rebuilds its task state from the same ordered events without a clock or external calls. It reconstructs recorded progress; an unrecorded outcome remains unknown.
Idempotent side effects
The result cache illustrates a logical effect key. The toy stubs run outside the local transaction, so there is a gap between the effect and the cached result. A cache hit avoids another stub invocation. The cache is not a remote idempotency guarantee.
PythonIn [12]Expand
def logical_key(task_id, step, tool, tool_input):
description = {"t": task_id, "s": step, "tool": tool, "i": tool_input}
return hashlib.sha256(
json.dumps(description, sort_keys=True).encode()
).hexdigest()
def call_with_idempotency(
task_id: str,
step: int,
tool: str,
tool_input: dict,
fn: Callable[[dict], Any],
) -> Any:
key = logical_key(task_id, step, tool, tool_input)
with DB as con:
row = con.execute(
"SELECT result FROM idem WHERE key = ?", (key,)
).fetchone()
if row is not None:
return {"key": key, "cached": True, "result": json.loads(row[0])}
# The stub effect happens outside the SQLite transaction. On a crash or a
# duplicate cache miss the effect can happen again. A real upstream key
# contract, when available, belongs inside this fn boundary.
result = fn(tool_input)
with tx() as con:
con.execute(
"INSERT OR IGNORE INTO idem (key, result, created_at) VALUES (?, ?, ?)",
(key, json.dumps(result), time.time()),
)
(canonical,) = con.execute(
"SELECT result FROM idem WHERE key = ?", (key,)
).fetchone()
return {"key": key, "cached": False, "result": json.loads(canonical)}A restart before the cache insert can repeat an operation, as can two concurrent cache misses. A winning result row is returned to every caller that reaches the post-call transaction, but it cannot undo another execution. The toy retains this gap to show why an upstream key contract matters.
With the same serialization options, sort_keys=True removes differences in dictionary key order. It does not make different numeric representations or serializers yield identical bytes. Specify how callers encode the fields when they must compute the same logical key.
Now let's wire those together. The folding at the end gives us a reconstructed state and the last completed step. When the worker loop below runs a step, it appends a tool_called event, calls the tool via call_with_idempotency, then appends tool_result and model_response events. For the demo, the tool is a stub that records each real execution in the EXECUTED list so we can watch it run, and that list is printed by the output-only demo blocks rather than from inside the tool.
The worker loop
With a new lease, a later worker can continue using the recorded step markers when the current turn ends without a terminal state. The worker checks and renews its assignment before executing a step. Intent and completion transitions also recheck the same ownership generation atomically. Completion writes group the tool result with the step marker.
PythonIn [13]Expand
LEASE_SECONDS = 5.0
MAX_TASK_ATTEMPTS = 3
def claim_task(worker_id: str, *, max_attempts: int = MAX_TASK_ATTEMPTS):
with tx() as con:
now = time.time()
available = con.execute(
"""SELECT id, kind, input, attempts, deadline, lease_epoch FROM tasks
WHERE status IN ('pending', 'running')
AND (lease_until IS NULL OR lease_until <= ?)
ORDER BY created_at, id""",
(now,),
).fetchall()
for task_id, kind, raw_input, attempts, deadline, epoch in available:
if deadline is not None and deadline <= now:
apply_terminal(con, task_id, "failed", "deadline_exceeded")
continue
if attempts >= max_attempts:
apply_terminal(con, task_id, "failed", "attempt_budget")
continue
con.execute(
"""UPDATE tasks SET status='running', lease_worker=?, lease_until=?,
lease_epoch=?, attempts=attempts+1 WHERE id=?""",
(worker_id, now + LEASE_SECONDS, epoch + 1, task_id),
)
return {
"id": task_id,
"kind": kind,
"input": json.loads(raw_input),
"attempts": attempts + 1,
"deadline": deadline,
"lease_epoch": epoch + 1,
}
return None
def renew_lease(worker_id: str, task: dict) -> bool:
with tx() as con:
now = time.time()
cur = con.execute(
"""UPDATE tasks SET lease_until=?
WHERE id=? AND status='running' AND lease_worker=?
AND lease_epoch=? AND lease_until>?""",
(
now + LEASE_SECONDS,
task["id"],
worker_id,
task["lease_epoch"],
now,
),
)
return cur.rowcount == 1renew_lease returns False if our lease has expired: another worker may have claimed the task, and we should stop writing. That's the fencing check applied at renewal. Combined with renew_lease, a well-behaved worker will exit early when fenced, minimizing wasted work.
The claim loop scans pending tasks and running tasks without a live lease. It marks expired or exhausted tasks failed and can select a remaining claimable task. In the SQLite fixture these steps share a write transaction.
Each loop turn renews the lease, folds the recorded trace, records intent, then runs one stub operation and attempts a fenced completion transaction. If the lease expires while the stub runs, that worker cannot commit the result to the task event log.
PythonIn [14]Expand
def plan_for(kind: str) -> list[dict]:
if kind == "draft_report":
return [
{
"tool": "search",
"input": {"q": "durable agent work"},
"cost": 0.01,
},
{"tool": "summarize", "input": {"style": "brief"}, "cost": 0.02},
{
"tool": "send_email",
"input": {"to": "user@example.com"},
"cost": 0.00,
},
]
if kind == "charge_customer":
return [
{
"tool": "validate_order",
"input": {"order": "ord_42"},
"cost": 0.01,
},
{
"tool": "charge_card",
"input": {"order": "ord_42", "amount": 1900},
"cost": 0.00,
},
{
"tool": "send_receipt",
"input": {"to": "user@example.com"},
"cost": 0.00,
},
]
raise ValueError(f"unknown kind {kind}")Each step has a tool name, parsed input (analogous to the JSON the model would produce in Function Calling), and a nominal cost. The runner doesn't care what the tool means; it only cares that the tool call is at the idempotent boundary.
The two plans are chosen to contrast the good case with the dangerous one. In draft_report, the only non-idempotent effect is the final send_email, so ordering is naturally safe: a crash at any earlier step can be retried freely. In charge_customer, the money-moving step charge_card is in the middle, with send_receipt after it. If the process crashes after the charge but before the receipt, a naive retry would charge the card twice. This is exactly the workflow that must lean on idempotency keys and compensation, and it is why we include it alongside the apparently-simpler report task.
The actual tool implementations are stubs. To make the demo's crashes visible, we let the caller inject a "crash after this step" instruction.
PythonIn [15]Expand
EXECUTED = [] # records every real (non-cached) tool execution; results are printed by output-only blocks
def execute_tool(tool: str, tool_input: dict) -> Any:
EXECUTED.append({"tool": tool, "input": tool_input, "t": time.time()})
if tool == "search":
return {"hits": ["a", "b", "c"]}
if tool == "summarize":
return {"summary": "durability matters"}
if tool == "send_email":
return {"ok": True, "message_id": f"msg_{uuid.uuid4().hex[:8]}"}
if tool == "validate_order":
return {"ok": True}
if tool == "charge_card":
return {"ok": True, "charge_id": f"ch_{uuid.uuid4().hex[:8]}"}
if tool == "send_receipt":
return {"ok": True}
raise ValueError(tool)Each entry in the in-memory call list records one stub invocation. A cache hit does not append to it. We count calls in the fixed crash-after-first-result example, and we inspect the log separately to identify steps available on recovery.
The crash injection raises after a selected completion is committed. In the duplicate-delivery example, the first claim expires before a second worker claims the task, and the first worker’s subsequent turn is rejected.
PythonIn [16]Expand
def run_task(
worker_id: str,
task: dict,
crash_after_step: int | None = None,
max_steps: int = 20,
) -> str:
task_id = task["id"]
plan = plan_for(task["kind"])
for _ in range(max_steps + 1):
if not renew_lease(worker_id, task):
return "lost_lease"
state = fold_events(read_events(task_id))
next_step = state["completed_step"]
if next_step >= len(plan):
transition = worker_commit(
worker_id, task, [], terminal="completed"
)
return "completed" if transition == "ok" else transition
if _ == max_steps:
break
step = plan[next_step]
call_id = f"s{next_step}"
transition = worker_commit(
worker_id,
task,
[
(
"tool_called",
{
"call_id": call_id,
"tool": step["tool"],
"input": step["input"],
"step": next_step,
},
)
],
)
if transition != "ok":
return transition
result = call_with_idempotency(
task_id,
next_step,
step["tool"],
step["input"],
lambda data: execute_tool(step["tool"], data),
)
transition = worker_commit(
worker_id,
task,
[
(
"tool_result",
{
"call_id": call_id,
"tool": step["tool"],
"key": result["key"],
"output": result["result"],
"cached": result["cached"],
},
),
(
"model_response",
{"step": next_step + 1, "text": f"did {step['tool']}"},
),
],
)
if transition != "ok":
return transition
if next_step == crash_after_step:
raise RuntimeError(f"simulated crash after step {crash_after_step}")
return "yield:max_steps"A few observations on the loop:
- The replay at the top of every iteration is what makes crash recovery automatic: after a crash, the next worker's first loop turn rebuilds
statefrom the log before doing anything else. We never have to reconstruct state manually. call_idis deterministic fromnext_step, so the fold can pair atool_calledwith itstool_resultunambiguously.- The idempotency key includes
next_step, so the same step and input yield the same key after restart. If the effect ran and theidemrow committed before the crash, the next attempt reads the recorded result. A crash after the effect and before the cache insert can leave onlytool_calledin the event log, so the next attempt can run the stub again. The reconciliation example below illustrates this gap. - The
crash_after_stepinjection raises after completion events are committed. The separate crash-window fixture below exercises the earlier interruption after the stub ran and before its result was recorded.
On a restart, the worker reconstructs completed steps from durable events. Its next transition also depends on the current lease generation, task deadline, and result cache. The ownership checks coordinate workers that can otherwise replay the same log independently.
We also need a small scheduler that can submit tasks, run one worker turn, and report state. Let's write that, then run a happy path.
PythonIn [17]Expand
def submit(
kind: str, input_dict: dict, deadline_seconds: float | None = 60.0
) -> str:
task_id = f"task_{uuid.uuid4().hex[:8]}"
now = time.time()
with tx() as con:
con.execute(
"""INSERT INTO tasks (id, kind, input, status, attempts, deadline, created_at)
VALUES (?, ?, ?, 'pending', 0, ?, ?)""",
(
task_id,
kind,
json.dumps(input_dict),
now + deadline_seconds
if deadline_seconds is not None
else None,
now,
),
)
return task_id
def status_of(task_id: str) -> dict:
con = DB
con.row_factory = sqlite3.Row
row = con.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone()
return dict(row) if row else {}Submission persists an intent and returns its ID. Completion still requires worker capacity and a usable deadline. A subsequent scheduler sweep can fail an expired unclaimed task without starting a tool.
Writing the accepted request before acknowledging it means a process restart need not lose the record. The fixture keeps its database open while it simulates the next worker reading an earlier worker’s committed state. It does not demonstrate recovery after loss of that database or process.
Worked example: crash and recovery
Let's prove the model. We submit a draft_report and run it with a simulated crash after step 0. We expect: step 0 (search) runs for real; step 1 (summarize) never runs on worker A; and when worker B claims the task, it reuses the recorded search result without re-invoking the tool.
PythonIn [18]Expand
EXECUTED.clear()
tid = submit("draft_report", {"topic": "durable agents"})
# Worker A: run, then crash after step 0
task_a = claim_task("A")
try:
run_task("A", task_a, crash_after_step=0)
except RuntimeError as e:
crash_message = str(e)ConsoleOut [19]Expand
worker A crashed: simulated crash after step 0 status after crash: running | lease worker: A
The store now has status=running, lease_worker=A, and the events list ends with tool_result(s0) + model_response(step=1). Worker A's lease is still live (we haven't waited), so no other worker can claim it yet. We need to wait for the lease to expire before B can take over. In practice you shorten the lease in tests, or trust that expirations happen quickly.
PythonIn [20]Expand
# Fast-forward: expire the lease manually to simulate waiting past LEASE_SECONDS
with tx() as con:
con.execute(
"UPDATE tasks SET lease_until = ? WHERE id = ?", (time.time() - 1, tid)
)
executed_before = len(EXECUTED)
task_b = claim_task("B")
result = run_task("B", task_b)
executed_after = len(EXECUTED)ConsoleOut [21]Expand
worker B result: completed tools executed on A: 1 tools executed on B (additional): 2 total real tool calls: 3 final status: completed
The output confirms that only three real tool calls occurred across two workers: search executed once on worker A, and summarize and send_email executed on worker B. That bounded rework is the property we want.
In this fixture, worker B finds the committed search result and skips that step. The other two stubs run on B. A crash before recording the result is covered separately below.
We can plot the accounting directly from the executed list and the recovered log, so "bounded rework" becomes a count instead of a claim.
PythonIn [22]Expand
executed_tools = [e["tool"] for e in EXECUTED]
plan_tools = [s["tool"] for s in plan_for("draft_report")]
recovered_tools = [e["tool"] for e in EXECUTED[:executed_before]]
real_executions = {tool: executed_tools.count(tool) for tool in plan_tools}VisualizationOut [23]Expand

Let's also confirm the event log tells the story.
PythonIn [24]Expand
logged_events = read_events(tid)ConsoleOut [25]Expand
1 tool_called {"call_id": "s0", "tool": "search", "input": {"q": "durable agent work"}, "step"
2 tool_result {"call_id": "s0", "tool": "search", "key": "e47f65649c9ca2b164ebc79ee7728b0b4ec7
3 model_response {"step": 1, "text": "did search"}
4 tool_called {"call_id": "s1", "tool": "summarize", "input": {"style": "brief"}, "step": 1}
5 tool_result {"call_id": "s1", "tool": "summarize", "key": "0ed53daecf4f881d1850091eef018387d
6 model_response {"step": 2, "text": "did summarize"}
7 tool_called {"call_id": "s2", "tool": "send_email", "input": {"to": "user@example.com"}, "st
8 tool_result {"call_id": "s2", "tool": "send_email", "key": "60e52a8a39da5dfdc55f2caf88f01c75
9 model_response {"step": 3, "text": "did send_email"}
10 task_completed {}The completed trace has ten events: an intent, result, and model-response marker for each of the three steps, followed by task_completed. B skips the first step because its completed-step marker exists. A cache hit follows a different path through the executor.
Duplicate delivery and fencing
Worker A stalls past its lease. Worker B acquires a new generation. In this fixture A fails its renewal before it can invoke a new step. The state store also checks ownership at commit, since renewal alone cannot protect against an old worker that remains active.
PythonIn [26]Expand
EXECUTED.clear()
tid2 = submit("draft_report", {"topic": "split brain"})
t1 = claim_task("A")
t2 = None
# Simulate: A holds the lease, but stalls so long that B can claim.
time.sleep(LEASE_SECONDS + 0.5)
# B claims because A's lease has expired
t2 = claim_task("B")
# Now both A and B "run". A is stale: its renew_lease will fail.
a_result = run_task("A", t1)
b_result = run_task("B", t2)ConsoleOut [27]Expand
A: lost_lease B: completed real tool calls: 3 ['search', 'summarize', 'send_email']
Worker A stops when it tries to renew the old claim. Worker B can complete under the newer generation. Rejecting a stale write does not prevent an earlier external operation from taking effect.
The generation check rejects a stale writer even if the worker had earlier passed renewal. The sequence constraint protects event ordering. An external effect requires its own protection at the downstream service.
The local cache can admit a duplicate when both callers miss before either records a result, or when a crash interrupts the operation after an effect but before insertion. A remote service that enforces the logical key can narrow this window under its own contract.
Retries, backoff, and retry budgets
The worker loop does not call this retry helper. The standalone helper retries only exceptions explicitly included in its retriable tuple, which defaults to TransientError.
- Retry a transient failure only when it is safe to repeat the operation. A permanent failure ends the attempt. If the effect’s outcome is unknown, first reconcile it or use the receiver’s valid idempotency contract.
- Cap the nominal exponential delay before multiplying it by jitter.
- Bound both the number of attempts and overall waiting time in the service policy.
The budget ensures a task whose tool keeps returning 503 doesn't consume unbounded compute. The same reasoning underlies circuit breakers in serving (LLM Inference Serving). Here's a tiny policy object.
PythonIn [28]Expand
retry_rng = random.Random(11)
def backoff(n: int, base: float = 0.1, cap: float = 5.0) -> float:
return min(cap, base * (2**n)) * retry_rng.uniform(0.5, 1.5)
class TransientError(Exception):
pass
def with_retries(
fn, max_attempts: int = 3, retriable=(TransientError,), *, sleep=time.sleep
):
if max_attempts < 1:
raise ValueError("max_attempts must be positive")
for attempt in range(max_attempts):
try:
return fn()
except retriable:
if attempt + 1 == max_attempts:
raise
sleep(backoff(attempt))The helper counts calls including the first. The separate durable budget counts claim attempts. Claiming checks the persisted number while holding the database write transaction and fails an exhausted task without giving it another lease.
PythonIn [29]Expand
tid3 = submit("draft_report", {"topic": "budget demo"})
with tx() as con:
con.execute(
"UPDATE tasks SET attempts = ? WHERE id=?", (MAX_TASK_ATTEMPTS, tid3)
)
claimed = claim_task("A")
budget_events = read_events(tid3)
assert claimed is None
assert status_of(tid3)["attempts"] == MAX_TASK_ATTEMPTS
assert budget_events[-1]["payload"]["reason"] == "attempt_budget"ConsoleOut [30]Expand
claimed or skipped: None status: failed
The demo injects a task whose prior attempt count is already at the limit. It remains at that count, logs the reason, and never reaches a worker.
The reason code identifies the rejected task for inspection.
There is a subtlety in where the budget is enforced that is easy to miss. If the budget were checked inside run_task, a poison task would still be claimed, still have its lease written, still renew once, before the check fired, and in some designs still execute one more failing step. By checking at claim time and immediately transitioning to failed, we spend essentially nothing on a task we've already decided to abandon. We also leave a clean task_failed event explaining why, which is what an on-call engineer needs to triage. A retry budget is only useful if exhausting it produces a diagnosable outcome, not a silent black hole.
Deadlines
A claim can expire after admission. The worker tests the deadline in the same transaction as each state transition. The demo sets the persisted deadline to the past after claiming the task, then checks that no tool executes.
The SQLite runner only checks whether the persisted deadline has elapsed. It does not forecast a step’s duration or pass a timeout to the stub. The separate cost illustration asks whether a proposed step would fit in a hypothetical remaining budget. A production executor needs its own timeout or cancellation contract for work that has already started.
PythonIn [31]Expand
EXECUTED.clear()
tid4 = submit("draft_report", {"topic": "deadline"}, deadline_seconds=60)
task4 = claim_task("D")
# Inject deadline expiry after admission without waiting for the wall clock.
expired_at = time.time() - 1
with tx() as con:
con.execute(
"UPDATE tasks SET deadline = ? WHERE id = ?", (expired_at, tid4)
)
task4["deadline"] = expired_at
deadline_exceeded = time.time() > task4["deadline"]
res = run_task("D", task4)ConsoleOut [32]Expand
deadline already exceeded: True result: failed:deadline tools executed: [] final status: failed
The result reports a deadline failure and the stub call list stays empty. If the deadline instead passes during a stub, its cache row can already exist when the guarded completion rejects the result event. Later reconciliation can then see a cached but unrecorded call. This demo does not cancel work that had already started.
This separate example schedules hypothetical steps using their known toy costs. The 20-second budget and step costs 1, 8, 9, and 6 seconds leave 20, 19, 11, and 2 seconds before the respective steps. Only the first three fit.
PythonIn [33]Expand
budget_seconds = 20.0
step_costs = np.array([1.0, 8.0, 9.0, 6.0])
cumulative_cost = np.cumsum(step_costs)
remaining_before = budget_seconds - np.concatenate(
([0.0], cumulative_cost[:-1])
)
would_fit = remaining_before >= step_costsVisualizationOut [34]Expand

The hard deadline blocks further guarded transitions and causes the runner to record failure when a valid owner next reaches a deadline check. A soft deadline can leave time to return partial work. The service executing a call needs its own timeout or cancellation to bound work already underway.
Reconciliation and compensation
There's a residual failure mode that no in-process protocol fixes: the process crashed after the side effect happened, but before the idem row was written (the at-least-once gap). For a payment API that honors idempotency keys upstream, you solve it by passing the key to the API, and a subsequent read of "did charge ch_… for order ord_42 exist?" tells you the truth. For an email server without such a feature, the honest tools are:
- Reconciliation compares external state with the local log. If the outcome is unknown, check the upstream operation using its identifier. Retry only when the upstream contract or verified state permits it.
- Compensation records a separate corrective operation when a prior effect cannot simply be undone. Give the correction its own authorization and audit record.
The reconciler checks whether a local result event and a cache entry exist and whether the result event carries the expected key. It does not compare the stored output values, and it cannot verify the upstream effect. Reconcile the actual external state before resolving a missing receipt.
PythonIn [35]Expand
def reconcile(task_id: str):
events = read_events(task_id)
calls = {
e["payload"]["call_id"]: e["payload"]
for e in events
if e["kind"] == "tool_called"
}
results = {
e["payload"]["call_id"]: e["payload"]
for e in events
if e["kind"] == "tool_result"
}
issues = []
with DB as con:
for call_id, call in calls.items():
key = logical_key(
task_id, call["step"], call["tool"], call["input"]
)
cached = (
con.execute("SELECT 1 FROM idem WHERE key=?", (key,)).fetchone()
is not None
)
result = results.get(call_id)
if result is None or result["key"] != key or not cached:
issues.append(
{
"call_id": call_id,
"cached": cached,
"recorded": result is not None,
}
)
return {"task_id": task_id, "issues": issues, "checked": len(calls)}ConsoleOut [36]Expand
incomplete local trace: [{'call_id': 's0', 'cached': False, 'recorded': False}]
recovered report trace: []The first trace has a call with neither a cached result nor a recorded completion. The recovered report has all three results. Inspecting the local trace identifies the unresolved call. An external query is still needed to determine what happened outside the worker.
Reconciliation reports which recorded intent still lacks an outcome. Use that identifier to ask the upstream system before deciding whether a retry or corrective operation is appropriate.
Limitations and impact
A local SQLite transaction can keep a task event and its status consistent. It cannot commit with an independent service in this fixture. The external operation can still be attempted again and its outcome can remain unknown after a crash.
A request can succeed and lose its acknowledgement. A local log cannot disambiguate that outcome by itself. Repeat the logical key only if the service actually deduplicates it, or query the outcome using an identifier and handle remaining uncertainty explicitly.
The tasks table holds queue and lease state. The events table records progress and the result cache records previously returned stub outcomes. A production checkpoint would add a durable state snapshot and an offset, while this notebook folds the full log.
After a worker disappears, a later worker can claim the task if the assignment expires and the task is still eligible. It can continue from committed progress if the store is available and the recorded state is valid. This runner reconstructs progress from the event log. A production runner can start from a checkpoint that records a consistent state and replay offset, then read subsequent events.
The third trap is unbounded retries and stale workers. Without fencing, a slow worker can keep writing after its lease expired, and without a retry budget a poison task can run forever. Combined, these produce the classic failure mode where "the task keeps failing but it also keeps making external effects": the worst of both. The defenses (fencing tokens, per-task attempt counters, transient-vs-permanent error classification) are simple, but they must be present; none of them is provided for free by the LLM call stack. You get them by building the runner around the model, not by pointing the model at a queue and hoping.
A timeout can hide a completed effect. Bound retry cost with an attempt budget, and use the upstream operation’s own outcome and idempotency semantics to decide whether to repeat it.
The fixture writes an intent and two completion events per successful step, and can also renew leases. Measure write load alongside execution cost. A different store needs equivalent atomic ownership and transition checks.
The same separation between state, execution, and authority matters when several agents or a human participate. See Long-Horizon Agents and Interoperability.
Key Parameters
The key implementation parameters for this durable task runner are:
- LEASE_SECONDS: How long a worker holds a lease before it expires and other workers may reclaim the task. Shorter leases recover faster from crashes but increase renewal traffic.
- MAX_TASK_ATTEMPTS: The maximum number of task claims, including the first. The next scan of an eligible task with an exhausted budget records failure without granting another lease.
- backoff base and cap: The base delay doubles per retry until it reaches the cap. The function applies the jitter multiplier afterward, so the returned delay can exceed the cap.
- deadline_seconds: A supplied relative timeout becomes an absolute deadline at submission. The worker checks expiry before starting another step and before recording its result.
crash_after_stepinjects a crash after committed completion. Separate fixtures manually expire a lease and interrupt execution before writing a result.
Summary
Long-horizon agent work is not "the same as short work but slower". Once the task outlives the process, you need explicit durability primitives, and the right mental model is an event log plus a queue plus an external-effect boundary.
- Event log, written before the side effect (write-ahead log discipline), so a crash leaves a record that a retry can consult.
- A checkpoint can store state with a consistent replay offset so recovery can read just the remaining events. This fixture replays the full log.
- Leases with a TTL let a dead worker's task be reclaimed without manual intervention. Claims are compare-and-swap transactions (
BEGIN IMMEDIATE, conditionalUPDATE,SET NX PX) so two workers can't both "win". - Fencing. Check the live lease and ownership generation inside the transaction that writes each batch of events or changes task status.
- Idempotency keys, deterministic from
(task_id, step, tool, input), turn unsafe retries into safe ones when the external service cooperates. For services that don't, order the work so non-idempotent effects are last, and plan for reconciliation and compensation. - The task budget limits claim attempts. The standalone retry helper limits calls and spaces transient retries with jitter. A permanent stub error propagates out of this runner and leaves the task running.
- An elapsed task deadline prevents the next step from starting. Bounding an in-flight operation requires a separate timeout or cancellation mechanism.
The local worker can recover committed progress only while its store remains available. Leases and fencing protect local writes, bounded retries control repeated attempts, and upstream receipts help resolve outcomes that the local log cannot establish.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about durable and asynchronous agent work.
Durable and Asynchronous Agent Work
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!