Your Agent's Worker Died Mid-Run. What Ran Twice?
The previous article moved a long Agent run out of the HTTP request and into a task. The browser can...
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.
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. A real one may keep keys only 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
Sumber artikel open-source oleh KristinZ di DEV Community — Baca artikel asli. Topik:
#llm#agents#webdev#typescript

Komentar