Graphs, State Machines, Parallelism and Sagas
Draw the allowed paths, then make the runtime refuse everything else.
A workflow graph connects steps with edges, including branches and loops. A state machine names the states a task can be in and the events allowed in each. Use them to bound what an agent may do next. Run independent steps in parallel with limits and deadlines, merge with explicit rules, and for actions across several systems record how to compensate, knowing that some effects cannot be undone.
What you will learn: graph and state-machine design, conditional and dynamic routing, fan-out and fan-in, compensation and sagas, and graphs for several agents.
Prerequisites: Orchestration vs Automation vs Frameworks and basic Python.
Graph workflows
A graph has nodes that do work and edges that say what may follow. Shared state flows through it. Unlike a simple pipeline, a graph can branch, join and loop.
| Element | Design question |
|---|---|
| Node | What does it read, write and call? |
| Edge | Under what condition is it taken? |
| State | Which fields exist and who may change them? |
| Entry and exit | How does a run start and finish, successfully or not? |
| Limits | How many visits, how long, how much spend? |
LangGraph is one widely used library built around state, nodes and edges. The same ideas can be written by hand.
State machines
A state machine is stricter about names. A task is in exactly one state, and only listed events move it. Anything else is refused.
"""A state machine that rejects moves nobody designed."""
MOVES = {
("new", "start"): "researching",
("researching", "draft_ready"): "reviewing",
("reviewing", "changes"): "researching",
("reviewing", "approve"): "publishing",
("publishing", "published"): "done",
}
CANCELLABLE = {"new", "researching", "reviewing"}
class Job:
def __init__(self, max_revisions=2):
self.state, self.revisions = "new", 0
self.max_revisions, self.history = max_revisions, []
def send(self, event):
if event == "cancel" and self.state in CANCELLABLE:
target = "canceled"
else:
target = MOVES.get((self.state, event))
if target is None:
return f"refused '{event}' in state {self.state}"
if event == "changes":
if self.revisions == self.max_revisions:
target = "needs_person"
else:
self.revisions += 1
self.history.append((self.state, event, target))
self.state = target
return f"{event} -> {target}"
job = Job()
for event in ["start", "approve", "draft_ready", "changes", "draft_ready",
"changes", "draft_ready", "changes", "approve"]:
print(job.send(event))
late = Job()
for event in ["start", "draft_ready", "approve", "cancel"]:
result = late.send(event)
print(result)
Output:
start -> researching
refused 'approve' in state researching
draft_ready -> reviewing
changes -> researching
draft_ready -> reviewing
changes -> researching
draft_ready -> reviewing
changes -> needs_person
refused 'approve' in state needs_person
refused 'cancel' in state publishing
Approval is refused while researching, even if an agent or a message asks for it. The third request for changes goes to a person because the revision limit is reached. Once publishing has started, canceling is refused because the machine has no safe way to do it; a real design would add a withdrawal process. In a service, store the state with a version and update it conditionally, so two events arriving together cannot both succeed. Also check who sent each event: a valid transition requested by the wrong person is still wrong.
| Choose | When |
|---|---|
| State machine | Lifecycle with strict rules, audit and external events |
| Graph | Flow of processing with branches, parallel work and loops |
| Both | A state machine for the business record, a graph inside one state |
The transition table
Writing moves as a table forces decisions that diagrams hide. For each state, consider every event, including cancel, timeout and duplicate delivery.
| From | Event | Guard | To |
|---|---|---|---|
| new | start | Request is complete | researching |
| researching | draft ready | Sources attached | reviewing |
| reviewing | changes | Revisions left | researching |
| reviewing | changes | No revisions left | needs person |
| reviewing | approve | Approver authorized, draft unchanged | publishing |
| publishing | published | Confirmed by the publisher | done |
A guard is a condition that must hold for a move to happen. The small program above implements the revision guard but not the others. Add them where the table says, and test each one both ways. Decide also how a person leaves the needs-person state; a state with no exit is acceptable only when it is meant to be final.
Conditional branching and dynamic routing
A conditional edge chooses the next node from the state. Prefer conditions computed by code. When a model chooses, restrict it to a listed set, validate the answer and provide a default for unknown or low-confidence cases.
- Make conditions exclusive, or state the order in which they are checked.
- Include an "otherwise" edge so no run is stranded.
- Log the chosen edge and the values behind it.
- Test every edge, including the default.
Dynamic routing goes further: the graph creates branches from data, such as one worker per document. Cap the number created and decide what happens to the items beyond the cap.
Parallelism, fan-out and fan-in
Fan-out starts several branches; fan-in combines them. The join needs rules: wait for all, for required ones, for the first good result or until a deadline.
"""Fan out with a concurrency limit and a deadline, then fan in."""
import asyncio
SOURCES = {"catalog": 0.01, "reviews": 0.02, "forum": 5.0,
"archive": 0.01, "partner": -1}
async def fetch(name, delay, gate, active, peak):
async with gate:
active[0] += 1
peak[0] = max(peak[0], active[0])
try:
if delay < 0:
raise ConnectionError("refused")
await asyncio.sleep(delay)
return f"{name} ok"
finally:
active[0] -= 1
async def main(limit=2, deadline=0.5):
gate, active, peak = asyncio.Semaphore(limit), [0], [0]
tasks = {name: asyncio.create_task(fetch(name, d, gate, active, peak))
for name, d in SOURCES.items()}
await asyncio.wait(tasks.values(), timeout=deadline)
results = {}
for name, task in tasks.items():
if not task.done():
task.cancel()
results[name] = "timed out"
elif task.exception():
results[name] = f"failed ({task.exception()})"
else:
results[name] = "ok"
await asyncio.gather(*tasks.values(), return_exceptions=True)
for name, state in results.items():
print(f"{name:<8}{state}")
good = sum(s == "ok" for s in results.values())
required = {"catalog", "reviews"}
usable = all(results[n] == "ok" for n in required)
print(f"{good}/{len(results)} sources, peak parallel {peak[0]}, "
f"{'continue with gaps listed' if usable else 'stop'}")
asyncio.run(main())
Output:
catalog ok
reviews ok
forum timed out
archive ok
partner failed (refused)
3/5 sources, peak parallel 2, continue with gaps listed
No more than two requests run at once. The slow source is canceled at the deadline, the refused connection is recorded and the run continues because both required sources answered. The result lists its gaps. Note that the deadline includes time spent waiting for a free slot, so queued branches can time out without ever starting. Cancellation stops this local task; a remote service may still carry out a request it has already received.
| Join rule | Use | Risk |
|---|---|---|
| All | Every part is essential | One slow branch delays or fails the run |
| Required plus optional | Core answer with extras | Gaps must be shown |
| First acceptable | Redundant sources | Wasted work, weak acceptance test |
| Quorum | Votes or replicas | Shared errors |
| Deadline | Interactive requests | Quietly partial results |
Parallel branches writing the same state field need a merge function, such as appending to a list, instead of last write wins. See Parallelism, Deadlocks and Conflict Resolution.
Designing the shared state
Keep state small, typed and explicit. Separate the request, which does not change, from findings that accumulate, decisions with their author, counters used for limits and the current status. For every field state who writes it and whether later writes replace or add to it. Avoid one free-form message list as the only state: it grows without bound, and conditions that depend on reading prose are fragile.
| Field | Writer | Update rule |
|---|---|---|
| request | Intake node | Set once |
| findings | Research nodes | Append with source |
| draft | Drafting node | Replace, keep version |
| decision | Approval step | Set once per draft version |
| revisions | Runtime | Increase only |
Agents should not be able to write counters, permissions or approvals. The runtime owns those.
Compensation and sagas
When a process changes several independent systems, one database transaction usually cannot cover them. A saga is a sequence of local steps, each paired with a compensating action that is run if a later step fails.
"""Run steps in order; on failure, compensate completed ones in reverse."""
def run(steps, failing=(), undo_failing=()):
completed, log = [], []
for name, undo in steps:
if name in failing:
log.append(f"{name}: failed")
break
log.append(f"{name}: done")
completed.append((name, undo))
else:
return "completed", log
manual = []
for name, undo in reversed(completed):
if undo is None:
manual.append(name)
log.append(f"{name}: cannot be undone")
elif undo in undo_failing:
manual.append(name)
log.append(f"{undo}: failed")
else:
log.append(f"{undo}: done")
status = "needs a person" if manual else "compensated"
return status, log
TRIP = [("reserve flight", "cancel flight"),
("send itinerary", None),
("reserve hotel", "cancel hotel"),
("charge card", "refund card")]
NO_MAIL = [s for s in TRIP if s[1]]
for title, steps, options in [
("clean failure", NO_MAIL, {"failing": {"charge card"}}),
("email already sent", TRIP, {"failing": {"charge card"}}),
("undo fails too", NO_MAIL, {"failing": {"charge card"},
"undo_failing": {"cancel flight"}})]:
status, log = run(steps, **options)
print(f"{title}: {status}")
for line in log:
print(" ", line)
Output:
clean failure: compensated
reserve flight: done
reserve hotel: done
charge card: failed
cancel hotel: done
cancel flight: done
email already sent: needs a person
reserve flight: done
send itinerary: done
reserve hotel: done
charge card: failed
cancel hotel: done
send itinerary: cannot be undone
cancel flight: done
undo fails too: needs a person
reserve flight: done
reserve hotel: done
charge card: failed
cancel hotel: done
cancel flight: failed
In the first case both reservations are canceled in reverse order. In the second, the email has already gone, so the run ends needing a person. In the third, a cancellation fails and is flagged while the remaining state is reported honestly. Three points the small program leaves out matter in production. A step that "failed" may actually have happened, so check its status before assuming otherwise. Record the saga's progress durably, or a crash loses the list of things to undo. And make compensations safe to repeat.
- Put irreversible steps, such as sending messages, as late as possible.
- Prefer reservations and drafts that expire to immediate commitments.
- Remember that compensation is a new action, not erasure: a refund does not make the charge never happen.
- Show a person exactly what is done, undone and unknown.
Orchestration for several agents
An agent can be a node. The graph then controls when it runs, what it sees, what it returns and where control may go next.
| Pattern | Graph form |
|---|---|
| Supervisor | A hub node routes to workers and receives results |
| Pipeline | A chain of agent nodes with checks between |
| Handoff | Conditional edges between peer nodes, with a hop limit |
| Generator and reviewer | Two nodes with a bounded loop |
| Map and combine | Dynamic fan-out followed by a merge node |
Give each agent node its own slice of state and a typed output. Validate between nodes so that one agent's mistake is stopped at the boundary. Keep irreversible actions in dedicated nodes guarded by approval rather than inside a free-running agent.
Design review for a graph
- List all states and terminal outcomes, including canceled and needs-person.
- Check every state can reach an end.
- Bound each loop with a counter or deadline.
- Name the owner of every state field.
- Mark nodes with side effects and how they avoid duplicates.
- Decide behavior for events that arrive late or twice.
Several of these can be tested automatically: walk the transition table, confirm that terminal states have no exits and that each non-terminal state has a path to one. For deeper checks, see Formal Verification and Testing Foundations.
Keep graphs readable
A graph with dozens of nodes and crossing edges is as hard to maintain as tangled code. Group related steps into subgraphs with a clear input and output, handle common failures in one place and delete paths that traces show are never used, after confirming they are not rare safety paths. Generate the diagram from the definition so the picture cannot drift from behavior. Changing a graph with runs in progress needs care, covered in Workflow Versioning, Testing and Resilience.
Error edges
Give failures their own routes instead of letting exceptions end a run wherever they occur. A node can finish with success, a retryable fault, a permanent fault or a need for input, and the graph decides what follows each. Route permanent faults to a handler that records the cause, compensates if required and notifies the owner. Keep the original error with the state so the person handling it does not have to search logs.
Time as an event
Waiting states need an exit that fires without anyone acting. Treat a timeout as an ordinary event in the machine: reviewing plus "expired" leads to a reminder, another reviewer or a person in charge. Store the deadline with the state, let a scheduler or workflow engine deliver the event and ignore it if the task has already moved on. Decide which clock counts, how holidays and time zones affect business deadlines and whether the timer restarts after each revision. A workflow with no expiry events tends to collect tasks that nobody notices are stuck.
Saving progress
Decide where the state lives between steps. If it is only in memory, a restart returns you to the beginning, and earlier actions may repeat. Save after meaningful steps, with a run identifier and the definition version, and make nodes with effects safe to run again. Durable Execution, Checkpoints and Approvals covers this in depth.
Seeing a graph in service
Emit one record per node visit with the run, node, incoming edge, state version, duration and outcome. From these you can see which paths are common, where runs wait, which loops reach their limit and which branches are never used. Compare the distribution after each release: a sharp rise in one edge often signals a changed input or a weaker model step before users report it. Link every run to its definition version so that old and new behavior are not mixed in one chart. See Agent Tracing and OpenTelemetry.
Common mistakes
- Letting a model invent the next state.
- Loops without an exit guarantee.
- No default edge.
- Parallel branches overwriting one field.
- Joins that wait forever.
- Assuming compensation always succeeds.
- Irreversible actions early in a saga.
Checklist
- States, events and edges are listed.
- Invalid moves are refused and logged.
- Every loop and wait is bounded.
- Joins define required parts and gaps.
- Side effects have operation keys.
- Compensations are durable, repeatable and monitored.
- Every edge and failure path has a test.
Frequently asked questions
Is a graph less flexible than an agent loop?
It deliberately limits next steps. Leave an agent node with several tools where exploration is needed, and constrain what surrounds it.
Are sagas the same as transactions?
No. Intermediate results are visible to others and compensation may fail, so a saga gives weaker guarantees than one database transaction.
How deep should parallel fan-out go?
Only as far as limits, budgets and the merge can handle. Cap both width and nesting.
Where do approvals fit?
As states of their own, with the proposed action stored, a deadline and events for approve, reject and expire.
References and further reading
- LangGraph: graph API
- Microsoft: saga distributed transactions pattern
- Python asyncio: tasks and coroutines
- Anthropic: building effective agents
Next steps
Durable Execution, Checkpoints and Approvals
Keep progress through failures.
Workflow Versioning, Testing and Resilience
Change and test workflows.
LangChain and LangGraph
See a graph library.