Durable Execution, Checkpoints and Approvals
A long task should survive a restart without forgetting its place or repeating its actions.
Durable execution records progress in reliable storage so that a run can resume after a crash, deployment or long wait. Systems do this by saving checkpoints of state or by replaying a recorded history of step results. Neither removes the need for operation keys on external actions, versioning for changed code, expiry on approvals and a person who can inspect and repair a stuck run.
What you will learn: why runs need durability, checkpoints and replay, resuming safely, approval pauses, a runnable template for a long-running task and what to verify in any product.
Prerequisites: Graphs, State Machines, Parallelism and Sagas and Reliable Tool Execution and Error Recovery.
What goes wrong without it
| Event | Without durable progress |
|---|---|
| Process restarts | Task disappears or starts again |
| Deployment | In-flight work is cut off |
| Approval takes two days | Memory and connections are long gone |
| Provider outage | Completed expensive steps are repeated |
| Crash after an action | Nobody knows whether it happened |
A short question answered in seconds rarely needs this: failing and asking again is fine. Tasks with many steps, long waits or real effects do.
Two ways to resume
| Aspect | State checkpoints | History replay |
|---|---|---|
| What is saved | The task state after steps | The results of each step in order |
| On resume | Load latest state, continue | Run workflow code again, returning saved results |
| Code requirement | State format must stay readable | Workflow decisions must be deterministic |
| Inspecting a run | Read snapshots | Read the event history |
| Examples | Graph libraries with checkpointers | Temporal and similar engines |
Replay in miniature
"""Durable execution in miniature: record results, replay after a crash."""
class Context:
def __init__(self, history):
self.history, self.position, self.executed = history, 0, []
def step(self, name, action):
if self.position < len(self.history):
recorded, result = self.history[self.position]
if recorded != name:
raise RuntimeError(f"history has '{recorded}' at step "
f"{self.position + 1}, code asks '{name}'")
else:
result = action()
self.history.append((name, result))
self.executed.append(name)
self.position += 1
return result
class Crash(Exception):
pass
def workflow(ctx, crash=False):
price = ctx.step("quote", lambda: 40)
ctx.step("reserve", lambda: "R-1")
if crash:
raise Crash
return ctx.step("charge", lambda: f"charged {price}")
history = []
try:
workflow(Context(history), crash=True)
except Crash:
print("crashed after", [name for name, _ in history])
second = Context(history)
print(workflow(second), "| executed on resume:", second.executed)
def changed(ctx):
ctx.step("check stock", lambda: True) # new step inserted first
return workflow(ctx)
try:
changed(Context(history[:2]))
except RuntimeError as error:
print("changed code:", error)
Output:
crashed after ['quote', 'reserve']
charged 40 | executed on resume: ['charge']
changed code: history has 'quote' at step 1, code asks 'check stock'
After the crash only the charge runs; the quote and reservation come from history. When a new step is inserted at the front, replay detects that the code no longer matches what was recorded. Real engines are far more careful: they persist history in a database, handle timers and concurrency and check more kinds of events. The principle explains a rule you will meet: workflow code must not read the clock, draw random numbers or call services directly, because a second run could decide differently. Such work belongs in recorded steps, often called activities or tasks.
What counts as a step
Step boundaries decide what is repeated after a failure. If one step searches, calls a model and sends an email, a crash at the end repeats all three. Split where results are expensive, where behavior could differ on a second run and where effects reach other systems.
| Work | As a step? | Reason |
|---|---|---|
| Model call | Yes | Costly and may answer differently |
| Read from a service | Yes | Data may change |
| External action | Its own step | Needs a key and confirmation |
| Pure formatting | Usually no | Cheap and repeatable |
| Current time or random value | Recorded or engine-provided | Must match on replay |
Very large results make histories slow and costly. Store the content elsewhere under a version or hash, and record the reference. Make sure the referenced object lives at least as long as the run.
Checkpointing
A checkpoint should contain enough to continue and to explain: task identifier, definition version, current position, results or references, pending actions, approvals, counters used and time. Store large documents elsewhere and keep references. Never store secrets in it; fetch credentials when needed.
How often you save is a trade-off. LangGraph documents three durability modes. Its "exit" mode persists only when execution leaves the graph, for success, error or interrupt, so a process crash in the middle may lose intermediate progress. Its "sync" mode writes each checkpoint before the next step starts, and an asynchronous mode sits between. Its in-memory saver is useful for learning but loses everything on restart. Whatever tool you use, find out what survives a killed process.
An action and the record of it are two writes to two systems. A crash can fall between them. Give every external action a stable key derived from the task and step, let the receiving service ignore repeats, and when it cannot, look up the outcome before retrying.
Resume and crash recovery
- Find runs that are not finished and have no live worker.
- Take ownership with an expiring claim so only one worker resumes each.
- Load the latest checkpoint and check its version.
- Reconcile actions that were started but not confirmed.
- Re-check permissions and facts that may have changed.
- Continue, counting the attempt against a limit.
A run that crashes every time at the same step will otherwise loop forever. After a few attempts, park it with its error for a person.
Effects and their evidence
For each external action, store three things: the intent before calling, the key sent with the call and the confirmed result afterward. On resume, an intent without a result means "unknown", not "not done". Query the target by key, then record what you find. If the target offers no way to ask and no duplicate protection, do not retry automatically; route the case to a person with the details needed to check by hand. State this limitation in the design so that nobody assumes more safety than exists. See Reliable Tool Execution and Error Recovery.
Approval nodes and interruptible workflows
An approval pause saves state, releases the worker and waits for an event. The approval must be bound to the exact proposal, come from an authorized person, expire and be recorded. On resume, check that the proposal is unchanged and the facts still hold. LangGraph offers interrupts for this, and its documentation explains that a resumed node runs again from its start, so code before the pause must be safe to repeat. Check the equivalent rule in your tool. See Human-in-the-Loop and Approval Gates.
Build a long-running agent with checkpoints
This template researches an item, proposes a purchase, waits for approval and creates an order key. It uses SQLite so you can see each part.
"""Template: a long-running task with checkpoints and an approval pause."""
import json
import sqlite3
def research(s):
return {"findings": f"3 offers for {s['item']}"}
def propose(s):
return {"proposal": {"item": s["item"], "price": 480}}
def order(s):
return {"order_id": f"{s['task']}:order"} # stable operation key
STEPS = [("research", research, False), ("propose", propose, False),
("order", order, True)] # True: needs approval
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE checkpoint(task TEXT, seq INT, state TEXT,"
" PRIMARY KEY(task, seq))")
def latest(task):
row = db.execute("SELECT seq, state FROM checkpoint WHERE task=? "
"ORDER BY seq DESC LIMIT 1", (task,)).fetchone()
return (row[0], json.loads(row[1])) if row else (0, None)
def save(task, seq, state):
with db: # duplicate seq raises
db.execute("INSERT INTO checkpoint VALUES (?,?,?)",
(task, seq, json.dumps(state)))
def start(task, item):
save(task, 1, {"task": task, "item": item, "done": 0,
"approved": None, "status": "ready"})
def resume(task):
seq, s = latest(task)
while s["done"] < len(STEPS):
name, action, gated = STEPS[s["done"]]
if gated and s["approved"] != s["proposal"]:
s["status"] = f"waiting for approval of {name}"
save(task, seq + 1, s)
return s["status"]
s.update(action(s), done=s["done"] + 1, status=f"after {name}")
seq += 1
save(task, seq, s)
return f"finished: {s['order_id']}"
def approve(task):
seq, s = latest(task)
s["approved"] = s["proposal"]
save(task, seq + 1, s)
start("t1", "laptop")
print(resume("t1"))
print(resume("t1")) # asking again does not skip the gate
approve("t1")
print(resume("t1"))
print("checkpoints kept:", latest("t1")[0])
Output:
waiting for approval of order
waiting for approval of order
finished: t1:order
checkpoints kept: 7
Asking to resume twice does not bypass the gate, and after approval only the remaining step runs. The primary key stops two workers from both saving the same sequence number. This is a teaching skeleton with clear gaps:
- It uses an in-memory database, so use a file or server database to survive restarts.
- The approval function does not check who is approving, record a reason or expire.
- Repeating resume while waiting adds another checkpoint; skip unchanged saves.
- The order step only returns a key. A real call must send it to the supplier system and confirm the result.
- A duplicate save raises an error that the caller must handle, ideally before doing work, by claiming the task.
A template you can copy
| Part | Fill in |
|---|---|
| Task | Identifier, owner, definition version |
| Steps | Name, inputs, outputs, effect, retry rule |
| Gates | Which step, who approves, expiry |
| Limits | Steps, attempts, time, spend |
| Operation keys | How each is derived and how duplicates are refused |
| Recovery | Claim, reconcile, resume, park |
| Cancellation | Allowed states and compensation |
| Retention | What is kept, for how long, how deleted |
Cancellation and expiry
A durable run will not disappear on its own, so define how it ends early. Check for a cancel request before each step and before every external action. Decide what happens to work in progress, which completed effects to compensate and what the final status says. Give the run an overall expiry and each wait its own. When the user deletes their account or loses access, their pending runs should stop, not continue with rights that no longer exist.
Model calls in durable runs
Record each model response as a step result. On resume you then reuse the same decision instead of paying again and possibly receiving a different one. Keep the prompt version and model identifier with it. Streaming output to a user is separate from committing a result: mark partial text as provisional. Long conversations grow history and context, so summarize into new state at defined points, and use the engine's way of starting a fresh history if it has limits.
Code changes while runs wait
A run started last week may resume on today's code. Keep old paths until old runs finish, use the versioning mechanism your engine provides or route runs to workers of the matching version. Test new code against recorded histories before release, as shown in Workflow Versioning, Testing and Resilience.
What to monitor
| Signal | Why |
|---|---|
| Runs by state and age | Find stuck work |
| Resume attempts per run | Spot crash loops |
| Approvals waiting and expired | Capacity problems |
| Unconfirmed actions | Possible duplicates or losses |
| Checkpoint size and write failures | Cost and durability risk |
Give operators safe controls: inspect, pause, cancel, retry one step and mark an outcome after investigation, each recorded with who did it. Avoid editing stored state by hand.
Choosing a durability tool
| Question | Why ask |
|---|---|
| What exactly is persisted, and when? | Defines what a crash can lose |
| What reruns on resume? | Determines which code must be repeatable |
| How are timers and external events handled? | Needed for long waits |
| How is changed code handled? | Long runs meet new releases |
| What limits apply to history and payload size? | Long agents grow quickly |
| Who operates storage, backup and upgrades? | Durability depends on them |
| Can data be encrypted, exported and deleted? | Privacy and exit |
Answer with a small experiment as well as documentation: kill a process at awkward moments and read what was kept.
Prove it recovers
- Kill the worker before a step, during it and after the effect but before saving.
- Start two workers on one run.
- Restart the storage service.
- Approve after expiry and after the facts change.
- Deploy new code while a run waits.
- Restore from backup and check actions are not replayed blindly.
The final test is often forgotten. Restoring older state can make completed actions look pending, so reconcile with external systems after a restore.
An agent orders stock, then the server restarts before saving. On resume it orders again. The fix derives a key from the task and step, sends it with the order, and has recovery ask the supplier about that key first. A test now kills the process in exactly that gap.
Stored progress is stored data
Checkpoints and histories often contain user requests, retrieved documents, model replies and tool results, kept far longer than a normal request log. Apply access control, encryption and tenant separation to them. Set a retention period for finished runs, and confirm that a deletion request reaches histories, snapshots and backups according to your policy. Redact or replace sensitive fields with references before they are recorded, because removing them from an append-only history later may be difficult. Check what your tool's dashboard displays and who can open it.
Keeping long runs healthy
A run that lives for weeks collects history, context and assumptions. Refresh facts before relying on them, shorten context at planned points while keeping decisions and their sources, and start a new run that carries essential state when the old one becomes unwieldy. Link the two so support staff can follow the thread. Watch credentials too: tokens issued at the start will expire, so obtain short-lived ones when each action runs and check that the original authority still holds.
Common mistakes
- Believing a checkpoint prevents duplicate actions.
- Using an in-memory saver in production.
- Calling clocks or services inside replayed workflow code.
- Resuming one run with two workers.
- Approvals that never expire.
- Deploying changes without considering waiting runs.
- No way to park a run that keeps failing.
Checklist
- You know exactly what survives a killed process.
- Checkpoints carry versions and no secrets.
- External actions use stable keys and reconciliation.
- One worker owns a resumed run.
- Approvals are authorized, bound, expiring and recorded.
- Recovery attempts are limited.
- Crash and code-change tests pass.
Frequently asked questions
Does durable execution mean exactly once?
The engine can ensure its own recorded progress is consistent. Effects on other systems still need keys or checks that make repeats harmless.
Can I build it with a database alone?
For simple flows, yes. Timers, concurrency, retries, versioning and visibility grow quickly, which is what engines provide.
How long can a run wait?
That depends on your tool and your rules. Set a business expiry even when the platform allows much longer.
Should every agent be durable?
No. Add durability where lost or repeated work matters more than the added complexity.
References and further reading
Next steps
Event-Driven and Background Agents
Start runs from events.
Workflow Versioning, Testing and Resilience
Version, test and retry.
Stateful and Long-Running Agent Architecture
Design long-lived state.