Module 2 · Flow control
Send API and parallel map-reduce
6 min read
A refund request often covers several items, and each must be assessed: is it part of the complaint? Within the return window? Refundable? Assessing three items one after the other triples latency. Assessing them in parallel, then aggregating the results, is the map-reduce pattern. LangGraph implements it with a dedicated tool: Send.
The problem: parallelism whose degree depends on the data
We saw that several edges leaving the same node launch several nodes in parallel. But that parallelism is static: the number of branches is fixed in the code. Here, the number of tasks depends on the data — an order has one, three or ten items — and each task must receive its own inputs (a different item).
Send solves both problems: a routing function returns a list of Sends, each naming a node and the payload it will receive.
from langgraph.types import Send
Send("assess_item", {"item": item, "complaint": complaint, "delivered_on": delivered_on})
The engine creates one task per Send and runs them all in the same step, in parallel.
Minimal map-reduce
Here is the complete pattern, without an LLM (file examples/03_map_reduce.py):
class State(TypedDict):
documents: list[str]
summaries: Annotated[list[str], operator.add]
report: str
class DocTask(TypedDict):
document: str
def dispatch(state: State) -> list[Send]:
return [Send("summarize", DocTask(document=d)) for d in state["documents"]]
async def summarize(task: DocTask) -> dict:
await asyncio.sleep(1) # simulates a one-second LLM call
return {"summaries": [f"résumé({task['document']})"]}
def combine(state: State) -> dict:
return {"report": " + ".join(sorted(state["summaries"]))}
builder = StateGraph(State)
builder.add_node("summarize", summarize)
builder.add_node("combine", combine)
builder.add_conditional_edges(START, dispatch, ["summarize"])
builder.add_edge("summarize", "combine")
builder.add_edge("combine", END)
Five documents are processed in about one second, not five. Three elements make the pattern work:
- The map:
dispatchis a routing function returning a list ofSends. - Each task's input:
summarizereceives theSendpayload (aDocTask), not the graph's full state. Each task only sees what it needs. - The reduce: each task writes to
summaries, and theoperator.addreducer concatenates all contributions. Without that reducer, the parallel writes would raise anInvalidUpdateError.
The summarize → combine edge performs the fan-in: combine runs only once, in the next step, when all summarize tasks are done.
Relay's map-reduce
In the refund subgraph, load_order loads the order, then fan_out_items distributes the items:
def fan_out_items(state: RefundState) -> list[Send] | Literal["explain"]:
refund = state["refund"]
if refund.get("error"):
return "explain"
return [
Send("assess_item", ItemTask(item=item, complaint=refund["complaint"],
delivered_on=refund["delivered_on"]))
for item in refund["items"]
]
builder.add_conditional_edges("load_order", fan_out_items, ["assess_item", "explain"])
builder.add_edge("assess_item", "decide")
The same router can return either a node name ("explain" if the order can't be found) or a list of Sends: the map only happens if the data allows it.
Each assess_item combines deterministic rules and model judgment:
async def assess_item(task: ItemTask) -> dict:
item = task["item"]
if item["category"] == "digital":
return {"assessments": [{**item, "eligible": False, "why": "digital"}]}
... # return window: computed by code
prompt = f"Article : {item['name']}\nRéclamation : {task['complaint']}"
verdict = await model.ainvoke([SystemMessage(REASON_PROMPT), HumanMessage(prompt)])
if not verdict.concerned:
return {"assessments": [{**item, "eligible": False, "why": "not_concerned"}]}
rate = config.CHANGED_MIND_RATE if verdict.reason == "changed_mind" else 1.0
amount = round(item["price"] * rate, 2)
return {"assessments": [{**item, "eligible": True, "why": verdict.reason, "amount": amount}]}
The order of checks matters: hard rules (digital product, window expired) are applied first, by code, without calling the model. The LLM only steps in for what it can do and code cannot: read the complaint in natural language and determine whether it concerns this item, and for what reason. The amount is always computed by code.
Then decide aggregates:
def decide(state: RefundState) -> dict:
eligible = [a for a in state["assessments"] if a["eligible"]]
amount = round(sum(a["amount"] for a in eligible), 2)
...
Parallelism pitfalls
Result order is not guaranteed. Tasks finish in any order. If order matters, sort in the reduce, or include an index in the payload.
Parallel tasks don't see each other. Each task reads its payload (or the state at the start of the step), never the writes of other tasks in the same step.
A failing task fails the step. If an assessment raises an unhandled exception, the step fails. The other results aren't lost if a checkpointer is configured: LangGraph keeps the writes of successful tasks (pending writes), and on resume only the failed tasks run again. For finer fault tolerance, attach a retry policy to the parallelized node, or catch the error in the task and return a "not assessed" result.
Parallelism has a cost. A hundred Sends mean a hundred simultaneous model calls: you'll quickly hit your provider's rate limits. Cap the number of tasks in the router, or group items into batches.
The reducer keeps everything, from one run to the next. A key with an addition reducer accumulates for the lifetime of the thread. If the same graph runs twice on the same thread, the second run also sees the first one's results. In Relay, assessments is a private key of the refund subgraph: each request starts from an empty list (next lesson). In a simple graph, reset the key at the start of the run with Overwrite([]).
Static or dynamic parallelism?
| Need | Solution |
|---|---|
| A fixed number of different branches (e.g. search the web AND the database) | Several edges from one node |
| A variable number of identical tasks on different inputs | Send |
| A step that waits for several branches | One edge from each branch to the aggregation node |
Key takeaways
Send(node, payload)creates a task; a list ofSends returned by a router performs the map.- Each task receives its payload, not the full state.
- The reduce relies on a reducer (often
operator.add); the fan-in on an edge to the aggregation node.- Hard rules in code first, model judgment second, amounts always computed by code.
- Order not guaranteed, cost and rate limits to watch, reducer accumulation to control.
Practice
- Run
examples/03_map_reduce.pywith 20 documents: does the total duration change? - Make
summarizefail for one document out of five and observe the behavior, with and without aRetryPolicy. - In Relay, add a cap of 10 items assessed per request; beyond that, escalate to a human.