Durable and Asynchronous Agent Work › Core concepts

Michael BrenndoerferDecember 1, 202610 min read
Language AI HandbookAll chapters
Part 49 of 67Long-Horizon Agents and Interoperability
Chapter 376Durable and Asynchronous Agent Work › Core concepts
Reading section 3 of 15 · Core concepts · 10 minSection 3 of 15 · 10 min

Section 3 of 15 · 10 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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_started
  • tool_called(tool="search", input=..., call_id="c1")
  • tool_result(call_id="c1", output=...)
  • model_response(step=3, text=...)
  • task_completed
  • task_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]
CollapseExpand
# 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]
CollapseExpand
Timeline with four crash markers and a labeled hatched interval from invocation to result commit.
Four positions in one step. The labeled interval from tool invocation until result commit can leave an external effect unresolved.

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:

lease(T)=⟨W,tacquired,texpiry⟩,texpiry=tacquired+Δlease\text{lease}(T) = \langle W, t_{\text{acquired}}, t_{\text{expiry}} \rangle, \quad t_{\text{expiry}} = t_{\text{acquired}} + \Delta_{\text{lease}}

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]
CollapseExpand
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.0
VisualizationOut [5]
CollapseExpand
Separate panels show decreasing live-step expiry percentage and increasing modeled crash recovery delay as the lease duration increases.
The left panel estimates lease expiry during a live step under the sampled step times. The right models recovery after a crash immediately after claim, including two seconds of fixed dispatch delay.

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

execute(k,f)={stored[k]if k∈storedf()otherwise, storing result under k\text{execute}(k, f) = \begin{cases} \text{stored}[k] & \text{if } k \in \text{stored} \\ f() & \text{otherwise, storing result under } k \end{cases}

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.

Idempotency keys only help if the callee honors them

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

delayn=min⁡(cap, base⋅2n)⋅U(0.5,1.5)\text{delay}_n = \min(\text{cap},\ \text{base} \cdot 2^{n}) \cdot U(0.5, 1.5)

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]
CollapseExpand
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]
CollapseExpand
Backoff curve with cap plus a histogram of jittered retry arrivals.
Exponential backoff with a cap, and how jitter de-synchronizes retry arrivals. Without jitter all workers retry at the same instant; with jitter arrivals spread across the window.

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.

  1. 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.
  2. 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.

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!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy