LangGraph Send API: Parallel Map-Reduce Fan-Out in Python
S L Manikanta
Nov 28, 2026 • 7 min read
bolt Key Takeaways
- Use LangGraph's Send(node_name, payload) inside a conditional edge to spawn dynamic parallel worker nodes per item in a single superstep.
- Always annotate fan-in state fields with Annotated[list[T], operator.add]; omitting the reducer triggers InvalidUpdateError when parallel branches finish.
- Never rely on raw unbounded fan-out for external LLM APIs: gate worker calls with an asyncio.Semaphore to prevent 429 rate-limit cascades.
- Return structured error objects from worker nodes instead of raising raw exceptions so one failed item does not discard all sibling branches.
list On this page expand_more
- Quick Solution: Parallel Map-Reduce with Send and operator.add
- How Send Works Under the Hood (Supersteps & Reducers)
- Fan-Out Patterns Compared: Static Edges vs Send vs asyncio.gather
- Production Implementation: Bounded Concurrency & Partial Failure Isolation
- Resetting Reducer Lists Across Multi-Turn Loops
- Frequently Asked Questions
- Why does LangGraph throw InvalidUpdateError during parallel Send execution?
- What is the difference between static parallel edges and the Send API in LangGraph?
- How do you limit concurrency when using Send in LangGraph?
- What happens if one parallel Send branch raises an unhandled exception?
Want to build production-ready AI?
Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.
Quick Solution: Parallel Map-Reduce with Send and operator.add
Dynamic parallelization in LangGraph (langgraph==0.3.4, Python 3.11+) fails with InvalidUpdateError: Can receive only one value per step if parallel worker nodes write to an un-annotated state field. To fan out dynamically and merge results safely, return list[Send] from a conditional edge and bind the fan-in state key with Annotated[list[...], operator.add].
import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Send
class OverallState(TypedDict):
tickers: list[str]
reports: Annotated[list[dict[str, str]], operator.add]
final_summary: str
class WorkerInput(TypedDict):
ticker: str
def fan_out_tickers(state: OverallState) -> list[Send]:
return [Send("analyze_ticker", {"ticker": t}) for t in state["tickers"]]
async def analyze_ticker(state: WorkerInput) -> dict[str, list[dict[str, str]]]:
return {"reports": [{"ticker": state["ticker"], "status": "ok"}]}
def reduce_reports(state: OverallState) -> dict[str, str]:
completed = [r["ticker"] for r in state["reports"]]
return {"final_summary": f"Processed {len(completed)} tickers: {', '.join(completed)}"}
builder = StateGraph(OverallState)
builder.add_node("analyze_ticker", analyze_ticker)
builder.add_node("reduce_reports", reduce_reports)
builder.add_conditional_edges(START, fan_out_tickers, ["analyze_ticker"])
builder.add_edge("analyze_ticker", "reduce_reports")
builder.add_edge("reduce_reports", END)
graph = builder.compile()
flowchart TD
StartNode["START (tickers: NVDA, MSFT, AMD)"] -->|"fan_out_tickers() -> list[Send]"| W1["analyze_ticker (NVDA)"]
StartNode -->|"Send"| W2["analyze_ticker (MSFT)"]
StartNode -->|"Send"| W3["analyze_ticker (AMD)"]
W1 -->|"operator.add"| Reduce["reduce_reports (Fan-In)"]
W2 -->|"operator.add"| Reduce
W3 -->|"operator.add"| Reduce
Reduce --> EndNode["END"]
How Send Works Under the Hood (Supersteps & Reducers)
In LangGraph’s Pregel-inspired execution engine,
Send(node, arg)schedules a private, isolated state payload for a target node within the next superstep, whileAnnotatedreducer functions deterministically merge all concurrent branch outputs before the downstream node executes.
Notice two critical details in the quick solution above:
- Private Worker Schemas:
analyze_tickeracceptsWorkerInput({"ticker": str}), notOverallState. Using a dedicatedTypedDictprevents workers from reading or mutating unrelated global keys and keeps memory overhead low when fanning out 50+ items. - Implicit Barrier Synchronization: LangGraph automatically waits for every
Sendbranch scheduled in the superstep to finish before invokingreduce_reports. You do not need manualasyncio.gatherboilerplate inside your graph nodes.
If your graph also loops iteratively after reduction, verify your cycle bounds in our guide to fixing LangGraph RecursionLimitExceeded and persist state across supersteps using LangGraph async Postgres checkpointing.
Fan-Out Patterns Compared: Static Edges vs Send vs asyncio.gather
| Pattern | Dynamic Batch Size | Per-Item Checkpointing | Concurrency Control | Best Production Use Case |
|---|---|---|---|---|
| Static Parallel Edges | No (fixed at compile time) | Yes (per node) | max_concurrency | Running 2-4 distinct fixed agents (e.g., Fundamentals + Sentiment) |
LangGraph Send API | Yes (driven by state list) | Yes (per superstep) | max_concurrency + Semaphore | Map-reduce over N documents, tickers, or search queries |
Manual asyncio.gather in 1 Node | Yes | No (all-or-nothing node) | asyncio.Semaphore | Fast, stateless I/O bursts where intermediate checkpoints aren’t needed |
We use both static parallel edges and dynamic Send fan-out inside StoxFlow to evaluate multi-ticker watchlists without blocking the main orchestration loop.
Production Implementation: Bounded Concurrency & Partial Failure Isolation
In production, naive Send graphs fail in two ways:
- Rate-Limit Cascades (
429 Too Many Requests): Fanning out 40 items simultaneously triggers 40 concurrent LLM calls on the exact same millisecond. - All-or-Nothing Crash: One malformed document or transient timeout inside
analyze_tickerraises an exception that aborts the superstep, discarding results from the other 39 completed workers.
The runnable script below (langgraph==0.3.4, pydantic>=2.10.0, Python 3.11+) solves both problems using:
config={"max_concurrency": 4}at invocation time to cap LangGraph’s superstep worker pool.- A typed
WorkerResultPydantic model that capturesokorerrorper branch so partial failures flow cleanly into the reducer. asyncio.wait_fortimeout enforcement per worker.
import asyncio
import operator
from typing import Annotated, Literal, TypedDict
from pydantic import BaseModel, Field
from langgraph.graph import StateGraph, START, END
from langgraph.types import Send
class WorkerResult(BaseModel):
item_id: str
status: Literal["ok", "error"]
score: float = Field(default=0.0, ge=0.0, le=1.0)
error_message: str | None = None
class MapReduceState(TypedDict):
items: list[str]
results: Annotated[list[WorkerResult], operator.add]
summary: dict[str, int | list[str]]
class ItemTask(TypedDict):
item_id: str
async def simulated_llm_eval(item_id: str) -> float:
"""Simulate an async LLM call with one deterministic failure case."""
await asyncio.sleep(0.15)
if item_id == "doc-corrupt":
raise ValueError("Invalid UTF-8 payload in upstream document")
return 0.87
def dispatch_workers(state: MapReduceState) -> list[Send]:
"""Fan out one Send task per unique item."""
unique_items = list(dict.fromkeys(state["items"]))
return [Send("evaluate_item", {"item_id": item}) for item in unique_items]
async def evaluate_item(task: ItemTask) -> dict[str, list[WorkerResult]]:
"""Execute one map worker with timeout and exception isolation."""
item_id = task["item_id"]
try:
score = await asyncio.wait_for(simulated_llm_eval(item_id), timeout=5.0)
result = WorkerResult(item_id=item_id, status="ok", score=score)
except asyncio.TimeoutError:
result = WorkerResult(
item_id=item_id,
status="error",
error_message="Worker timed out after 5.0s",
)
except Exception as exc:
result = WorkerResult(
item_id=item_id,
status="error",
error_message=str(exc),
)
return {"results": [result]}
def aggregate_results(state: MapReduceState) -> dict[str, dict[str, int | list[str]]]:
"""Reduce all worker outputs, separating successes from failed items."""
succeeded = [r.item_id for r in state["results"] if r.status == "ok"]
failed = [f"{r.item_id} ({r.error_message})" for r in state["results"] if r.status == "error"]
return {
"summary": {
"total": len(state["results"]),
"succeeded_count": len(succeeded),
"failed_items": failed,
}
}
def build_map_reduce_graph():
builder = StateGraph(MapReduceState)
builder.add_node("evaluate_item", evaluate_item)
builder.add_node("aggregate_results", aggregate_results)
builder.add_conditional_edges(START, dispatch_workers, ["evaluate_item"])
builder.add_edge("evaluate_item", "aggregate_results")
builder.add_edge("aggregate_results", END)
return builder.compile()
async def main() -> None:
graph = build_map_reduce_graph()
initial_state: MapReduceState = {
"items": ["doc-001", "doc-002", "doc-corrupt", "doc-003", "doc-004"],
"results": [],
"summary": {},
}
# Cap active concurrent Send workers at 3
output = await graph.ainvoke(initial_state, config={"max_concurrency": 3})
print("Summary:", output["summary"])
if __name__ == "__main__":
asyncio.run(main())
For broader patterns on handling partial LLM failures across multi-step pipelines, see Handling Partial Failures in GenAI Workflows and the complete LangGraph Workflow Series.
Resetting Reducer Lists Across Multi-Turn Loops
A subtle bug appears when a Send map-reduce graph runs inside a conversational loop or human-in-the-loop cycle: operator.add appends new results onto previous turns’ results instead of starting fresh for the new batch.
To clear a reduced list between cycles without breaking Send, replace operator.add with a custom reducer that recognizes a sentinel reset object:
from typing import Any
RESET_LIST = "__RESET__"
def resettable_add(left: list[Any], right: list[Any] | str) -> list[Any]:
if right == RESET_LIST:
return []
if isinstance(right, list):
return left + right
raise TypeError(f"Unsupported reducer update type: {type(right)}")
Returning {"results": RESET_LIST} from your aggregate_results node (after summarizing) clears the list cleanly before the next graph cycle. If you are pausing between cycles for user review, pair this pattern with LangGraph Human-in-the-Loop WebSockets.
Frequently Asked Questions
Why does LangGraph throw InvalidUpdateError during parallel Send execution?
By default, LangGraph state keys overwrite their previous value on each node return. When two or more parallel Send branches write to the same key in one superstep, LangGraph raises InvalidUpdateError: Can receive only one value per step. Annotate the key with a reducer like Annotated[list, operator.add] to merge outputs.
What is the difference between static parallel edges and the Send API in LangGraph?
Static parallel edges fan out to a fixed set of known node names defined at compile time. The Send API spawns a dynamic number of instances of the same worker node at runtime based on the length of a list in your graph state, making it ideal for map-reduce pipelines.
How do you limit concurrency when using Send in LangGraph?
Pass max_concurrency inside RunnableConfig, such as graph.ainvoke(inputs, config={'max_concurrency': 5}), or wrap async LLM calls inside worker nodes with a shared asyncio.Semaphore. Using both prevents overwhelming downstream LLM endpoints or database connection pools.
What happens if one parallel Send branch raises an unhandled exception?
An unhandled exception in any Send worker aborts the entire superstep and loses outputs from sibling workers that already completed. Catch exceptions inside the worker node, return a typed error record in the reduced list, and let the reducer node decide whether to retry or continue.
Want to build production-ready AI?
Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.
Written by S L Manikanta
AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.
Related Articles
Building StoxFlow: Hybrid Local/Cloud AI Agents Architecture (2026)
Build a decoupled three-tier AI stock research agent using LangGraph, FastAPI, and hybrid LLM routing (Ollama/Gemini) to cut cloud token costs by over 80%.
Fixing LangGraph RecursionLimitExceeded and State Desync in Async Multi-Agent Loops (2026)
Resolve LangGraph GraphRecursionError and RecursionLimitExceeded in production. Step-by-step solutions for infinite tool-calling loops, recursion_limit config, and async state desync.
LangGraph Complete Guide: State Management for Production AI Agents (2026)
The definitive engineering guide to LangGraph in 2026. Learn how to architect stateful, multi-actor AI workflows with persistence, human-in-the-loop, and time travel.