Lab: Routing, Cycles and Parallel Branches
Wire a real LangGraph StateGraph with a fan-out to two branches, a fan-in join with a reducer, a conditional edge that loops back with an exit condition, and recursion_limit as the backstop; then break it on purpose to see each failure.
Contentsand lesson path
On this page
Lessons of Stateful Agent Graphs
- Agents as State Machines Concept · 15 min
- State, Nodes and Reducers Worked example · 20 min
- Lab: Routing, Cycles and Parallel Branches Lab · 25 min
- Checkpoints, Threads and Replay Lab · 25 min
- Graph Framework, Agent SDK or Plain Code? Concept · 15 min
- Check: Trace a Graph Execution Knowledge check · 8 questions
What you will learn
- Implement conditional routing, cycles with exit conditions and parallel branches.
Prerequisites: Agent Loops & ReAct
01. Beyond Linear Orchestration
Many agent tasks are not a straight line. An analysis agent may query two data sources at once, check whether the combined result is good enough, and go back to re-plan when it is not. In graph terms that needs three things: parallel branches (two nodes running in the same step), conditional routing (code that picks the next node from the state) and cycles (an edge back to an earlier node) with an exit condition, so the loop ends.
In this lab you wire all three with LangGraph, using the state and reducer ideas from State, Nodes and Reducers. Then you break the graph on purpose four times, because seeing each failure once makes it much easier to recognise in your own traces.
02. Goal and Setup
The graph answers "Analyse quarterly retention" with fake data, so it runs offline and gives the same result every time:
plannerstarts an attempt and counts it inattempt.- Two edges leave
planner, sosqlandapi_fetchrun in parallel. This is the fan-out. The API branch is two nodes long:api_fetch, thenapi_clean. add_edge(["sql", "api_clean"], "evaluator")is the fan-in:evaluatorwaits until both sources have finished. Both branches write intometrics, and the reduceroperator.or_merges their dictionaries.evaluatorstores ascorein the state. On the first attempt the API returns no customer segment, so the score is low.add_conditional_edges("evaluator", route_after_eval, ["planner", "synthesizer"])routes on that score. Going back toplanneris the cycle. The exit condition is a score at or aboveTHRESHOLD, orattemptreachingMAX_ATTEMPTS.STARTandENDmark where the run begins and stops, andcompile()checks the wiring and returns a runnable graph.
LangGraph runs a graph in super-steps: every node scheduled for a step runs, their updates are applied together, and then the next step is planned. The script prints the nodes of each super-step, so nodes on the same line ran in parallel. It reads them from graph.stream(..., stream_mode="debug"), which reports each task with its step number.
You need Python 3.12 or later. The lab was tested with Python 3.12 and langgraph 1.2.22. No checkpointer is used here; the next lab adds one.
mkdir graph-lab && cd graph-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "langgraph==1.2.22""""Routing, a bounded cycle and parallel branches with LangGraph.
python graph_lab.py normal run: one retry, then a report
python graph_lab.py --force-low the score never passes: the guard exits
python graph_lab.py --force-low --no-guard no exit condition: recursion_limit
python graph_lab.py --separate-edges two plain edges instead of one join
python graph_lab.py --fail-api one branch raises: the super-step fails"""
import operator
import sys
from typing import Annotated, TypedDict
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
FLAGS = set(sys.argv[1:])
THRESHOLD = 0.8
MAX_ATTEMPTS = 3
class AnalyticsState(TypedDict, total=False):
question: str
attempt: int
metrics: Annotated[dict, operator.or_] # merges the dicts from both branches
notes: Annotated[list[str], operator.add] # appends feedback from each loop
score: float
report: str
def planner(state):
attempt = state.get("attempt", 0) + 1
return {"attempt": attempt, "notes": [f"plan {attempt}: query SQL and API"]}
def sql_worker(state): # stands in for a warehouse query
return {"metrics": {"churn_rate_pct": 2.41}}
def api_fetch(state): # stands in for a cohort API; first call returns no segment
if "--fail-api" in FLAGS:
raise RuntimeError("cohort API timed out")
segment = "enterprise" if state["attempt"] > 1 else None
return {"metrics": {"mau_raw": "1,420,500", "segment": segment}}
def api_clean(state):
return {"metrics": {"mau": int(state["metrics"]["mau_raw"].replace(",", ""))}}
def evaluator(state): # a scripted grader; a real one could be a model or tests
m = state["metrics"]
complete = "churn_rate_pct" in m and "mau" in m and m.get("segment")
score = 0.4 if "--force-low" in FLAGS or not complete else 0.9
note = "ok" if score >= THRESHOLD else "missing data, retry with segment filter"
return {"score": score, "notes": [f"eval {state['attempt']}: {score} {note}"]}
def route_after_eval(state): # reads state, returns the name of the next node
if state["score"] >= THRESHOLD:
return "synthesizer"
if "--no-guard" not in FLAGS and state["attempt"] >= MAX_ATTEMPTS:
return "synthesizer" # exit condition: stop retrying, report best effort
return "planner" # the cycle
def synthesizer(state):
verdict = "final" if state["score"] >= THRESHOLD else "best effort, low score"
return {"report": f"{verdict} after {state['attempt']} attempt(s)"}
builder = StateGraph(AnalyticsState)
for name, node in [("planner", planner), ("sql", sql_worker), ("api_fetch", api_fetch),
("api_clean", api_clean), ("evaluator", evaluator),
("synthesizer", synthesizer)]:
builder.add_node(name, node)
builder.add_edge(START, "planner")
builder.add_edge("planner", "sql") # two edges out of planner: fan-out
builder.add_edge("planner", "api_fetch")
builder.add_edge("api_fetch", "api_clean")
if "--separate-edges" in FLAGS:
builder.add_edge("sql", "evaluator") # each edge triggers evaluator on its own
builder.add_edge("api_clean", "evaluator")
else:
builder.add_edge(["sql", "api_clean"], "evaluator") # fan-in: waits for both
builder.add_conditional_edges("evaluator", route_after_eval, ["planner", "synthesizer"])
builder.add_edge("synthesizer", END)
graph = builder.compile()
def run(inputs):
steps, final = {}, {}
try:
for mode, data in graph.stream(inputs, {"recursion_limit": 20},
stream_mode=["debug", "values"]):
if mode == "values":
final = data # the full state after each super-step
elif data["type"] == "task": # a node scheduled in super-step N
steps.setdefault(data["step"], []).append(data["payload"]["name"])
finally: # print the trace even when the run fails
for step, names in steps.items(): # same step = ran in parallel
print(f"step {step}: {' + '.join(sorted(names))}")
return final
try:
final = run({"question": "Analyse quarterly retention"})
except GraphRecursionError:
sys.exit("run failed: GraphRecursionError (recursion_limit=20 reached)")
except RuntimeError as exc:
sys.exit(f"run failed: RuntimeError: {exc}")
print("metrics:", ", ".join(f"{k}={v}" for k, v in sorted(final["metrics"].items())))
print("notes:", *final["notes"], sep="\n ")
print("report:", final["report"])03. Run the Lab
Step 1: the normal run. Run the graph without flags.
python graph_lab.pystep 1: planner
step 2: api_fetch + sql
step 3: api_clean
step 4: evaluator
step 5: planner
step 6: api_fetch + sql
step 7: api_clean
step 8: evaluator
step 9: synthesizer
metrics: churn_rate_pct=2.41, mau=1420500, mau_raw=1,420,500, segment=enterprise
notes:
plan 1: query SQL and API
eval 1: 0.4 missing data, retry with segment filter
plan 2: query SQL and API
eval 2: 0.9 ok
report: final after 2 attempt(s)Read the trace from the top. In step 2, api_fetch and sql ran in the same super-step: the fan-out. evaluator did not run in step 3, although sql had finished, because the join waits for api_clean too. In step 4 the evaluator scored 0.4 (see notes), below the threshold, so the router sent the run back to planner: the cycle. On the second attempt the API returned a segment, the score was 0.9 and the router chose synthesizer. metrics holds keys from both branches, merged by the reducer, and notes grew by one entry per node call because its reducer is operator.add.
Step 2: force a low score. With --force-low, the evaluator never passes. Predict the last attempt number before you run it.
python graph_lab.py --force-lowstep 1: planner
step 2: api_fetch + sql
step 3: api_clean
step 4: evaluator
step 5: planner
step 6: api_fetch + sql
step 7: api_clean
step 8: evaluator
step 9: planner
step 10: api_fetch + sql
step 11: api_clean
step 12: evaluator
step 13: synthesizer
metrics: churn_rate_pct=2.41, mau=1420500, mau_raw=1,420,500, segment=enterprise
notes:
plan 1: query SQL and API
eval 1: 0.4 missing data, retry with segment filter
plan 2: query SQL and API
eval 2: 0.4 missing data, retry with segment filter
plan 3: query SQL and API
eval 3: 0.4 missing data, retry with segment filter
report: best effort, low score after 3 attempt(s)The loop ran three times and then the exit condition fired: attempt reached MAX_ATTEMPTS, so the router chose synthesizer even with a low score, and the report says so. This exit is part of your design. The run ends normally, and the report tells the user that the answer is a best effort.
Step 3: remove the exit condition. --no-guard makes the router ignore MAX_ATTEMPTS. Now only recursion_limit can stop the loop. It is the maximum number of super-steps per run, set in the config. The script sets it to 20. The default in the version tested is 10,007, so a loop without a guard could run for a long time and cost a lot of model calls before it stops.
python graph_lab.py --force-low --no-guardstep 1: planner
step 2: api_fetch + sql
step 3: api_clean
step 4: evaluator
step 5: planner
step 6: api_fetch + sql
step 7: api_clean
step 8: evaluator
step 9: planner
step 10: api_fetch + sql
step 11: api_clean
step 12: evaluator
step 13: planner
step 14: api_fetch + sql
step 15: api_clean
step 16: evaluator
step 17: planner
step 18: api_fetch + sql
step 19: api_clean
step 20: evaluator
run failed: GraphRecursionError (recursion_limit=20 reached)This time there is no report. GraphRecursionError fails the whole run, and the work of five attempts is thrown away. Treat recursion_limit as a safety net that catches bugs, and keep the exit condition in your router.
Step 4: replace the join with two plain edges. --separate-edges wires sql → evaluator and api_clean → evaluator as two separate edges.
python graph_lab.py --separate-edgesstep 1: planner
step 2: api_fetch + sql
step 3: api_clean + evaluator
step 4: evaluator + planner
step 5: api_fetch + planner + sql
step 6: api_clean + api_fetch + evaluator + sql
step 7: api_clean + evaluator + synthesizer
step 8: evaluator + synthesizer
step 9: synthesizer
metrics: churn_rate_pct=2.41, mau=1420500, mau_raw=1,420,500, segment=enterprise
notes:
plan 1: query SQL and API
eval 1: 0.4 missing data, retry with segment filter
eval 1: 0.4 missing data, retry with segment filter
plan 2: query SQL and API
plan 3: query SQL and API
eval 3: 0.9 ok
eval 3: 0.9 ok
eval 3: 0.9 ok
report: final after 3 attempt(s)Each plain edge triggers evaluator by itself. So evaluator ran in step 3, as soon as sql finished and before the API data was clean, and again in step 4. Each low score started another planner, so several attempts overlapped and the notes contain duplicates. Use the list form of add_edge whenever a node must wait for several branches, especially when the branches have different lengths.
Step 5: make one branch fail. --fail-api makes api_fetch raise an error, as a timed-out API call would.
python graph_lab.py --fail-apistep 1: planner
step 2: api_fetch + sql
run failed: RuntimeError: cohort API timed outOne failing branch fails the whole super-step. sql ran in step 2 as well, but the run stops with the error and its churn rate is not applied to the state. Without a checkpointer, that work is gone. With one, LangGraph keeps the successful writes of the failed step as pending writes, as described in the previous lesson, so a resume does not run sql again.
Also note what LangGraph does not do for you by default: it sets no time limit on a node. A synchronous node that hangs on a slow API keeps its whole super-step waiting. Put a timeout on every network call inside your nodes (most HTTP clients take a timeout argument). In the version tested, add_node(..., timeout=...) also exists, but only for async nodes. A RetryPolicy can then retry a failed or timed-out node.
04. Verify Your Understanding
05. Apply It
In the skill's practice project you rebuild your framework-free agent as a graph with a router node, a tool node, a reflection node and a final-answer node. Use this lab as the template:
- Let the model return a structured decision (which tool, or done), and let a router function in code turn it into the next node name.
- Give the reflection loop an exit condition in state, and set
recursion_limitlow enough that a bug fails fast. - If two tools can run independently, fan them out and join them with the list form of
add_edge, with a reducer on every field both of them write. - Put a timeout on every external call inside a node, and decide whether one failed branch should fail the run or be caught inside the node and recorded as a partial result.
06. Review Prompt
Without looking back, sketch the lab graph and label the fan-out, the join, the cycle and the exit condition. Explain what a super-step is, why evaluator did not run in step 3 of the normal run, and what changed with two plain edges. Then explain the difference between the exit condition in the router and recursion_limit, and what happens to the state when one of two parallel branches raises an error.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.