Skip to content

Resume a three-hour dispatch run after the worker dies

Record each completed step of an agent run in a journal before starting the next. When a worker dies, a new one replays the journal, skips every step already recorded and carries on. Side effects are never repeated, and the gap between doing a step and recording it is closed by idempotency keys.

20 MIN

By AIAgentInterviews · Updated

TL;DR: Treat the run as a list of steps and write each result to durable storage before the next step starts. A new worker resumes by replaying that record: recorded steps return their stored results, unrecorded ones execute. Key every side effect, because a worker can die between doing a step and writing it down.

Where you are. Module one, lesson one. Kestrel's dispatch agent runs; now it has to keep running when the machine under it does not.

A run longer than a worker's life

A truck carrying shipment KF-5531 breaks down. Kestrel's dispatch agent asks carriers for quotes, rebooks with the best one, and notifies the customer. Between those steps it waits: carriers take minutes to quote, a dispatcher may take an hour to approve, and the customer notification waits for the booking to confirm. A single exception can take three hours.

Workers do not live that long reliably. Deployments restart them, autoscaling removes them, machines fail. If the run's progress lives only in a worker's memory, a restart either loses the run (the customer is never notified) or starts it again (the shipment is rebooked twice). Neither is acceptable for something that spends money with carriers.

In plain language. A journal is the durable record used to resume work. Replay rebuilds a run from recorded results. An effect changes an external system; recording that you intended an effect does not establish that it happened.

A journal of completed steps

The fix is to make progress durable. Each step's result is written to storage that outlives the worker before the next step begins. To resume, a new worker walks the same steps in order: for each step already in the journal it takes the stored result without calling anything; for the first step not in the journal it executes for real.

class Crash(Exception):
    pass

CALLS = []   # every real call to the outside world, to count side effects

def carrier_quote(shipment):
    CALLS.append("quote")
    return {"carrier": "Northline", "eta_hours": 18}

def rebook(shipment, carrier):
    CALLS.append("rebook")
    return {"booking": f"BK-{shipment}-{carrier}"}

def notify(shipment, booking):
    CALLS.append("notify")
    return {"sent": True}

STEPS = [("quote", lambda s, j: carrier_quote(s)),
         ("rebook", lambda s, j: rebook(s, j["quote"]["carrier"])),
         ("notify", lambda s, j: notify(s, j["rebook"]["booking"]))]

def run(shipment, journal, crash_after=None):
    """Replay finished steps from the journal; execute only the ones not recorded."""
    for name, step in STEPS:
        if name in journal:
            continue
        journal[name] = step(shipment, journal)
        if name == crash_after:
            raise Crash(f"worker died after {name}")
    return journal["notify"]

journal = {}  # in production: one stored row per step, written before the next starts
try:
    run("KF-5531", journal, crash_after="rebook")
except Crash as e:
    print(e)  # => worker died after rebook
print(run("KF-5531", journal))  # => {'sent': True}
print(CALLS)  # => ['quote', 'rebook', 'notify']

The first worker gets a quote, rebooks, records both, and dies. The second worker finds quote and rebook in the journal, skips them, and sends the notification. Each outside call happened exactly once, which is what the CALLS list proves.

The model's turns are steps too

In an agent, the steps are not a fixed list. The model decides what to do next, and its decisions depend on earlier results. That is fine, as long as every model call is itself a recorded step. On resume, the replayed model call returns the reply it gave the first time instead of asking the model again. If the model were called again, it might choose differently, and the rest of the journal would no longer match the run being replayed. Recording model replies makes replay deterministic even though the model is not.

This is the core idea behind durable execution frameworks: a recorded event history, deterministic replay over it, and activities (here, tool calls and model calls) whose results are stored. You can build the small version above in an afternoon. The frameworks add timers, retries, versioning of the step list and visibility into stuck runs, which matter once you have many of them.

Trace
KF-5531: one run, two workers
  1. 01toolcarrier_quote(KF-5531)
  2. 02checkjournal: quote recordedpass
  3. 03toolrebook(Northline)write
  4. 04checkjournal: rebook recordedpass
steps 0tool calls 2writes 1context 0 tok
1/3

Worker A does two steps

A quote and a rebooking, each written to the journal as it finishes.

The gap the journal cannot close

There is one moment the journal does not cover: after a step has acted and before its result is written. A worker that dies there leaves no record, so the next worker runs the step again. For a quote, that costs a second quote. For a rebooking, it books a second truck.

The answer is the one from the harness course: every side effect carries an idempotency key built from what the effect is (rebook this shipment, for this exception). The replacement worker sends the same key, and the carrier's API returns the original booking instead of making a new one. Journal and keys together give the property you want, which is that every effect happens once however many workers it takes.

Things that break replay

Replay assumes the steps run the same way twice. Three habits break that. Reading the clock or generating random values inside the run's own logic, instead of inside a recorded step, gives a different value on replay. Changing the step list while runs are in flight means an old journal no longer lines up with new code, so version the run definition and let old runs finish on the old version. And keeping state in a worker's memory between steps instead of in the journal loses it on restart. All three show up as runs that resume into the wrong state, which is far harder to debug than a run that simply failed.

Place the crash on both sides of the booking

Kestrel's dispatcher books a carrier, then records the receipt. Put a synthetic crash at each boundary and predict the next worker's behavior before running the fixture.

Crash pointDurable evidenceSafe recovery
Before dispatchOperation identity, no receiptSubmit under the same identity
After carrier acceptance, before journal writeOperation identity, outcome unknownQuery or deduplicate at carrier
After receipt journaledCompleted resultReplay the recorded receipt

The middle row is the important one. The absence of a journaled result does not prove the carrier did nothing. A worker that simply executes every unrecorded effect can create a second booking. The operation identity must survive the crash and reach the service that owns the effect.

Model results need recording too. Recalling the model during replay may produce a different carrier choice even with identical input. Once an observed decision has led to an effect, recovery cannot replace its history with a newly generated plan.

Use the fake carrier's ledger as your oracle. The recovered transcript should describe the existing booking, and the ledger should contain exactly one logical effect. Several transport attempts can still be consistent with that result.

DiagramThe crash gap crosses two systems
  1. 1Worker→Journal

    Save operation ID

    Persist the identity before the external effect.

WorkerCarrierJournalSave operation ID
1/6

Save operation ID

Persist the identity before the external effect.

Read Worker as the logical worker role: the process before and after the crash is different.

What if · interview follow-ups

Change one condition

A worker dies after carrier acceptance but before it journals the receipt.

  1. Start here

    Does “no completed step in the journal” authorize another booking?

Do this before moving on

Pick the longest-running task your agent does. List its steps, mark each one that has a side effect, and write down what happens today if the worker dies just before, during and just after each marked step. Any "during" or "after" that repeats an effect needs a journal entry and a key.

Review your result. Keep one fixture for each crash boundary. Assert the carrier ledger, journal and reported state after recovery. A restart that merely stops crashing is not enough.

Go deeper

Key takeaways

  • Write each step's result durably before the next step starts; resume by replaying the record.
  • Record model replies as steps, so replay returns the same decisions.
  • Idempotency keys close the gap between doing a step and recording it.
  • Keep clocks, randomness and memory inside recorded steps, and version the run definition.

Check yourself

Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.

  1. 1On resume, why should the replayed model call return the stored reply instead of calling the model again?

  2. 2A worker dies after the carrier confirms a rebooking but before the journal entry is written. What prevents a second booking?

  3. 3Which of these breaks deterministic replay?

Sign in to track which lessons you have finished.