The Agent That Started Over
An agent was running a complex codebase analysis task. Fifty files. Cross-file dependency mapping. Security vulnerability identification. Estimated runtime: 12 minutes.
At minute 9, the process died. Memory limit exceeded.
The agent had no checkpoint. It restarted from file 1.
But it had already written intermediate results to a shared database - partial dependency maps, preliminary vulnerability flags. The restart overwrote some of them incorrectly. When it finally completed on the third attempt (another memory spike at minute 11 killed the second run too), the output contained contradictions: vulnerabilities flagged in the first run that were cleared in the third, dependencies mapped differently across restarts.
Nobody knew which version was correct. Three attempts. Three different outputs. One database. Zero confidence in any of it.
The agent wasn't poorly designed. The task was reasonable. The failure was one missing layer: state management. No checkpointing, no restart-from-midpoint, no idempotency on writes. Every run was a fresh start with side effects from previous runs still in the database.
A stateless agent in a stateful world produces stateful damage.
grid-rows: 1
grid-gap: 14
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
r1: "Run 1\nfiles 1-9, writes results\ndies at minute 9" {class: red}
r2: "Run 2\nstarts at file 1, overwrites\ndies at minute 11" {class: red}
r3: "Run 3\nstarts at file 1 again\nfinishes" {class: yellow}
r1 -> r2 -> r3
All three runs wrote to the same database, and none of them knew what the others had written. The final state is a mix of three runs.
This is Part 7 of the Harness Engineering series. Part 1 introduced the seven-layer Harness Architecture. This article covers Layer 7 - State Management - including checkpoint-resume strategies, cross-session memory, and durable state for long-running agents.
This series grew into a book: Harness Engineering for Production AI Systems. Chapter 12, "State, Checkpoints, Resume," covers this layer.
17 November 2026: corrected the guarantee: the checkpoint pattern gives at-least-once execution, and only a key written before the side effect makes the effect happen once. Fixed a resume path that crashed on reload, tied checkpoint expiry to task state, and added a section on why a checkpoint is not durable execution. Also mapped the memory tiers to Part 3 and gave every tier its own diagram.
Why State Management Is a Distinct Layer
For simple LLM applications, state is trivial. Request comes in, response goes out, nothing persists between them except what you explicitly store.
For agentic systems, state is the engineering problem. Agents run for minutes or hours. They execute sequences of actions. They accumulate intermediate results. They call tools that have side effects. They may be interrupted, resumed, or run across multiple user sessions.
Without explicit state management, you have three compounding problems:
Resume fragility. If the agent process dies, it restarts from scratch. All computation performed before the failure is lost. For a 12-minute task, that's 12 minutes of wasted compute on every failure. At production scale, with many long-running tasks, this cost is material.
Idempotency failure. If the agent retries a step that already had side effects, those effects are duplicated. Database writes happen twice. API calls fire twice. Emails send twice. Without idempotency guarantees, retry-on-failure corrupts state rather than recovering it.
Context discontinuity. When a user resumes a task in a new session, the agent starts without memory of what was done in previous sessions. It re-asks questions already answered. It re-does work already completed. The user's patience degrades with every fresh start.
State management solves all three. Checkpoints enable resume-from-failure. Idempotency keys prevent duplicate side effects. Persistent memory enables cross-session continuity.
grid-rows: 2
grid-columns: 3
grid-gap: 12
classes: {
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
p1: "Resume fragility\nrestart from step 1" {class: red}
p2: "Idempotency failure\neffects happen twice" {class: red}
p3: "Context discontinuity\nnew session starts blind" {class: red}
s1: "Checkpoints" {class: green}
s2: "Idempotency keys" {class: green}
s3: "Persistent memory" {class: green}
Each problem has its own fix, and none of the fixes covers another column. A checkpoint without idempotency keys resumes cleanly and still double-writes.
Together these three guarantees form what I call the Stateful Execution Contract: a task resumed after an interruption keeps the work it already recorded, and repeats no side effect that carried a durable key, however many times it is interrupted. That contract is what separates a production agentic system from a fragile script that happens to use an LLM. It covers the run's past, not its next step - checkpoint a hand-rolled loop and you still have a runtime whose guarantees were never specified, because durable history does nothing to narrow what the agent may do next.
The Three State Tiers
State in agentic systems exists at three levels, each with different persistence requirements and access patterns.
Tier 1: Task State (Checkpoint-Resume)
Task state is the record of what has been done within a single task execution. Which steps have completed. What their outputs were. What still needs to happen.
Checkpoints serialize this state to durable storage at meaningful boundaries - after each tool call, after each reasoning step, after each file processed. If the process dies, it resumes from the last checkpoint rather than from step 1.
from dataclasses import dataclass, field, asdictfrom datetime import datetime, timezonefrom typing import Anyimport jsonimport uuiddef now() -> str: return datetime.now(timezone.utc).isoformat()@dataclassclass StepResult: step_id: str step_type: str input: dict output: Any # must be JSON-serializable completed_at: str idempotency_key: str@dataclassclass TaskCheckpoint: task_id: str created_at: str last_updated: str total_steps: int completed_steps: list[StepResult] = field(default_factory=list) current_step_index: int = 0 pending_key: str | None = None # written BEFORE a side effect runs task_output: Any = None status: str = "in_progress" # in_progress | completed | failed def is_complete(self) -> bool: return self.status == "completed" def step_already_completed(self, idempotency_key: str) -> StepResult | None: for step in self.completed_steps: if step.idempotency_key == idempotency_key: return step return None @classmethod def from_json(cls, data: str) -> "TaskCheckpoint": raw = json.loads(data) # Rebuild nested dataclasses: json.loads returns plain dicts raw["completed_steps"] = [StepResult(**s) for s in raw["completed_steps"]] return cls(**raw)class CheckpointManager: def __init__(self, store): self.store = store # Redis, Postgres, or any durable KV store def create(self, task_id: str, total_steps: int) -> TaskCheckpoint: checkpoint = TaskCheckpoint(task_id=task_id, created_at=now(), last_updated=now(), total_steps=total_steps) self._save(checkpoint) return checkpoint def load(self, task_id: str) -> TaskCheckpoint | None: data = self.store.get(f"checkpoint:{task_id}") return TaskCheckpoint.from_json(data) if data else None def record_intent(self, checkpoint: TaskCheckpoint, idempotency_key: str): checkpoint.pending_key = idempotency_key self._save(checkpoint) def record_step(self, checkpoint: TaskCheckpoint, step: StepResult): checkpoint.completed_steps.append(step) checkpoint.current_step_index += 1 checkpoint.pending_key = None self._save(checkpoint) def complete(self, checkpoint: TaskCheckpoint, output: Any): checkpoint.task_output = output checkpoint.status = "completed" self._save(checkpoint) def _save(self, checkpoint: TaskCheckpoint): checkpoint.last_updated = now() # Never expire a task that may still resume (it could be waiting on # an approval for days); keep finished ones long enough to audit. ttl = None if checkpoint.status == "in_progress" else 86400 * 30 self.store.set(f"checkpoint:{checkpoint.task_id}", json.dumps(asdict(checkpoint)), ex=ttl)The idempotency key on each step is what makes a retry safe, but only under two conditions. The key must be durable before the side effect runs, and the system the step writes to must honour it. A key recorded after the call can only tell you, on resume, that a step finished. It can't tell you whether a step that was in flight when the process died already sent its email. So the loop writes an intent record (pending_key) first, then passes the same key to the executor, which forwards it to the downstream API (Stripe-style idempotent requests, a unique constraint on a database row, a conditional write).
async def execute_with_checkpoint( task_id: str, steps: list[dict], checkpoint_manager: CheckpointManager, executor,) -> Any: checkpoint = checkpoint_manager.load(task_id) if checkpoint and checkpoint.is_complete(): return checkpoint.task_output if not checkpoint: checkpoint = checkpoint_manager.create(task_id, len(steps)) for i, step in enumerate(steps[checkpoint.current_step_index:], start=checkpoint.current_step_index): idempotency_key = f"{task_id}:{step['type']}:{i}" if checkpoint.step_already_completed(idempotency_key): continue # Write-ahead: the key is durable before the side effect runs, and the # executor passes it to the system it writes to, which dedupes on it. checkpoint_manager.record_intent(checkpoint, idempotency_key) output = await executor.run(step, idempotency_key=idempotency_key) checkpoint_manager.record_step(checkpoint, StepResult( step_id=str(uuid.uuid4()), step_type=step["type"], input=step, output=output, completed_at=now(), idempotency_key=idempotency_key, )) final_output = [s.output for s in checkpoint.completed_steps] checkpoint_manager.complete(checkpoint, final_output) return final_outputHere is the window this closes, in a run with a fake store and a downstream system that honours keys. The process is killed after step 2's side effect but before its checkpoint is written, then the task is run again:
crashed: process died after the effect, before the checkpointafter crash: completed 1 pending t1:write:1 ttl Noneresumed output: ['done:scan', 'done:write', 'done:report']effects applied: 3 for 3 stepsStep 2 ran twice and its effect landed once, because the second attempt carried the same key. That is the honest guarantee: at-least-once execution, effects applied at most once per key. It is also what LangGraph's own fault-tolerance docs say about node retries: they give "at-least-once semantics", and a key must be "already durable before the side effect runs". Two other details from the earlier version of this code are fixed here. Reloading a checkpoint now rebuilds StepResult objects instead of leaving plain dicts, which made the resume path crash. And an in-progress checkpoint never expires, because a task paused on an approval can legitimately wait for days.
Resuming is not the same as starting fresh. A resumed run restores what the agent read before the pause, so anything that could have changed since needs to be read again before an action depends on it. That's why an approval is a checkpoint resume that restores stale observations, and why the approval gate in Part 4 re-checks its preview on resume. That same checkpoint layer is what higher-level agents quietly lean on when they assume an action is reversible - a workload-placement agent's ability to undo a move is borrowed from the checkpoint beneath it, not a property it owns.
direction: down
classes: {
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
intent: "1. Save intent: pending_key = task:step:i" {class: violet}
effect: "2. Run the step, passing the key\ndownstream dedupes on it" {class: yellow}
record: "3. Save result, clear pending_key" {class: green}
next: "4. Next step" {class: blue}
intent -> effect: "a crash here: nothing happened"
effect -> record: "a crash here: re-run, same key"
record -> next
The label on each arrow is what a crash at that point costs. Before the intent record there is no window at all. Between the effect and the result is the one window left, and the key is what makes re-running it harmless.
Without Tier 1: every process failure wastes all prior compute and risks corrupting shared state with duplicate writes. The codebase analysis incident is the exact consequence.
Tier 2: Session State (Cross-Session Memory)
Session state persists across the boundary between separate user interactions with the same agent. When a user returns to continue a task, the agent should know what happened in previous sessions.
This is distinct from task state (which tracks steps within a single execution) and from context engineering (which manages what's in the current context window). Session state is the bridge between sessions.
@dataclassclass SessionSummary: session_id: str task_description: str decisions_made: list[str] work_completed: list[str] open_questions: list[str] next_recommended_steps: list[str] created_at: strclass SessionMemory: def __init__(self, vector_store, kv_store): self.vector_store = vector_store # For semantic recall self.kv_store = kv_store # For direct lookup def save_session(self, user_id: str, summary: SessionSummary): # Store in vector store for semantic recall self.vector_store.add( id=summary.session_id, content=self._to_text(summary), metadata={ "user_id": user_id, "session_id": summary.session_id, "created_at": summary.created_at, } ) # Store structured data for direct lookup self.kv_store.set( f"session:{user_id}:{summary.session_id}", json.dumps(asdict(summary)) ) def recall_relevant( self, user_id: str, current_query: str, top_k: int = 3 ) -> list[SessionSummary]: results = self.vector_store.similarity_search( query=current_query, filter={"user_id": user_id}, k=top_k ) return [SessionSummary(**json.loads( self.kv_store.get(f"session:{user_id}:{r.metadata['session_id']}") )) for r in results] def build_continuation_context( self, user_id: str, current_query: str ) -> str: relevant = self.recall_relevant(user_id, current_query) if not relevant: return "" lines = ["[Prior session context]"] for s in relevant: lines.append(f"\nSession: {s.task_description}") if s.decisions_made: lines.append(f"Decisions made: {'; '.join(s.decisions_made)}") if s.work_completed: lines.append(f"Work completed: {'; '.join(s.work_completed)}") if s.open_questions: lines.append(f"Open questions: {'; '.join(s.open_questions)}") return "\n".join(lines) def _to_text(self, summary: SessionSummary) -> str: return ( f"Task: {summary.task_description}. " f"Completed: {', '.join(summary.work_completed)}. " f"Decided: {', '.join(summary.decisions_made)}." )The session summary is generated at the end of each session by asking the model to distill what happened into a structured format. This compressed representation is what gets injected at the start of the next session - not the raw conversation history, which would be too long and too noisy.
Two cautions. A summary written at session end doesn't exist if the session dies first, so for long sessions, write it incrementally or at milestones. And the save is itself a side effect: keyed on session_id, as above, a retried save overwrites rather than duplicates, provided the vector store upserts by id.
In Part 3's terms, this tier is episodic memory, and the next one is semantic memory. In LangGraph's terms, Tier 1 is the per-thread checkpointer and Tiers 2 and 3 live in the store.
direction: down
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
}
end: "Session ends: model writes a SessionSummary" {class: blue}
stores: "" {
grid-rows: 1
grid-gap: 14
vec: "Vector store\nfor semantic recall" {class: violet}
kv: "KV store\nsession:user:id" {class: violet}
}
next: "Next session: recall top 3,\ninject as prior context" {class: teal}
end -> stores
stores -> next
The summary is written twice on purpose. The vector store finds which past sessions are relevant, and the KV store returns them intact, so recall is fuzzy but the content injected is exact.
Without Tier 2: every new session starts blind. The agent re-asks questions already answered. The user re-explains context already given. The work already done has to be rediscovered.
Tier 3: User State (Long-Term Preferences)
User state captures standing facts about the user that persist indefinitely and inform agent behavior across all sessions and tasks.
class UserStateStore: def __init__(self, kv_store): self.store = kv_store # One hash per user: reading all facts is one call, not a keyspace scan # (Redis KEYS is O(N) over every key and can stall a large database) def set(self, user_id: str, key: str, value: str): self.store.hset(f"user:{user_id}", key, value) def get(self, user_id: str, key: str) -> str | None: return self.store.hget(f"user:{user_id}", key) def get_all(self, user_id: str) -> dict: return self.store.hgetall(f"user:{user_id}") def build_user_context(self, user_id: str) -> str: facts = self.get_all(user_id) if not facts: return "" lines = ["[User preferences and context]"] for k, v in facts.items(): lines.append(f"- {k}: {v}") return "\n".join(lines)Examples of user state: preferred programming language, coding style preferences, project tech stack, timezone, communication preferences, standing access permissions. These facts don't change session to session and shouldn't need to be re-established every time.
Without Tier 3: every session starts with a stranger. The agent that helped you yesterday knows nothing about you today.
Standing facts go stale too: a project changes its stack, a user changes teams. Store when each fact was set, and treat old ones as claims to confirm rather than truths to act on.
grid-rows: 1
grid-gap: 14
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
t1: "Tier 1: task\none run, until it completes" {class: yellow}
t2: "Tier 2: session\nacross sessions, by relevance" {class: violet}
t3: "Tier 3: user\nindefinitely, until changed" {class: blue}
Each tier lives longer than the one to its left, and changes less often. That is why each needs its own store and its own expiry rule.
The Stateful Execution Contract in Practice
I call the combination of checkpointing + idempotency the Stateful Execution Contract: the guarantee that an interrupted task keeps the work it recorded and repeats no keyed side effect, however many times it is resumed.
The contract has three terms, and each one says exactly as much as the code can deliver:
Progress is durable. Every completed step is recorded before the next step begins. An interruption costs at most the step that was in flight.
Side effects are applied at most once per key. A step can run more than once - that's what at-least-once means - but its effect lands once, provided its key was durable before the call and the downstream system honours the key. The in-flight step after a crash is the one window left, and the restore line is where that window is examined in detail.
Recorded results are reused, not recomputed. A resumed task returns the recorded output for every step that finished. A step that re-runs - an LLM call, say - may produce something different the second time, so determinism holds only for what the checkpoint already holds.
grid-rows: 1
grid-gap: 14
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
p: "Progress is durable\nlose at most one step" {class: green}
e: "Effects once per key\nif the key is durable\nand honoured downstream" {class: violet}
r: "Recorded results reused\nre-run steps may differ" {class: blue}
Each box carries its own condition. Drop the condition and the term becomes a promise the code doesn't keep.
Without the Stateful Execution Contract, you do not have an agentic system. You have a script that breaks under any fault.
A Checkpoint Is Not Durable Execution
Everything above preserves a run's data. None of it restarts a run whose process died. The opening incident needed both: the agent died at minute 9, and something had to notice and start it again. In the code above, that something doesn't exist. execute_with_checkpoint resumes correctly when it's called again, but nothing calls it.
Whether a checkpointing framework counts as durable execution is genuinely contested. Temporal, which sells a durable-execution engine, says plainly: "LangGraph checkpoints state, but checkpoints are not durable execution," and "The checkpoint preserves your data, not your execution." LangChain counters that durability is what its Agent Server provides on top of the checkpointer: runs sit on a managed task queue, and when a worker crashes another picks the run up from its latest checkpoint. Both are vendor framings. The useful question for your system is concrete: when the process dies, what restarts the run, and how soon? A job queue that re-delivers unfinished tasks, a supervisor that re-invokes by task_id, a managed agent server, or a durable-execution engine like Temporal all answer it. A checkpoint on its own doesn't.
If you're on LangGraph, the pieces map directly onto this article. The checkpointer is Tier 1, keyed by thread_id. The durability argument ("exit", "async" or "sync") controls when each step's checkpoint is written. On resume, a node that hadn't finished runs again from its start, so the write-ahead key rule applies to every node with a side effect. A minimal version, checked against langgraph 1.2.22:
from typing import TypedDictfrom langgraph.checkpoint.memory import InMemorySaver # PostgresSaver in productionfrom langgraph.graph import END, START, StateGraphclass S(TypedDict): n: intdef step(s: S) -> dict: return {"n": s["n"] + 1}builder = StateGraph(S)builder.add_node("step", step)builder.add_edge(START, "step")builder.add_edge("step", END)graph = builder.compile(checkpointer=InMemorySaver())config = {"configurable": {"thread_id": "task-42"}} # stable id = resumable rungraph.invoke({"n": 0}, config, durability="sync") # checkpoint before continuingprint(graph.get_state(config).values){'n': 1}grid-rows: 1
grid-gap: 16
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
cp: "A checkpoint gives you" {
label.near: top-center
grid-columns: 1
grid-gap: 8
a: "what finished" {class: green}
b: "what it returned" {class: green}
c: "which key is in flight" {class: green}
}
de: "You still need something that" {
label.near: top-center
grid-columns: 1
grid-gap: 8
d: "notices the process died" {class: red}
e: "starts the run again" {class: red}
f: "does it before anyone waits" {class: red}
}
The left column is data, and this article builds it. The right column is execution: a queue, a supervisor or an engine. Without it, a perfect checkpoint just waits for someone to remember the task.
The Full State Management Flow
The three tiers operate across two distinct axes: within a single task execution (Tier 1), and across session boundaries (Tiers 2 and 3). This diagram shows how they interact across both.
grid-rows: 7
grid-columns: 2
vertical-gap: 34
horizontal-gap: 120
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
start: "1. Session start: inject user state\nand recall session memory" {class: violet}
n0: "" {style.opacity: 0}
load: "2. Load checkpoint, or create one" {class: blue}
n1: "" {style.opacity: 0}
done: "3. Step already recorded?" {class: violet}
reuse: "Yes: reuse its output" {class: teal}
intent: "4. No: save intent key" {class: yellow}
n3: "" {style.opacity: 0}
run: "5. Run the step with the key" {class: yellow}
n4: "" {style.opacity: 0}
rec: "6. Record result; more steps?" {class: green}
loop: "Yes: back to 3" {class: teal}
end: "7. Done: save session summary,\nupdate user state" {class: violet}
n6: "" {style.opacity: 0}
start -> load -> done
done -> reuse
done -> intent -> run -> rec
rec -> loop
rec -> end: "no"
Three structural decisions this diagram makes explicit. First, state flows in a full loop - injected at session start, updated at session end, recalled at the next session start. Second, the inner loop saves an intent key before every side effect, so a process failure inside it costs at most the in-flight step, and that step re-runs under the same key. Third, session memory and user state update at session end, not during task execution. They capture the settled outcome, not intermediate state, which keeps the recall signal clean and deliberate.
What Observability Looks Like for This Layer
Checkpoint resume rate - what fraction of task executions resume from a checkpoint rather than starting fresh? This tells you how often your agents are being interrupted mid-task. A high resume rate signals infrastructure instability (processes dying frequently) or task timeouts (tasks running longer than expected).
Replay-skip rate - what fraction of steps are skipped on resume because a recorded result already exists? It rises with process restarts, and it shows the checkpoint doing its job.
Duplicate-effect count - how often does the downstream system report a repeated idempotency key? Each one is a step that re-ran inside the crash window and was deduplicated. A duplicate that wasn't caught - two refunds, two emails - means some side effect is running without a key.
Session memory recall precision - when session memory is injected at session start, does it improve task completion time or quality? Measure by comparing sessions with and without relevant prior context. If recall doesn't help, your session summaries need to be more structured.
Checkpoint storage growth - how much storage is checkpointing consuming over time? Set expiry policies by state, not by age alone. A completed task's checkpoint can expire once your debugging and audit windows pass. An in-progress one must not: it may be waiting days on an approval, and it holds the idempotency record that protects its late retries. Framework stores have their own tools for this, such as prune on LangGraph's Postgres checkpointer and TTL support on its store.
grid-rows: 2
grid-columns: 4
grid-gap: 12
classes: {
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
a: "Process health" {class: violet}
b: "Checkpoint" {class: violet}
c: "Idempotency" {class: violet}
d: "Memory" {class: violet}
m1: "Resume rate" {class: grey}
m2: "Replay-skip rate,\nstorage growth" {class: grey}
m3: "Duplicate-effect count" {class: grey}
m4: "Recall precision" {class: grey}
The third column is the one that catches a missing key. The others can all look healthy while an unkeyed refund runs twice.
What to Build First
First: Idempotency keys on all write operations, written before the call. Before anything else, make every step that writes to external systems idempotent, with a key that is durable before the side effect runs and that the downstream system honours. This is the minimum viable protection against duplicate side effects from retries.
Second: Checkpoint-resume for tasks over 60 seconds. Any task that runs longer than 60 seconds should checkpoint. Implement the checkpoint manager and wire it into your agent execution loop.
Third: Session summaries. At the end of each session, prompt the model to generate a structured summary: decisions made, work completed, open questions, next steps. Store it.
Fourth: Session memory injection. At the start of each session, retrieve relevant prior session summaries using semantic search. Inject them into the system context.
Fifth: User state store. Capture standing user preferences and project context, with timestamps. Inject at session start.
Sixth: Something that restarts dead runs. A queue, a supervisor or a durable-execution engine. Without it, every checkpoint above waits for a person to notice.
grid-columns: 1
grid-gap: 8
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
s1: "1. Write-ahead idempotency keys" {class: green}
s2: "2. Checkpoint-resume (tasks > 60s)" {class: green}
s3: "3. Session summaries" {class: violet}
s4: "4. Session memory injection" {class: violet}
s5: "5. User state store" {class: violet}
s6: "6. A restarter: queue, supervisor, engine" {class: blue}
The green steps protect the outside world from your retries. The violet steps protect the user from repeating themselves. The blue step is what makes the green ones run without a person in the loop.
The Principle
Long-running agents operate in a world where things fail. Processes die. Network calls time out. Infrastructure has incidents. These are not exceptional events - at production scale they are routine.
The question is not whether your agent will be interrupted. It's whether you designed it to resume.
Checkpoint-resume, idempotency, and session memory are not optional features for agentic systems. They are the baseline that separates a production agent from a fragile script.
An agent that starts over is not an agent. It's an expensive coin flip.
What's Next in This Series
- Part 1: Harness Engineering - The Missing Layer - The full seven-layer Harness Architecture overview
- Part 2: Normalization and Input Defense - Prompt injection, input sanitization, and multi-surface consistency
- Part 3: Context Engineering - Memory architectures, retrieval strategies, and context compression
- Part 4: Gated Execution - Policy engines, human-in-the-loop design, and dry-run patterns
- Part 5: Validation Layer Design - Schema validators, semantic checks, and repair prompt patterns
- Part 6: Retry, Fallback, and Circuit Breaking - Building resilient LLM infrastructure that survives outages
- Part 8: Deterministic Constraint Systems - Building tool registries and action manifests that prevent hallucinated actions in agentic systems
Going deeper: Chapter 12 of the book
This is Part 7 of the Harness Engineering series, which grew into Harness Engineering for Production AI Systems. This layer became Chapter 12, "State, Checkpoints, Resume," which measures what four combinations of checkpointer and durability setting record for the same three nested counter increments, and only one of them gets it right. It also covers durability per run mode, and how Temporal's programming model compares with a few hundred lines of harness code.
The code for that chapter is the ch12-state-checkpoints-resume tag of the companion repository.
For a chapter-length treatment on this blog, including where it departs from the book, see LangGraph Interrupt Resume: Approvals Run on Stale Facts, Part 12 of the chapter-by-chapter guide to the book.
References
-
Kleppmann, M. (2017). Designing Data-Intensive Applications. O'Reilly Media.
-
Gray, J., & Reuter, A. (1992). Transaction Processing: Concepts and Techniques. Morgan Kaufmann.
-
Park, J. S., O'Brien, J. C., Cai, C. J., et al. (2023). Generative Agents: Interactive Simulacra of Human Behavior. ACM UIST 2023. https://arxiv.org/abs/2304.03442
-
Zhong, W., Guo, L., Gao, Q., et al. (2024). MemoryBank: Enhancing Large Language Models with Long-Term Memory. AAAI 2024. https://arxiv.org/abs/2305.10250
-
LangGraph. Persistence. https://docs.langchain.com/oss/python/langgraph/persistence and Fault tolerance (at-least-once node execution). https://docs.langchain.com/oss/python/langgraph/fault-tolerance
-
Anthropic. (2024). Building effective agents. https://www.anthropic.com/research/building-effective-agents (background)
-
Richardson, C. (2018). Microservices Patterns. Manning Publications.
-
Kumar, R. (2026). Harness Engineering for Production AI Systems. Chapter 12, "State, Checkpoints, Resume." https://harness.ranjankumar.in/
-
Temporal. (2026). Temporal LangGraph plugin: durable execution. https://temporal.io/blog/temporal-langgraph-plugin-durable-execution
-
Stripe. Idempotent requests. https://docs.stripe.com/api/idempotent_requests
-
LangChain. (2026). The runtime behind production Deep Agents. https://www.langchain.com/blog/runtime-behind-production-deep-agents
Related Articles
- Context Engineering: What the Model Sees Is What the Model Does
- Deterministic Constraint Systems: Building Tool Registries That Keep Agents in Scope
- Normalization and Input Defense: Hardening the Entry Point of Your LLM System
- Harness Engineering: The Missing Layer Between LLMs and Production Systems






