Durable agent runs on Electric streams
Record each turn as a run, lease every attempt with a fenced heartbeat, keep agent state in Electric's durable streams, and never replay a tool call to recover.
Record each turn as a run, lease every attempt with a fenced heartbeat, keep agent state in Electric's durable streams, and never replay a tool call to recover.
A chatbot answers; an agent plans steps and uses tools to do the work. Start read-only, add approvals for irreversible actions, enforce the user's permissions.
Each customer's Twin runs as a full stack on its own server, shipped as immutable images through one path: one CI run, staging, then production on one commit.
A recurring report. A slow review. A prototype that needs to work in the real world.
An agent turn can run for twenty minutes and make dozens of model and tool calls, and we deploy far more often than that. To let turns survive restarts, deploys and dropped clients without losing or repeating work, the Company Twin records every turn as a run in Postgres, runs it under a lease that a heartbeat has to keep renewing, and stores the agent's own state in Electric's durable streams. If the process executing a turn stops mid-flight, another can pick straight up from the log, with a hard guarantee that the stopped process can't wake up later and write over it, and without redoing anything that's already happened.
(Electric is an open-source sync engine for Postgres; its Durable Streams project provides replayable HTTP streams, and its agents runtime builds on top of them.) Getting that contract to hold through real deploys, and knowing where to leave Electric out, took a handful of painful lessons.
Key takeaways
A chat completion is one request and one response. An agent turn is a loop: plan, call a tool, inspect the result, call the model again, sometimes for ten or twenty minutes while it reconciles a ledger or works through a mailbox. In that window a release might restart the process, a host might reboot, the person who asked might shut their laptop, or a network call might hang. All four are routine. None of them should drop the work, run it twice, or leave a half-written reply looking finished.
The hard part isn't saving progress. It's making sure that once a second process takes over, the first can't come back and write over it. That's what leases and fencing are for.
A session owns a task, and each turn is a task_run row in the control plane's Postgres database. Sending a message creates the next run on the server and returns 409 if the session already has one in progress, so two turns of the same conversation can never collide. Clients never create runs directly and never touch the agent's internal streams; they only read projections served by the control plane.
When a run is admitted, its limits go straight into the run's own event log: a deadline (30 minutes for an ordinary turn) and a tool-call budget (300). Because those live on the run rather than being pulled from config on every step, a turn admitted under one release keeps its limits even if a later deploy changes the defaults.
Executors claim queued runs from the tenant API in batches. Claiming is a single SQL statement selecting eligible rows with FOR NO KEY UPDATE SKIP LOCKED (so concurrent executors never block on or grab the same row), ordered fairly across tenants so one busy organisation can't starve a quiet one. Each claim writes the lease owner, sets an expiry 30 seconds ahead, and increments the run's attempt number. Once a lease expires, the run becomes eligible again as a new attempt.
While it works, the executor sends a heartbeat every 10 seconds. That heartbeat locks the run row and checks four things: the run still exists and isn't cancelled, the lease owner is this worker, the attempt number matches, and the turn hasn't passed its deadline. Only then does it extend the lease. Any refusal, or a malformed reply, tells the worker it no longer owns the attempt, and it fences itself immediately, making no further writes. Every event, heartbeat and terminal write carries the same identity, so a late write from an old attempt is rejected even if the stalled process hasn't noticed yet.
It's the classic fencing-token pattern from distributed systems, with the attempt number acting as the token. Nothing depends on clocks agreeing or a process noticing it was paused; the database decides, and the database only has one answer.
The agent itself runs on Electric's agents runtime (version 0.6.3 at the time of writing), with an agents server coordinating entities over durable streams. An entity is one addressable agent with its own stream; in the Twin, each session is one entity. A durable stream is an append-only HTTP log with catch-up reads and live tailing, so a reader that falls behind or reconnects picks up from its last offset instead of starting over. Every write carries a producer (the writer), an epoch (a generation number, where a newer epoch renders older writers' appends stale) and a sequence number, and the stream server deduplicates on that triple so a retried append lands once. When new input arrives for an entity, the agents server wakes it (asking the executor to run the entity's handler on the new input), and each wake starts a new epoch.
That gives us what the Electric team call "the agent is the durable stream": the transcript, the audit trail and the context for the next step are all projections of one ordered log, rather than separate stores that can drift apart. When an executor resumes an entity, it reads the log instead of trusting anything in memory.
Three real failures taught us how to hold that contract together.
| What happened | Why | What we changed |
|---|---|---|
| A new message arriving mid-turn killed the running turn's final write | Waking the entity bumped its epoch, which invalidated the running handler's producer, so its last append was rejected as stale | One wake at a time per entity. New triggers wait until the running turn says it's done or its wake lease (90 s) lapses |
| A restart of the agents server stranded turns until their deadline | In-flight wakes lived only in memory, so nothing delivered them again | In-flight wakes are written to the registry and restored on start; a reconciler refires any wake whose latest offset was never delivered |
| Two deploy slots could reserve the same epoch | Each slot counted epochs locally | Epochs are reserved in the shared durable store, where the producer triple makes the reservation atomic |
All three boil down to the same rule: anything that decides ownership has to live in shared, durable state, never in one process's memory, because the process is the thing that disappears.
Recovering a turn would be easy if we were willing to rerun things. We're not, because a tool call might send an email, post a bill or mutate a record. So we enforce the opposite rule: recovery never replays a model call or a tool call.
The executor and its agents server run blue-green as a pair of slots on each server. A release brings up the new slot, waits for its health gate, then shifts new work to it. Both resident slots have to be on the same release before claims flow, because a run claimed by one release and resumed by another is the exact mixed-version bug we want to prevent. The old slot then drains: it claims nothing new and finishes the turns it holds on the release they started on, and its agents server stays up until that drain finishes. If the drain can't be observed or misses its deadline, convergence halts and leaves the healthy new slot routed; it never kills the old slot's dependency just to tidy up.
A liveness check doesn't prove a release works. On 1 September 2026 a mixed-version bug in the execution fence sailed past every health check, because an empty queue always looks healthy. Every deploy touching the control plane, the executor or the Electric runtime now runs a contract canary: an isolated, authenticated task and session that the executor has to carry through claim, claim-time context, the executor-to-runtime boundary, entity creation, fence admission and normal completion. The runtime returns a fixed protocol marker before any model call happens, so the canary costs nothing in tokens. Only a terminal completion with that exact marker passes; claimed or running doesn't count. The wider server rollout is covered in one customer per server.
Electric also offers Shapes for syncing subsets of Postgres straight to clients. We evaluated them for our desktop and iPhone apps and passed for now. Our clients don't consume raw tables; they consume server-built, client-safe projections of channels, records, sessions, inbox and files, filtered by organisation, person and private-channel membership, then refetched through the API that enforces those rules. Making Shapes fit would have meant a new gateway understanding our signed subject tokens, serialisers mapped into shape rows, and matching rules for deletions and schema changes. At that point you're building a second sync engine rather than swapping one in. Our native apps stay on SQLite with a cursor over our workspace event feed, with the conditions for revisiting Shapes written down.
We also bypass the entity layer on one path. Turns on our self-hosted models (where time to first token matters most) are accepted and persisted in a single transaction and dispatched straight to the runtime, which streams directly from the model. Authentication, scope, grants and lease checks stay intact; the entity, inbox and stream setup drop out. It's a deliberate latency exception, backed by its own lease (30 seconds, renewed every two) and its own recovery scanner.
If your agents run for more than a few seconds, durability belongs in day-one architecture rather than a later patch. These are the three tiers we'd weigh with your team.
| Option | When to use | Trade-offs |
|---|---|---|
| Stateless retries | Short, read-only agents where repeating a call is harmless | Simple, though a retried write creates a duplicate and a long turn restarts from zero |
| Runs in your database with leases and fencing | Any agent that writes, or runs for minutes | Needs a heartbeat, an attempt number checked on every write, and a rule for unknown outcomes |
| Agent state in a durable log (Electric or similar) | Long, multi-step agents where resuming mid-turn matters | Strong recovery and audit; ownership decisions must still live in shared state, never in memory |
Before you call an agent run durable
For how agents earn the right to act in the first place, see from chatbots to AI agents that do the work, and for why a message from another agent never counts as permission on its own, talk is not authority.
Every turn in the Company Twin runs on this path: recorded in Postgres, leased, recoverable across deploys and never silently repeated. Explore the Twin runtime →