The previous article moved a long Agent run out of the HTTP request and into a task. The browser can close the tab, and the run continues.
That raises the next problem. The run now lives in a worker process, and worker processes die: deploys, out-of-memory kills, crashed nodes. Something picks the task up again. The question is what that recovery repeats.
An Agent run is a sequence of steps, and some of those steps have consequences:
plan → paid LLM call
research → paid LLM call
send_email → a message in someone's inbox
write_report → paid LLM call, then a row in your database
Repeat plan and you pay twice. Repeat send_email and a customer gets two emails.
I built this four-step Agent with a SQLite job table and a worker process, then killed the worker on purpose at every point in the run. I also froze it mid-step and woke it up after another worker had taken over. Nothing calls a real model, so it runs for free: aiengineering-book/agent-task-demo, npm run durable.
The Result First
A clean run sends 1 email and makes 3 paid LLM calls. Each strategy was tested at 12 crash points:
| Recovery strategy | Crash points with a duplicate email | Extra LLM calls, all crash points |
|---|---|---|
| Restart the task from scratch | 4 of 12 | 18 |
| Skip steps that have a completion marker | 1 of 12 | 3 |
| Markers + idempotency key on the email | 0 of 12 | 3 |
Then the harder case. A worker that pauses instead of dying loses its lease, another worker takes over, and the first one wakes up. 20 runs each:
| Variant | Runs with 2 emails | Paid LLM calls (avg) | Runs where the old worker kept writing |
|---|---|---|---|
| Markers | 20 of 20 | 5.0 | 20 of 20 |
| Markers + idempotency key | 0 of 20 | 5.0 | 20 of 20 |
| Markers + idempotency key + fencing | 0 of 20 | 4.0 | 0 of 20 |
Completion markers keep recovery from repeating finished work. They don't stop two workers running the same task. That needs fencing. Neither one removes the need for an idempotency key on the external call.
The Setup
The job table holds one row per Agent run:
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
status TEXT NOT NULL, -- pending | running | done
epoch INTEGER NOT NULL DEFAULT 0,
lease_owner TEXT,
lease_until INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
report TEXT
);
A worker claims a task that is pending, or whose lease has run out. The claim bumps epoch, which comes back later as the fencing token:
UPDATE tasks
SET status = 'running', epoch = epoch + 1, lease_owner = ?, lease_until = ?,
attempts = attempts + 1
WHERE id = (SELECT id FROM tasks
WHERE status = 'pending' OR (status = 'running' AND lease_until < ?)
LIMIT 1)
RETURNING id, epoch
While it runs, the worker renews its lease every 200 ms (the lease is 600 ms). A dead worker stops renewing, the lease expires, and the next worker's claim succeeds. That is how a crash gets noticed. Nothing has to watch for it.
The worker runs in its own process. The experiment kills it with SIGKILL: no finally blocks, no cleanup, the same as an out-of-memory kill. The LLM and the mail service are mock HTTP servers that count every call, so "what ran twice" is a number, not a guess.
The 12 crash points are three per step:
- before: the step hasn't started.
- after-call: the LLM or mail call returned, but nothing has been recorded yet.
- after-marker: the step's completion has been committed.
Restart From Scratch
The simplest recovery runs the whole task again. It's correct only if every step is free and harmless to repeat. Here, neither is true:
- A crash anywhere after the email went out sends a second one. That's 4 of the 12 crash points.
- Every LLM call made before the crash is paid again: 18 extra calls across the 12 runs, up to 3 in a single run.
For a chat answer, restarting is fine. For an Agent that sends something, it isn't.
Completion Markers
The next step up records each finished step, with its output, in a second table:
CREATE TABLE steps (
task_id TEXT NOT NULL,
step TEXT NOT NULL,
output TEXT NOT NULL,
worker TEXT NOT NULL,
PRIMARY KEY (task_id, step)
);
A resumed run skips any step that has a row and reads its stored output instead of recomputing it. Storing the output matters: write_report needs research's result, and without it the resumed run would have to call the LLM again to get it back. That makes the table a small journal, not only a list of checkboxes.
The rework drops to the one step that was in flight when the worker died. Across 12 crash points that's 3 extra LLM calls, one for each after-call point on an LLM step.
One duplicate email is left, at after-call:send_email. The email went out, the worker died before writing the marker, and the recovered run saw no marker and sent it again. No ordering fixes this. Write the marker before the call and a crash in between loses the email. Write it after and a crash in between duplicates the email. Your database and the mail service can't commit together.
The local write is different. write_report updates the task and writes its marker in one transaction:
tx(db, () => {
checkFence(task);
db.prepare(`UPDATE tasks SET report = ?, status = 'done' WHERE id = ?`).run(report, task.id);
db.prepare(
`INSERT INTO steps (task_id, step, output, worker) VALUES (?, ?, ?, ?)
ON CONFLICT (task_id, step) DO UPDATE SET output = excluded.output, worker = excluded.worker`
).run(task.id, step, report, workerId);
});
Either both happened or neither did, so a crash can't leave the step half done. Effects in your own database get exactly-once for free, as long as they commit with their marker.
Idempotency Keys
An external effect can't join your transaction, so the deduplication has to happen on the other side. The worker sends a key that is the same on every attempt:
if (strategy === 'keyed') headers['Idempotency-Key'] = `${task.id}:send_email`;
The mail service remembers keys it has accepted. A repeated request gets the first result back and sends nothing. With that, the email went out exactly once at all 12 crash points.
This only works if the downstream service supports it. Payment APIs such as Stripe accept an idempotency key. Check whether your email or messaging provider does. If yours doesn't, the fallback is to ask before acting ("did message X go out?") or to accept the rare duplicate.
A key also protects only for as long as the service remembers it. Stripe, for example, keeps keys for at least 24 hours; other services keep them for less, or don't say. Every retry has to fall inside that window, including a manual replay days later. Past it, a step whose outcome is still unknown shouldn't send again. Mark it for reconciliation instead, and when the call returns a provider message ID, store it with the step's marker, so whoever reconciles has something concrete to look up.
The 3 extra LLM calls don't go away. A call whose result was lost in a crash has already been paid, and model APIs don't generally deduplicate completions by key. The cost of a crash is the step in flight, and small steps keep that cost small.
The Worker That Wasn't Dead
A lease can't tell a dead worker from a stalled one. A long garbage-collection pause, a VM migration, or a container frozen under memory pressure stops the heartbeat exactly as a crash does. The lease expires, another worker claims the task, and then the first worker continues where it left off. It still thinks it owns the task.
The experiment freezes worker 1 with SIGSTOP in the middle of its research call. It waits for the lease to expire, starts worker 2, and resumes worker 1 (SIGCONT) as soon as worker 2 starts its own research call. Here is one run with completion markers, timed from the moment worker 1 resumed:
+ 0 ms w1 step-done research
+ 1 ms w1 call-start send_email
+ 17 ms w2 step-done research
+ 18 ms w2 call-start send_email
+ 157 ms w1 step-done send_email
+ 157 ms w1 call-start write_report
+ 173 ms w2 step-done send_email
+ 173 ms w2 call-start write_report
+ 312 ms w1 step-done write_report
+ 312 ms w1 task-done
+ 328 ms w2 step-done write_report
+ 328 ms w2 task-done
The two workers ran the rest of the task side by side, 16 ms apart. Each checked for the send_email marker before the other had written it, so both sent the email. That happened in all 20 runs. Markers protect a recovery that runs after the old worker is gone. They don't protect anything while it's still running.
The idempotency key stopped the second email, but both workers still finished the task, both paid for write_report, and both wrote the report. In this timing worker 2 always wrote last, so the stored result happened to be consistent. Under different timing the report could be built from one worker's research while the journal holds the other's.
Fencing
Fencing makes the old worker find out. Every write checks, inside its transaction, that the task's epoch is still the one this worker claimed:
function checkFence(task: Task) {
const row = db.prepare('SELECT epoch FROM tasks WHERE id = ?').get(task.id) as { epoch: number };
if (row.epoch !== task.epoch) throw new LostLease(`epoch ${task.epoch} superseded by ${row.epoch}`);
}
Worker 2's claim bumped the epoch, so worker 1's first write after waking up fails. Worker 1 logs lost-lease and stops:
+ 0 ms w1 lost-lease
+ 16 ms w2 step-done research
+ 16 ms w2 call-start send_email
+ 172 ms w2 step-done send_email
+ 172 ms w2 call-start write_report
+ 331 ms w2 step-done write_report
+ 331 ms w2 task-done
With fencing, the old worker wrote nothing in any of the 20 runs. Two costs remain:
- Worker 1's in-flight
researchcall was still paid, which is why the average is 4 calls, not 3. - Fencing protects your database, not the mail service. Worker 1 checks the epoch, then calls the service. If its lease expires between those two moments, the call goes out anyway. That's why the email still needs the key. Some systems pass the epoch along to the downstream service, which rejects anything older than the newest epoch it has seen. That works only if the service supports it.
Job Table or Durable Workflow Engine?
What's above comes to a little over 200 lines, comments included: a lease, an epoch, a step journal, a key on the external call. For an Agent whose steps take seconds to minutes and whose effects can carry an idempotency key, that covers recovery.
Durable execution engines (Temporal, Restate, Inngest and DBOS are examples) are built on the same core idea. They record each step's result and replay the record after a failure, so finished steps aren't run again. What they add is what you'd otherwise build next:
- Timers that outlive processes: "wait three days, then follow up".
- Waiting for outside events: human approval, a webhook, another workflow.
- Retry policies per step, with backoff and limits.
- Changing the code while runs are in flight: a run that started on version 1 of your steps can finish correctly after version 2 deploys.
- Visibility: what is running, where it's stuck, what each step returned.
My rule of thumb, not a measurement: start with the job table. Move to an engine when you notice you're building the second item on that list, or when a single run lasts long enough to span a deploy.
What an engine doesn't change is the boundary at the external call. A step that calls an outside service runs at least once. The engine can record that the step finished. It can't commit the email and the record together any better than your SQLite transaction can, so the step can still run again. The idempotency key goes to the downstream service either way.
What This Does and Does Not Establish
Established, in this setup:
- Where each recovery strategy repeats work, at every crash point of a four-step run, with hard kills rather than simulated exceptions.
- That completion markers didn't prevent duplicate side effects once a paused worker resumed next to its replacement (20 of 20 runs), and that fencing did (0 of 20).
Not established:
- Many workers, many tasks, or a real database server. This is SQLite with two processes on one machine.
- Other timings. The mock services answer in a fixed 150 ms, so worker 2 always trailed worker 1 by the same margin. Other timings would interleave the two workers differently.
- Real LLM or mail providers. The mock mail service deduplicates perfectly and keeps keys forever. A real one keeps them for a limited window.
- Anything about the engines named above beyond their documented core model. None were run here.
A Checklist for Agent Workers
- Claim tasks with a lease that the worker renews. Expiry is the crash detector.
- Increment an epoch on every claim and check it inside every write transaction.
- Store each step's output with its completion marker, so a resumed run reads finished results instead of recomputing them.
- Commit local effects in the same transaction as their marker.
- Send external effects with an idempotency key derived from the task and step, not from the attempt.
- Keep paid steps small. A crash costs the step in flight.
Further Reading
This is part of a series on long-running AI work:
- Your LLM App Is Wasting Money: What Happens When Users Close the Tab?
- You Aborted the LLM Request. Did You Actually Stop the AI?
- Your AI Agent Doesn't Belong Inside an HTTP Request: the task model this article builds on.
- Your Users Click "Regenerate". Are You Paying Twice?
Agent loops, tool calls, and how agents fail are covered in Chapters 13 and 14 of 《AI Engineering with TypeScript — A Comprehensive Guide to Building AI Agents》 at Leanpub. Timeouts and interrupts in multi-agent runs are in Chapter 16. The book's companion code is at github.com/aiengineering-book/code.
References
- Node.js
node:sqlite - Martin Kleppmann, How to do distributed locking (leases and fencing tokens)
-
aiengineering-book/agent-task-demo:
src/durable/andresults/durable-2026-11-30.txt
Top comments (11)
The three-row progression is the cleanest demo of this I've seen — markers fix re-doing finished work, the idempotency key fixes the external side effect, and only fencing stops two live workers. The subtle part worth underlining: the idempotency key only works if it's derived deterministically from the task, not generated at call time. If a retried worker mints a fresh UUID for the email, the provider sees a new request and you're back to two emails even with "idempotency" in the code. Deriving it as
hash(task_id + step_name)is what makes recovery actually safe. One thing I'd add to the fencing row: the epoch/lease number has to travel all the way to the write and be checked there (compare-and-swap on the row), not just checked when the worker wakes up — otherwise the zombie worker passes the wake-up check, then stalls, then writes after the new worker already fenced it. Did your SQLite version enforce the fence at write time, or at claim time? That gap is where the "0 of 20" can quietly become "1 of 20" under real scheduling jitter.Both points are right. The key in the demo is derived, not minted: Idempotency-Key: ${task.id}:send_email. A retried worker sends the same key, which is the only reason the keyed row reads 0. A fresh UUID per attempt would look idempotent in the code and do nothing.
The fence is enforced at write time. Every write runs inside a BEGIN IMMEDIATE transaction that first reads the task's epoch and throws if it changed, then writes. BEGIN IMMEDIATE takes SQLite's write lock before that read, so a new claim can't land between the check and the write. That makes it a compare-and-swap on the row. There's also a check just before each external call, but that one only saves work. It can't be the guarantee, because the lease can expire during the call, and that's exactly the gap the idempotency key covers. On a multi-writer database I'd write it as UPDATE ... WHERE id = ? AND epoch = ? and check the row count, rather than a separate read.
The 20/20 zombie-worker row is where most production setups get burned, because a GC pause or stalled upstream call looks identical to a dead worker from outside.
Two subtle bugs I hit in this exact durability boundary:
inngest/inngest-js#1904, awrapStepmiddleware throwing on a memoized step during replay left the step promise unsettled instead of propagating the error, so recovery stalled right after reading the completion marker. Testing middleware failures during replay catches a class of hangs that crash-point tests miss.Did your lease-fencing test also cover a provider succeeding right as the lease expires and the retry arriving after the provider's dedup window?
That's a great field report, and a sharper version of the gateway case than I could test.
The billing gap closing once transport.abort() dropped the socket instead of a graceful close draining the buffered chunks is the arm D mechanism showing up one layer further in. Mocks hide it, as you found. No, I haven't run the probe through a Python gateway. Everything went direct to DeepSeek, with only a local network proxy in the path. It would be a good next test, since the balance-meter method works whatever sits in between. The retry point deserves to be in the article too: a wrapper that treats an AbortError as a network failure turns a user's cancel into a fresh, fully billed request. Checking signal.aborted before retrying is the one-line guard.
That's a great field report, and a sharper version of the gateway case than I could test.
The billing gap closing once transport.abort() dropped the socket instead of a graceful close draining the buffered chunks is the arm D mechanism showing up one layer further in. Mocks hide it, as you found.
No, I haven't run the probe through a Python gateway. Everything went direct to DeepSeek, with only a local network proxy in the path. It would be a good next test, since the balance-meter method works whatever sits in between. The retry point deserves to be in the article too: a wrapper that treats an AbortError as a network failure turns a user's cancel into a fresh, fully billed request. Checking signal.aborted before retrying is the one-line guard.
The crash matrix makes the boundaries unusually clear. I would carry one logical task ID through the step journal, worker epoch, attempt, and external idempotency key in the trace. At
after-call:send_email, a missing completion marker means “outcome unknown,” not “email failed,” and that difference matters when the provider’s key retention expires. Does the demo record a dispatch event separately from the completion marker so an operator can see that uncertainty?Agreed.
A missing marker after the call means "outcome unknown", not "failed", and that's what goes to reconciliation once the key's retention has run out. In the demo the dispatch is only partly recorded. The worker logs a call-start event with its epoch before every external call, and the step journal only gets a row when the step completes. So the uncertainty is visible in the logs but not queryable in the journal. The better shape is what you describe: write a dispatched row to the journal (task ID, step, epoch, attempt, idempotency key) before the call, then mark it done with the provider's message ID afterwards. A dispatched row with no completion is then exactly the "outcome unknown" queue an operator needs.
This is the rare agent-reliability post that actually measures instead of asserts — the two tables are the whole argument. The one that sticks with me is the zombie-worker table: markers alone still double-sent in 20 of 20 runs, and the idempotency key fixed the email but not the fact that both workers finished the task. Fencing is the only thing that stopped the old worker writing, and even then the average is 4.0 calls, not 3 — the in-flight step is always paid. One gap your own 'not established' list names: a real mail provider may keep idempotency keys only for a short time. If a run retries days later and the key has expired, the second send goes through — so is the key's lifetime the real expiry you have to design around, and would you scope it to the task's retry window?
Thanks.
Yes, the key's lifetime is the expiry you actually design around. The experiment couldn't show it, because the mock keeps keys forever. I'd scope it the way you suggest: retries are only automatic inside the provider's retention window (Stripe documents at least 24 hours). After that, a step whose outcome is unknown stops and waits for reconciliation, using the provider's message ID if the journal has one. I've added that to the article.
And yes, the 4.0 is the honest cost. Fencing stops the old worker from writing, but the call it already had in flight has been paid for. Small steps keep that cost small.
The key's retention window needs to cover the whole retry window, including manual replays. If a send is still uncertain after that window, a retry can become a second email. I'd leave it for reconciliation rather than silently send again. The step journal should keep the provider's message ID when one is returned, so an operator has something concrete to look up.
Agreed on all three, and I've added them to the article. The key's lifetime has to cover every retry path, manual replays included. Past that window, an uncertain send goes to reconciliation rather than out again. And the provider's message ID belongs in the step journal next to the marker, so the reconciler has something to look up instead of guessing from timestamps.