By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A digest request names N documents and asks for one summary per document plus a combined report. N is not known when the graph is built — it comes from the request — so a fixed set of parallel edges cannot express the work. LangGraph's answer is Send: return one Send(node, payload) per item from a conditional edge and the runtime starts the target node once per payload. That is the map. The fan-in is an ordinary edge from the map node to a reduce node, which runs once after every branch completes.
The payload is the branch's own small state; the branch's returned updates merge back into the parent through the normal channels. So the merged channels need reducers — an append reducer on the summaries list is the standard choice — or the branches collide the same way parallel fixed edges would. In this lab you add a second concern that separates a toy map-reduce from a usable one: what happens when one item fails.
The fan-out function returns a list of Send objects from a conditional edge. Notice that the graph has one summarize node, not N nodes: Send starts the same node once per payload. The reduce node then sees the reducer-merged channels. The branch here turns a missing document into an in-band failure — a failures entry rather than a raised exception — so one bad id cannot discard the other summaries.
from operator import add
from typing import Annotated, TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
class DigestState(TypedDict):
doc_ids: list[str]
summaries: Annotated[list[str], add]
failures: Annotated[list[str], add]
digest: str | None
class DocState(TypedDict):
doc_id: str
DOCS = {
"d1": "refunds within 30 days",
"d2": "ships in 3 days",
"d3": "gift cards never expire",
}
def fan_out(state: DigestState) -> list[Send]:
"""One branch per id: the width is decided by state at runtime."""
return [Send("summarize", {"doc_id": doc_id}) for doc_id in state["doc_ids"]]
def summarize(state: DocState) -> dict:
text = DOCS.get(state["doc_id"])
if text is None:
# In-band failure: the branch completes, the reduce counts it.
return {"failures": [f"{state['doc_id']}: unknown document"]}
return {"summaries": [f"{state['doc_id']}: {text}"]}
def reduce(state: DigestState) -> dict:
return {
"digest": f"{len(state['summaries'])} ok, {len(state['failures'])} failed"
}
builder = StateGraph(DigestState)
builder.add_node("summarize", summarize)
builder.add_node("reduce", reduce)
builder.add_conditional_edges(START, fan_out)
builder.add_edge("summarize", "reduce")
builder.add_edge("reduce", END)
graph = builder.compile()
result = graph.invoke(
{
"doc_ids": ["d1", "d9", "d3"],
"summaries": [],
"failures": [],
"digest": None,
}
)
print(result["digest"])
print(sorted(result["summaries"]))
print(result["failures"])Two of three ids resolve and the digest reports the third as a failure. The reduce node could not have known that on its own: the branch recorded the failure through the same reducer machinery as a success. That is the pattern — partial failure is data the fan-in can reason about, not an exception that unwinds the request.
A map branch can fail in two different ways, and the choice between them is a product decision, not an implementation detail. In-band failure means the node catches the problem, records it in a reducer channel and completes. Raised failure means the node lets the exception escape; the superstep fails, any retry policy applies, and the run aborts if retries are exhausted. Mixed policies are normal: a missing optional document is in-band, a database outage is raised and retried.
| Failure shape | What the runtime does | Design decision |
|---|---|---|
| Node returns an error value | Branch completes; the fan-in sees the error as data | Count it, report partial success and let the caller decide |
| Node raises | Superstep fails; node RetryPolicy applies; run aborts if retries are exhausted | Catch inside the node only when one item must not sink the other N-1 |
| Zero items | No Send tasks are created, so the reduce node has no map edge to trigger it | Decide the empty-list result in the planner and test that case explicitly |
import pytest
from digest_graph import build_digest_graph
def invoke(graph, doc_ids):
return graph.invoke(
{
"doc_ids": doc_ids,
"summaries": [],
"failures": [],
"digest": None,
}
)
def test_one_branch_per_item_and_one_reduce():
graph = build_digest_graph()
result = invoke(graph, ["d1", "d2", "d3"])
assert result["digest"] == "3 ok, 0 failed"
assert len(result["summaries"]) == 3
def test_a_bad_item_does_not_lose_the_good_ones():
graph = build_digest_graph()
result = invoke(graph, ["d1", "d9", "d3"])
assert len(result["summaries"]) == 2
assert result["failures"] == ["d9: unknown document"]
assert result["digest"] == "2 ok, 1 failed"
def test_the_map_reducer_accumulates_instead_of_replacing():
graph = build_digest_graph()
result = invoke(graph, ["d1", "d2", "d3"])
assert sorted(result["summaries"]) == [
"d1: refunds within 30 days",
"d2: ships in 3 days",
"d3: gift cards never expire",
]Send objects built from state, with no hard-coded branch count.Key takeaways
Send expresses a map over a list known only at runtime: return one Send(node, payload) per item from a conditional edge.
A Send payload is the branch's state; branch updates merge back through the parent graph's channels, which must have reducers.
The edge from the map node to the reduce node is the fan-in barrier; the reduce runs once after every branch completes.
Partial failure is a design choice: in-band error values let N-1 results survive, while a raised exception fails the superstep and follows the node's retry policy.
A zero-length list produces no map tasks, so decide the empty digest in the planner and test it explicitly.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.