LangGraph supports parallel execution through Fan-out (one node triggering multiple downstream nodes) and Fan-in (multiple nodes converging into a single downstream node).
To implement this:
- Fan-out: Add multiple outgoing edges from a single node to different target nodes. LangGraph will trigger these nodes concurrently.
- Fan-in: Connect multiple nodes to the same downstream node. This downstream node acts as a synchronization point, waiting for all incoming parallel branches to complete before executing.
- State Management: Use a
Reducer (e.g., operator.add) in your TypedDict state definition to ensure that updates from concurrent branches are correctly merged rather than overwritten.
import operator
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
# Use operator.add to merge results from parallel branches
class ParallelState(TypedDict):
aggregate: Annotated[list, operator.add]
def node_a(state: ParallelState):
return {"aggregate": ["A"]}
def node_b(state: ParallelState):
return {"aggregate": ["B"]}
def node_c(state: ParallelState):
return {"aggregate": ["C"]}
def node_d(state: ParallelState):
return {"aggregate": ["D"]}
builder = StateGraph(ParallelState)
builder.add_node("node_a", node_a)
builder.add_node("node_b", node_b)
builder.add_node("node_c", node_c)
builder.add_node("node_d", node_d)
# Fan-out: node_a triggers node_b and node_c concurrently
builder.add_edge(START, "node_a")
builder.add_edge("node_a", "node_b")
builder.add_edge("node_a", "node_c")
# Fan-in: node_d waits for both node_b and node_c
builder.add_edge("node_b", "node_d")
builder.add_edge("node_c", "node_d")
builder.add_edge("node_d", END)
parallel_graph = builder.compile()