Durable Agents Need a Run Log, Not a Very Long Promise Chain
Long-running agents should survive worker crashes and human pauses without starting over. This design stores step state, checkpoints, idempotency keys, and resumable events so execution can move between workers safely.
On this page
An agent that works for twenty minutes should not lose twenty minutes of work because one Node.js process restarted.
That sounds obvious, but many early agent implementations are effectively one long in-memory function:
const plan = await model.plan(input);const docs = await search(plan.query);const result = await tool(plan.tool);const answer = await model.respond(result);As long as everything completes in one request, the design is fine.
Then the workflow grows. It waits for a human approval. A provider rate-limits a step for five minutes. A worker is redeployed. The process crashes after a side effect. The user comes back tomorrow and expects the job to continue.
At that point, “agent state” cannot mean whatever happens to be in memory inside the current worker.
I prefer to model long-running agent execution as a durable workflow with an append-only run log and explicit checkpoints. A worker can disappear. The run remains.
The example here is a GitHub maintenance agent that analyzes a repository, creates a patch, runs tests, pauses for approval, and then opens a pull request.
Give the run an identity before doing work
The first durable record is created before the first model call.
type RunStatus = | "queued" | "running" | "waiting-for-approval" | "completed" | "failed" | "cancelled";type AgentRun = { id: string; tenantId: string; userId: string; workflow: string; workflowVersion: number; status: RunStatus; currentStep: string; createdAt: string; updatedAt: string;};I also persist the version of the workflow definition. If code changes while a run is paused, I do not want it silently resuming under completely different step semantics.
For simple systems, a version number and backward-compatible state migrations are enough. More sophisticated workflow engines solve this problem differently, but the principle remains: durable state needs a contract across deployments.
Store events separately from the current snapshot
The run row tells me where the workflow is now. An event log tells me how it got there.
type RunEvent = { id: string; runId: string; sequence: number; type: | "step-started" | "step-completed" | "tool-called" | "tool-completed" | "approval-requested" | "approval-received" | "checkpoint" | "run-failed"; payload: unknown; createdAt: string;};A PostgreSQL table can enforce event ordering per run:
CREATE TABLE agent_run_events ( run_id UUID NOT NULL, sequence BIGINT NOT NULL, event_type TEXT NOT NULL, payload JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (run_id, sequence));I do not need event sourcing for every application feature. For long agent runs, however, an event trail is valuable because debugging often means reconstructing what happened across several processes and external calls.
Checkpoint state that is expensive to recreate
A checkpoint is a compact state object the next worker can resume from.
type RepositoryCheckpoint = { repositoryId: string; baseCommit: string; branchName?: string; task: string; relevantFiles: string[]; patchArtifactId?: string; testRunArtifactId?: string; approvalId?: string; nextStep: "analyze" | "edit" | "test" | "approval" | "open-pr";};Large logs or file snapshots should normally live in artifact storage, not inside the checkpoint JSON. The checkpoint stores stable handles and the resource versions needed to verify freshness later.
That keeps database rows manageable and makes artifact retention an explicit part of workflow retention.
Advance step and checkpoint atomically
A common crash window looks like this:
- worker writes checkpoint B;
- worker crashes before updating
current_step; - another worker loads checkpoint B but thinks the run is still at step A.
Use a transaction for local durable state.
async function commitCheckpoint(input: { runId: string; expectedStep: string; nextStep: string; checkpoint: RepositoryCheckpoint;}): Promise<void> { await db.transaction(async (tx) => { const run = await tx.runs.lock(input.runId); if (run.currentStep !== input.expectedStep) { throw new Error("Run step changed concurrently"); } await tx.checkpoints.insert({ runId: input.runId, step: input.nextStep, state: input.checkpoint, }); await tx.events.append(input.runId, "checkpoint", input.checkpoint); await tx.runs.update(input.runId, { currentStep: input.nextStep, updatedAt: new Date().toISOString(), }); });}The expected-step check acts like optimistic concurrency. It prevents two workers from independently advancing the same run after a duplicate queue delivery.
A worker needs a lease, not ownership forever
Queues can redeliver messages. Workers can stall. I do not want one database boolean called is_running to block a run permanently after a crash.
A short lease is more useful:
type RunLease = { runId: string; workerId: string; expiresAt: Date;};A worker claims the run for a bounded period and renews while it is actively making progress. Another worker can recover the run after the lease expires.
The exact implementation can use database row locks, a queue's visibility timeout, Redis leases, or a workflow engine. What matters is that worker ownership is temporary and recoverable.
Side effects must be replay-safe
Checkpointing creates intentional replay.
That makes the previous article's idempotency boundary essential.
Suppose the open-pr step does this:
const pr = await github.createPullRequest(...);await saveCheckpoint({ nextStep: "done", pullRequestId: pr.id });If the worker crashes between those two lines, recovery runs createPullRequest again.
The step needs a persisted logical operation key:
type SideEffectState = { operationKey: string; status: "pending" | "completed" | "unknown"; externalId?: string;};The recovery path first checks whether that operation already produced a PR. It does not assume “checkpoint missing” means “side effect did not happen.”
Durability without replay-safe writes is a duplication engine.
Python state machine example
from dataclasses import dataclassfrom enum import Enumclass Step(str, Enum): ANALYZE = "analyze" EDIT = "edit" TEST = "test" APPROVAL = "approval" OPEN_PR = "open-pr" DONE = "done"@dataclass(frozen=True)class Checkpoint: repository_id: str base_commit: str task: str next_step: Step branch_name: str | None = None patch_artifact_id: str | None = None test_artifact_id: str | None = None approval_id: str | None = Noneasync def execute_next(run_id: str, store) -> None: checkpoint = await store.load_checkpoint(run_id) match checkpoint.next_step: case Step.ANALYZE: updated = await analyze_repository(checkpoint) case Step.EDIT: updated = await create_patch(checkpoint) case Step.TEST: updated = await run_tests(checkpoint) case Step.APPROVAL: await store.mark_waiting_for_approval(run_id) return case Step.OPEN_PR: updated = await open_pr_idempotently(checkpoint) case Step.DONE: await store.complete_run(run_id) return await store.commit_checkpoint(run_id, updated)This is deliberately not a fully generic workflow engine. It shows the core boundary: one worker loads durable state, performs one resumable transition, persists the next state, and can disappear.
For complex production workflows, an established durable workflow/orchestration system may be better than implementing leases, timers, replay, and signals yourself.
Human approval is just another durable wait state
The approval screen should not depend on a worker process staying alive.
When the agent reaches a risky action:
- persist the exact proposed action and arguments;
- set run status to
waiting-for-approval; - release the worker lease;
- notify the reviewer;
- when an approval event arrives, enqueue/resume the run.
The workflow may sleep for ten minutes or three days without consuming a worker.
type ApprovalCheckpoint = { action: string; arguments: unknown; argumentsHash: string; requestedByRunId: string;};On resume, verify the action still matches what was approved and that relevant authorization/resource versions have not become invalid.
A durable pause should not become a bypass around freshness and permission checks.
Timers and retries should also be durable
If a dependency says “retry after 90 seconds,” I do not want a Node process sleeping for 90 seconds.
Persist the next-at timestamp and let a scheduler or delayed queue wake the run.
type RetryState = { attempt: number; nextAttemptAt: string; reason: string;};That survives deployment and avoids tying up a worker for backoff time.
The same pattern handles “wait until business hours,” “resume after document processing,” and other long delays.
Separate nondeterministic calls from replayable decisions
Model calls, time, random IDs, network responses, and external tools are nondeterministic.
If recovery re-executes everything from the beginning, it may produce a different plan and different arguments.
I prefer to persist important outputs at their boundary:
- selected plan;
- normalized tool arguments;
- model/provider/version metadata;
- tool result or artifact reference;
- approval decision;
- generated idempotency key.
A resumed run can use those stored results rather than asking the model to recreate history unless the product deliberately wants replanning.
This also makes deterministic debugging much easier later.
Checkpoint frequency is a tradeoff
Writing after every token would be absurd. Checkpointing only at the end defeats durability.
Useful boundaries are usually after expensive or externally meaningful steps:
- after a retrieval batch;
- after a model produces an accepted plan;
- after a file patch is stored;
- after a test run completes;
- before/after a side effect;
- before entering a human wait state.
I ask: how much work am I willing to repeat after a crash, and is repeating that work safe?
That answer determines checkpoint granularity.
Recovery needs an invariant checker
A checkpoint can become invalid while the run sleeps.
The repository branch moved. A customer record was deleted. An approval expired. A tool schema changed. A budget was reduced.
Before resuming, validate the assumptions encoded in durable state:
type ResumeValidation = { valid: boolean; requiresReplan: boolean; reason?: string;};A stale run may need to re-read current state or return to an earlier planning step instead of continuing blindly.
Durable does not mean frozen reality.
Observability should follow the run across workers
A run ID becomes the correlation key across:
- queue deliveries;
- worker processes;
- model calls;
- tool calls;
- checkpoints;
- approvals;
- retries;
- final output.
Trace IDs can change between resumed executions, but every span/event should carry the durable run ID so the entire lifecycle remains queryable.
That is how you debug “this agent took six hours” when most of those hours were waiting for approval and only forty seconds were actual compute.
When an in-memory agent is enough
A short interactive assistant that normally finishes in a few seconds does not need a workflow platform.
Durability becomes worth the machinery when runs are expensive, long, side-effectful, pausable, or operationally important enough that restart-from-zero is unacceptable.
The key design change is simple: the worker is not the workflow.
The workflow is durable state plus transitions. A worker temporarily advances it.
Once that distinction is in place, deploys, crashes, approvals, retries, and queue redelivery stop being special agent failures. They become ordinary workflow events that the system was built to survive.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article