# Durable runs and streaming

How runs are queued, leased and automatically resumed from checkpoints after a crash, how to scale out with workers, and how tokens stream to the IDE and your apps.

Source: https://glamorous-boar.cloudvent.net/durable-runs/

---

## Durable execution

Every run goes through a **database job queue**. Workers claim jobs under a renewable **lease**, run them, and checkpoint every finished node. If a worker or the server stops mid-run, another worker (or the restarted server) **resumes the run from its checkpoints** without repeating finished nodes.

<Diagram caption="A run's lifecycle in the queue.">

```
flowchart LR
  S([POST /runs]) --> Q[queued]
  Q -- worker claims --> L[leased: heartbeat renews]
  L -- run finished --> D([done])
  L -- graceful shutdown --> Q
  L -- lease expired --> R[another worker reclaims and resumes from checkpoints]
  R --> L
  L -- Human Approval --> W[waiting]
  W -- POST /resume --> Q
```

</Diagram>

### How it works

- **Submitting.** Starting a run writes the run and its job in one transaction. Resuming (approvals, interrupted runs) re-queues the job with the responses.
- **Claiming** is a single conditional `UPDATE … WHERE status='queued' OR (status='leased' AND lease expired)`, atomic on SQLite and PostgreSQL, so two workers never hold one job.
- **Heartbeat.** A running job renews its lease every `lease_seconds / 3` (default lease 30 s), picks up cancel requests, and cancels locally if it lost the lease.
- **Recovery.** A crashed worker simply stops renewing; the next claim resumes from checkpoints (finished nodes restored, not re-run).
- **Side effects are not repeated silently.** If a non-idempotent node was mid-flight, the run fails as `RUN_INTERRUPTED` and can be resumed with `force` once you have checked.
- **Capped.** At most `AGENTICMIND_MAX_RUN_ATTEMPTS` (3) recoveries, then `RUN_RECOVERY_LIMIT`.
- **Graceful shutdown.** Stop claiming, give running runs a grace period, then release their jobs back to the queue; another worker continues immediately.

### Checkpoints

After each top-level node finishes, its exact outputs, activated branches and run outputs are stored. Values that are not JSON or that contain a resolved secret are marked non-restorable and simply re-run on resume. Loop iterations are not checkpointed individually.

### Scaling out with workers

By default a worker runs **inside the API process** (`AGENTICMIND_EMBEDDED_WORKER=1`). To scale:

<CodeBlock language="bash" filename="terminal" showCopy={true}>

```
# PostgreSQL + 3 workers sharing the data volume
docker compose --profile postgres --profile workers up --scale worker=3
```

</CodeBlock>

or run `agenticmind-worker` processes against the same database and data directory, and give the API `AGENTICMIND_EMBEDDED_WORKER=0`. Each worker claims at most `AGENTICMIND_MAX_CONCURRENCY` runs. Cancels and waits work across processes. Several processes need PostgreSQL (or one shared SQLite file on one host) and a shared data directory.

### Resuming by hand

`POST /api/runs/{id}/resume` with `{"force": true}` re-executes unfinished nodes of an interrupted run, even if they are not idempotent. The IDE offers a **Resume** button on interrupted runs.

## Streaming

LLM and Agent nodes stream text **when someone is listening**; otherwise they make normal calls.

- **Providers:** OpenAI-compatible SSE (OpenRouter, OpenAI, Azure, Mistral, Groq, DeepSeek, Together, xAI, Hugging Face, Ollama) with tool calls rebuilt from fragments; Anthropic via the SDK's stream helpers (thinking blocks and usage kept); Gemini `streamGenerateContent`; Bedrock and other providers deliver the whole text as one chunk.
- **Delivery across processes:** deltas are buffered and written to the database in batches (every ~100 ms or 256 characters, always before the node's next trace event), so any API process can serve them wherever the run executes.
- **The run event stream** (`GET /api/runs/{id}/events` with `Accept: text/event-stream`) carries `event: token` messages with a chunk `seq` alongside `event: trace`. `?tokens=false` leaves tokens out. Finished runs replay their tokens. Reconnect with `Last-Event-ID`.
- **One call for apps:** `POST /api/projects/{id}/runs/stream` emits `event: run` (the ID), then `token` and `trace` events (`?trace=false` to skip traces), then `result` (status, outputs, error) and `end`.

<CodeBlock language="bash" filename="terminal" showCopy={true}>

```
curl -N -X POST "http://localhost:8000/api/projects/prj_abc123/runs/stream?trace=false" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"question": "Explain RAG in two sentences"}}'
```

</CodeBlock>

Deltas are a live preview: node outputs remain the source of truth, and a node's deltas add up to its output.

### Latency notes

Delivery is batched (~100 ms) and polled (~200 ms): smooth typing, not per-token latency. Reasoning models may think for many seconds before the first visible token. Reasoning-strategy and guardrail nodes, MCP results and exported apps do not stream yet.

## Theory

Why durable execution, idempotency and checkpoints matter for agents: [Production AI systems](/learn/production-ai-systems/).
