Stateful and Long-Running Agent Architecture
Work that lasts hours or days must survive restarts, waiting, change and more than one worker.
A stateful agent keeps a durable record of its task outside the model and the process. A long-running agent adds queues, timers, pauses for events and recovery after failure. Save progress after meaningful steps, make effects safe to repeat, protect the record against competing writers, version the state and give people a way to see, pause and cancel work.
What you will learn: what to store, checkpoints and effects, a reference architecture, waiting and resuming, concurrency, upgrades, cancellation and operations.
Prerequisites: Distributed Systems, Networking and Databases and Single-Agent, Router and Retrieval Patterns.
Why state is needed
A model call keeps nothing for your application between requests unless something sends it again or a service stores it for you. A process can restart at any time. If an agent must wait for an approval, a delivery or a nightly job, the facts of the task need a home that outlives both.
| Kind of data | Example | Typical home |
|---|---|---|
| Task state | Steps done, pending action, status | Database or workflow engine |
| Conversation | Messages and summaries | Session store |
| Long-term memory | Stable preferences | Governed memory store |
| Artifacts | Files and reports | Object storage |
| Business records | Orders, tickets | The system of record |
| Audit | Who did what | Protected log |
Do not copy business records into task state and treat the copy as truth. Store identifiers and versions, and read the current record before acting.
Do you need long-running design?
Many tasks finish within one request. Adding queues and recovery to them costs effort without benefit. Use the table to decide.
| Situation | Reasonable design |
|---|---|
| Answer in seconds, no actions | Stateless request, conversation stored if wanted |
| Minutes of work, user may leave | Background job with saved status and notification |
| Actions that must not repeat | Durable record and idempotent operations |
| Waiting for people or events | Pause and resume with deadlines |
| Many steps over days with compensation | Consider a durable workflow engine |
A task record
- Task identifier, owner and tenant.
- Goal and constraints as accepted.
- Status and current step.
- Completed actions with external references.
- Pending question, approval or timer.
- Budgets used and remaining.
- Versions of state schema, workflow, instructions and tools.
- Record version for safe updates.
Explicit statuses
One step at a time
Structure a worker as a short cycle: load the record, check that the task may still run, decide the next step, carry it out, save the result and schedule what follows. Each cycle should be small enough to repeat safely. This shape gives you natural places to check budgets, cancellation and permissions. It also lets a new release take over between steps instead of in the middle of one.
Separate the decision from the action. First save what the agent intends to do, with its operation key and arguments; then execute it; then save the outcome. After a crash, an intent without an outcome tells the next worker to look up what happened before doing anything. Without the saved intent, a fresh model call may choose slightly different arguments and produce a second, different action.
Checkpoints and effects
A checkpoint saves progress so that work can resume. The difficult moment is a crash after an outside action but before the save. This example reproduces it.
"""Save progress after each step so a restart does not repeat actions."""
import json
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE task(id TEXT PRIMARY KEY, version INT, state TEXT)")
db.execute("INSERT INTO task VALUES ('t1', 0, '{\"done\": []}')")
effects = {} # the outside world, keyed for safety
def load(task):
version, state = db.execute(
"SELECT version, state FROM task WHERE id=?", (task,)).fetchone()
return version, json.loads(state)
def save(task, version, state):
with db:
changed = db.execute(
"UPDATE task SET version=?, state=? WHERE id=? AND version=?",
(version + 1, json.dumps(state), task, version)).rowcount
if not changed:
raise RuntimeError("someone else updated this task")
def work(task, crash_after=None):
version, state = load(task)
for step in ["reserve", "charge", "notify"]:
if step in state["done"]:
continue
key = f"{task}:{step}"
fresh = key not in effects
effects.setdefault(key, f"{step} completed")
print(f" {step}: {'performed' if fresh else 'already done'}")
if crash_after == step:
print(" process crashed before saving")
return
state["done"].append(step)
save(task, version, state)
version += 1
print("first run")
work("t1", crash_after="charge")
print("saved:", load("t1")[1]["done"])
print("second run")
work("t1")
print("saved:", load("t1")[1]["done"], "| effects:", len(effects))
try:
save("t1", 1, {"done": []})
except RuntimeError as error:
print("stale worker:", error)
Output:
first run
reserve: performed
charge: performed
process crashed before saving
saved: ['reserve']
second run
charge: already done
notify: performed
saved: ['reserve', 'charge', 'notify'] | effects: 3
stale worker: someone else updated this task
The charge happened but was not recorded. On the second run the stable key shows that it was already done, so there is no second charge. The version check then rejects a worker holding an old copy. Here a dictionary stands in for the outside service; in reality that service must support the key, or you must look up the result before repeating. Checkpoints alone do not give exactly-once effects.
Test every crash point
| Crash happens | Correct recovery |
|---|---|
| Before the intent is saved | Decide again; nothing happened |
| After intent, before the call | Look up, then perform with the same key |
| During the call | Outcome unknown; look up before repeating |
| After the call, before saving | Lookup or key shows it is done; record it |
| After saving, before acknowledging the message | Redelivery finds the step done and skips it |
Write one automated test for each row by raising an exception at that point. These tests are cheap compared with discovering the gap from a customer who was charged twice.
Three implementation approaches
| Approach | How it resumes | Mind |
|---|---|---|
| Your own tables and queue | Reads saved state and continues | You build timers, leases and recovery |
| Durable workflow engine | Rebuilds progress from recorded history | Workflow code has determinism and versioning rules |
| Agent framework checkpointer | Restores graph state | Check what re-runs; use a durable store in production |
Details differ in important ways. In LangGraph, for example, a node containing an interrupt runs again from its start when resumed, so side effects placed before the pause must be safe to repeat. Read the current documentation of whichever tool you use. Durable Execution, Checkpoints and Approvals compares the ideas.
Reference architecture
Waiting without holding resources
- Save the question or action and release the worker.
- Set a deadline and decide what happens when it passes.
- Match incoming events to a task by a protected correlation identifier.
- Verify the sender and ignore duplicates.
- On resume, check that facts and permissions are still valid.
Re-validation is essential. A price, stock level or user role can change while a task sleeps.
Events that arrive early, late or twice
A reply can arrive before the task has recorded that it is waiting, after the deadline passed or three times in a row. Store incoming events with their identifiers before processing them, so that none is lost while the task is busy. When a task starts waiting, check the stored events first. Ignore repeats by identifier. For a late event, follow a stated rule, such as reopening with confirmation or recording it and notifying the owner. Do not let event text choose which task or tenant it belongs to without verification.
More than one worker
Queues commonly deliver a message at least once, so two workers may pick up the same task. Use a lease with an expiry, check a record version on every save and let downstream systems reject stale writers where possible. Process events for one task in a controlled order. Parallelism, Deadlocks and Conflict Resolution goes further.
Upgrading saved state
A task started last week may resume under this week's program.
"""Upgrade old saved state when a newer program resumes it."""
def v1_to_v2(state):
"""'done' was a list of names; now each step records who approved it."""
state["done"] = [{"step": s, "approved_by": None} for s in state["done"]]
return state
def v2_to_v3(state):
"""Money moves from a float to whole cents."""
state["total_cents"] = round(state.pop("total") * 100)
return state
UPGRADES = {1: v1_to_v2, 2: v2_to_v3}
CURRENT = 3
def restore(saved):
state = {k: v for k, v in saved.items() if k != "schema"}
schema = saved["schema"]
if schema > CURRENT:
raise ValueError(f"state v{schema} is newer than this program")
while schema < CURRENT:
state = UPGRADES[schema](state)
schema += 1
return {"schema": schema, **state}
old = {"schema": 1, "done": ["quote", "reserve"], "total": 19.99}
print(restore(old))
print("original untouched:", old["total"], old["schema"])
try:
restore({"schema": 4})
except ValueError as error:
print("refused:", error)
Output:
{'schema': 3, 'done': [{'step': 'quote', 'approved_by': None}, {'step': 'reserve', 'approved_by': None}], 'total_cents': 1999}
original untouched: 19.99 1
refused: state v4 is newer than this program
Version one state is upgraded step by step, and a state from a newer program is refused rather than misread. The original saved value stays untouched because each upgrade assigns new fields on a copy; an upgrade that edits nested lists in place would need a deep copy. Alternatives to upgrading are finishing old tasks on old workers or canceling them with notice.
Versions beyond the schema
The data format is only one thing that changes during a long task. Instructions, models, tools, policies and business rules change as well. Decide for each whether a running task keeps the version it started with or moves to the newest. Security and permission rules should normally apply at once. Conversation style or step order may be safer to keep until the task ends. Record the versions used at every step, so that an unexpected result can be explained. Keep old tool contracts working until no unfinished task depends on them, and list those tasks before removing anything.
Pause, cancel and recover
| Request | Expected behavior |
|---|---|
| Pause | No new actions; state retained |
| Cancel | Stop, then undo or report completed effects |
| Retry a step | Safe repeat with the same operation key |
| Hand over | A person receives state, evidence and next options |
| Stop everything | An operator switch that workers check before acting |
Identity over time
The person who started a task may have left, changed role or lost access before it ends. Do not store a long-lived user credential in task state. Store who requested the work and obtain a fresh, narrow token when a step runs, then check current permission. Decide who inherits a waiting task when its owner is gone, and cancel it if nobody does. Approvals should expire and should apply only to the exact action shown. See Agent Identity, Authorization and Secrets.
Context over long tasks
History grows beyond what a model can use well. Keep facts and decisions in structured fields, summarize older exchanges, link to artifacts and re-read the current records. Summaries can lose or distort details, so keep originals according to policy and never rely on a summary for an amount or identifier. See Context Assembly, Retrieval, Compression and Caching.
Budgets across days
A task that wakes repeatedly can consume a great deal while each step looks modest. Keep running totals of model calls, tool calls, money spent and attempts in the task record, and check them before each step. Include a limit on how many times a task may be re-queued without progress. When a limit is reached, move the task to a state that a person reviews, with a summary of what was done. Raising a budget should be a recorded decision, not an automatic response.
Make progress visible
People trust background work when they can see it. Show the current status, completed steps in plain words, what the task is waiting for, who can unblock it and when it will give up. Notify on decisions needed and on completion, not on every internal step. Let an authorized person correct a wrong fact in the task record through a controlled action that is logged, so that staff never edit database rows by hand.
Operate it
- Show counts and age of tasks by status.
- Alert on stuck tasks, repeated attempts and growing queues.
- Set a maximum task lifetime.
- Test restarts by killing workers at each boundary.
- Back up state and rehearse restore, including reconciliation with outside systems.
- Delete finished data on schedule.
The task waits days for documents. A worker saves the request and stops. When files arrive, a verified event queues the next step, the agent checks them, and an approver is asked. If the supplier's details changed meanwhile, the approval request is rebuilt. A restart during any wait loses nothing.
Plan for the backlog
After an outage, thousands of tasks may wake together. Limit how many run at once, give urgent work priority and add random delay to retries. Check that model and tool rate limits can absorb the recovery, and expire work that is no longer useful. Keep one tenant's backlog from delaying everyone else, for example with separate queues or fair scheduling. Measure the oldest waiting task as well as the queue length, because a short queue can still contain something forgotten. See Latency, Load Testing and Capacity Planning.
Restore without repeating the past
Restoring task state from a backup moves your records back in time, while payments, messages and bookings already made stay made. Before workers restart, compare restored tasks with the systems of record for the missing period, using operation keys and references. Hold actions until that check is done, and mark tasks that cannot be reconciled for a person. Rehearse this once with test data, because it is hard to design during an incident. Also decide how long keys are remembered downstream: if a provider forgets them sooner than your longest restore window, a lookup must replace reliance on the key. Write the finding into the recovery plan with an owner.
Start small: one durable record, explicit statuses, saved intents and a version check will carry many agents a long way before any new infrastructure is needed.
Common mistakes
- Keeping task state in process memory or only in chat history.
- Saving only at the end.
- Assuming resume skips completed side effects.
- Waiting with a sleeping process.
- Allowing silent overwrites by concurrent workers.
- Deploying changes without a plan for unfinished tasks.
- No way to cancel.
Checklist
- State is durable, structured and owned.
- Effects use stable keys or lookups.
- Saves check a version.
- Every waiting status has a deadline.
- Events are verified and deduplicated.
- Facts and permissions are rechecked on resume.
- State upgrades are tested.
- People can see, pause and cancel work.
Frequently asked questions
Is chat history enough state?
No. It is hard to query, can be shortened and does not reliably show whether an action happened. Keep explicit task fields.
When should I adopt a workflow engine?
When timers, retries, long waits and recovery start to dominate your own code, and the team can operate the engine.
How often should I checkpoint?
After each step whose repetition would be costly or harmful, and always before waiting.
What happens to running tasks during a release?
Either they remain compatible, are upgraded, finish on old workers or are canceled with notice. Decide before deploying.
References and further reading
Next steps
Human-in-the-Loop and Approval Gates
Pause for people safely.
Event-Driven and Background Agents
Start work from events.
Graphs, State Machines, Parallelism and Sagas
Model states explicitly.