Detailed interpretation of LangGraph parallel node execution
📚 Overview
This document explains in detail the parallel node execution (Parallelization) mechanism in LangGraph. This is one of the core technologies for building efficient multi-agent systems, allowing multiple tasks to be executed simultaneously and greatly improving performance.
🎯 Core Concept
What is parallel execution?
In LangGraph, parallel execution refers to having multiple nodes run simultaneously within the same time step (step), rather than executing one after another in sequence. This mode is often called Fan-out (fan-out) and Fan-in (fan-in):
- Fan-out: The output of one node is distributed to multiple parallel nodes
- Fan-in: The output of multiple parallel nodes is aggregated into one node
🔧Basic example: linear execution vs parallel execution
1. Linear execution graph (Sequential)
First look at a simple linear execution example:
from typing import Any
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
state: str
class ReturnNodeValue:
def __init__(self, node_secret: str):
self._value = node_secret
def __call__(self, state: State) -> Any:
print(f"Adding {self._value} to {state['state']}")
return {"state": [self._value]}
# 构建图
builder = StateGraph(State)
builder.add_node("a", ReturnNodeValue("I'm A"))
builder.add_node("b", ReturnNodeValue("I'm B"))
builder.add_node("c", ReturnNodeValue("I'm C"))
builder.add_node("d", ReturnNodeValue("I'm D"))
# 线性流程:START → a → b → c → d → END
builder.add_edge(START, "a")
builder.add_edge("a", "b")
builder.add_edge("b", "c")
builder.add_edge("c", "d")
builder.add_edge("d", END)
graph = builder.compile()Execution result:
Adding I'm A to []
Adding I'm B to ["I'm A"]
Adding I'm C to ["I'm B"]
Adding I'm D to ["I'm C"]
{'state': ["I'm D"]}Analysis: Each node is executed in sequence, and the latter node will overwrite the status of the previous node.
2. Parallel execution graph (Parallel) - encountered a problem!
Now let's try to get b and c to execute in parallel:
builder = StateGraph(State)
builder.add_node("a", ReturnNodeValue("I'm A"))
builder.add_node("b", ReturnNodeValue("I'm B"))
builder.add_node("c", ReturnNodeValue("I'm C"))
builder.add_node("d", ReturnNodeValue("I'm D"))
# 并行流程:a 扇出到 b 和 c,然后扇入到 d
builder.add_edge(START, "a")
builder.add_edge("a", "b") # a → b
builder.add_edge("a", "c") # a → c(并行)
builder.add_edge("b", "d") # b → d
builder.add_edge("c", "d") # c → d
builder.add_edge("d", END)
graph = builder.compile()**An error will be reported when executing! **
Adding I'm A to []
Adding I'm B to ["I'm A"]
Adding I'm C to ["I'm A"]
An error occurred: At key 'state': Can receive only one value per step.
Use an Annotated key to handle multiple values.**Why is an error reported? **
Because within the same time step (step), b and c are trying to update the state key. LangGraph doesn't know how to merge these two updates, so it throws a InvalidUpdateError error.
🔑 Solution: Use Reducer
What is a Reducer?
Reducer is a function that defines how to merge multiple parallel updates. In Python, we use the Annotated type hint to specify reducers.
Python knowledge points: Annotated type hints
Annotated is a type hint tool introduced in Python 3.9+ that allows us to add metadata to types:
from typing import Annotated
import operator
# 语法:Annotated[类型, 元数据]
state: Annotated[list, operator.add]
# ^^^^^^^^ ^^^^ ^^^^^^^^^^^^^
# 关键字 类型 reducer 函数Use operator.add as Reducer
operator.add is Python’s built-in addition operator function. For lists, it performs list concatenation:
import operator
# operator.add 对列表的作用
result = operator.add([1, 2], [3, 4]) # 结果: [1, 2, 3, 4]Fixed code:
import operator
from typing import Annotated
class State(TypedDict):
# 使用 operator.add 作为 reducer,让 state 支持追加
state: Annotated[list, operator.add]
# 构建图(结构同上)
builder = StateGraph(State)
builder.add_node("a", ReturnNodeValue("I'm A"))
builder.add_node("b", ReturnNodeValue("I'm B"))
builder.add_node("c", ReturnNodeValue("I'm C"))
builder.add_node("d", ReturnNodeValue("I'm D"))
builder.add_edge(START, "a")
builder.add_edge("a", "b")
builder.add_edge("a", "c")
builder.add_edge("b", "d")
builder.add_edge("c", "d")
builder.add_edge("d", END)
graph = builder.compile()Execution result:
Adding I'm A to []
Adding I'm B to ["I'm A"]
Adding I'm C to ["I'm A"]
Adding I'm D to ["I'm A", "I'm B", "I'm C"]
{'state': ["I'm A", "I'm B", "I'm C", "I'm D"]}**✅ Success! ** Updates to b and c are now preserved and their results are spliced into the state list.
⏳ Wait for the parallel node to complete
Parallel paths of different lengths
What happens when parallel paths are of different lengths?
builder = StateGraph(State)
builder.add_node("a", ReturnNodeValue("I'm A"))
builder.add_node("b", ReturnNodeValue("I'm B"))
builder.add_node("b2", ReturnNodeValue("I'm B2")) # b 路径的额外节点
builder.add_node("c", ReturnNodeValue("I'm C"))
builder.add_node("d", ReturnNodeValue("I'm D"))
builder.add_edge(START, "a")
builder.add_edge("a", "b")
builder.add_edge("a", "c")
builder.add_edge("b", "b2") # b → b2(更长的路径)
builder.add_edge(["b2", "c"], "d") # 等待 b2 和 c 都完成
builder.add_edge("d", END)
graph = builder.compile()Execution result:
Adding I'm A to []
Adding I'm B to ["I'm A"]
Adding I'm C to ["I'm A"]
Adding I'm B2 to ["I'm A", "I'm B", "I'm C"]
Adding I'm D to ["I'm A", "I'm B", "I'm C", "I'm B2"]Key Points:
b,b2andcall belong to the same execution step (step)**- Although
ccompletes first, the graph will wait forb2to also complete before entering thednode - This is LangGraph's automatic synchronization mechanism
🎨 Control the order of status updates
Problem: The default order is uncontrollable
In the above example, although they are all the same step, the order of status updates is: ["I'm A", "I'm B", "I'm C", "I'm B2"]
Note that "I'm C" appears before "I'm B2", even though b2 is the successor of b.
Reason: LangGraph determines the update order based on the topology of the graph, which we cannot directly control.
Solution: Custom Reducer
We can write a custom reducer to sort status updates:
def sorting_reducer(left, right):
"""合并并排序列表中的值"""
# 确保 left 是列表
if not isinstance(left, list):
left = [left]
# 确保 right 是列表
if not isinstance(right, list):
right = [right]
# 合并并排序
return sorted(left + right, reverse=False)
class State(TypedDict):
# 使用自定义的 sorting_reducer
state: Annotated[list, sorting_reducer]Execution result:
Adding I'm A to []
Adding I'm B to ["I'm A"]
Adding I'm C to ["I'm A"]
Adding I'm B2 to ["I'm A", "I'm B", "I'm C"]
Adding I'm D to ["I'm A", "I'm B", "I'm B2", "I'm C"]
{'state': ["I'm A", "I'm B", "I'm B2", "I'm C", "I'm D"]}NOTE: The order now becomes ["I'm A", "I'm B", "I'm B2", "I'm C", "I'm D"], in alphabetical order!
🔍 Detailed explanation of Reducer function
How custom reducers work:
def sorting_reducer(left, right):
# left: 当前状态的值
# right: 新节点返回的值
# 1. 标准化为列表
if not isinstance(left, list):
left = [left]
if not isinstance(right, list):
right = [right]
# 2. 合并并处理(这里是排序)
return sorted(left + right, reverse=False)Other reducer examples:
# 只保留最新的 N 个值
def keep_last_n(n=5):
def reducer(left, right):
combined = (left if isinstance(left, list) else [left]) + \
(right if isinstance(right, list) else [right])
return combined[-n:]
return reducer
# 去重
def unique_reducer(left, right):
combined = (left if isinstance(left, list) else [left]) + \
(right if isinstance(right, list) else [right])
return list(dict.fromkeys(combined)) # 保持顺序的去重🤖 Practical case: parallel retrieval to generate answers
Scene
We are going to build a question answering system that gets information from two sources simultaneously:
- Wikipedia - Get encyclopedic knowledge
- Web Search (Tavily) - Get the latest network information
The LLM is then asked to generate an answer based on this information.
State definition
import operator
from typing import Annotated
from typing_extensions import TypedDict
class State(TypedDict):
question: str # 用户问题
answer: str # 生成的答案
context: Annotated[list, operator.add] # 检索到的上下文(支持并行追加)Key Points:
contextusesoperator.addas reducer, allowing two retrieval nodes to write in parallel
Node implementation
1. Web search node
from langchain_community.tools import TavilySearchResults
def search_web(state):
"""从网络搜索获取文档"""
# 使用 Tavily 搜索
tavily_search = TavilySearchResults(max_results=3)
search_docs = tavily_search.invoke(state['question'])
# 格式化搜索结果
formatted_search_docs = "\n\n---\n\n".join(
[
f'<Document href="{doc["url"]}">\n{doc["content"]}\n</Document>'
for doc in search_docs
]
)
return {"context": [formatted_search_docs]}Knowledge points:
- Return
{"context": [formatted_search_docs]}, note that the value ofcontextis a list - This way
operator.addcan be spliced into an existing context
2. Wikipedia search node
from langchain_community.document_loaders import WikipediaLoader
def search_wikipedia(state):
"""从 Wikipedia 获取文档"""
# 搜索 Wikipedia
search_docs = WikipediaLoader(
query=state['question'],
load_max_docs=2
).load()
# 格式化搜索结果
formatted_search_docs = "\n\n---\n\n".join(
[
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}">\n{doc.page_content}\n</Document>'
for doc in search_docs
]
)
return {"context": [formatted_search_docs]}3. Generate answer nodes
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
llm = ChatOpenAI(model="gpt-4o", temperature=0)
def generate_answer(state):
"""基于上下文生成答案"""
# 获取状态
context = state["context"]
question = state["question"]
# 构建提示词
answer_template = """Answer the question {question} using this context: {context}"""
answer_instructions = answer_template.format(
question=question,
context=context
)
# 调用 LLM 生成答案
answer = llm.invoke([
SystemMessage(content=answer_instructions),
HumanMessage(content="Answer the question.")
])
return {"answer": answer}Build parallel graph
from langgraph.graph import StateGraph, START, END
builder = StateGraph(State)
# 添加节点
builder.add_node("search_web", search_web)
builder.add_node("search_wikipedia", search_wikipedia)
builder.add_node("generate_answer", generate_answer)
# 并行流程
builder.add_edge(START, "search_wikipedia") # START → search_wikipedia
builder.add_edge(START, "search_web") # START → search_web(并行)
builder.add_edge("search_wikipedia", "generate_answer") # 汇聚
builder.add_edge("search_web", "generate_answer") # 汇聚
builder.add_edge("generate_answer", END)
graph = builder.compile()Flowchart:
START
/ \
/ \
search_web search_wikipedia
\ /
\ /
generate_answer
|
ENDExecute query
result = graph.invoke({
"question": "How were Nvidia's Q2 2024 earnings"
})
print(result['answer'].content)Example output:
Nvidia's Q2 2024 earnings were strong, showcasing record revenue and a robust
performance in its data center division. The company reported revenue of $30.0
billion, which was up 15% from the previous quarter and up 122% from a year ago.
GAAP earnings per diluted share were $0.67, up 12% from the previous quarter and
up 168% from a year ago, while non-GAAP earnings per diluted share were $0.68...🎓 Summary of core knowledge points
LangGraph-specific concepts
Parallel Execution Mode
- Fan-out: One node fans out to multiple nodes
- Fan-in: multiple nodes converge into one node
Reducer mechanism
- A reducer must be used to handle parallel updates to the same state key
operator.addfor list splicing- You can customize reducer to control merging logic
Execution Step
- Parallel nodes are executed in the same step
- The graph will wait for all parallel paths to complete before proceeding to the next step
Status update sequence
- The default order is determined by LangGraph based on the graph topology
- The order can be controlled through custom reducer
Python-specific knowledge points
TypedDictpythonfrom typing_extensions import TypedDict class State(TypedDict): field1: str field2: intType structure used to define dictionaries
AnnotatedType Tippythonfrom typing import Annotated # 语法:Annotated[类型, 元数据...] field: Annotated[list, operator.add]Add additional metadata to types
operator.addpythonimport operator # 对列表执行拼接 operator.add([1, 2], [3, 4]) # [1, 2, 3, 4]Callable Class
pythonclass ReturnNodeValue: def __init__(self, value): self._value = value def __call__(self, state): # 实现 __call__ 方法 return {"state": [self._value]}Implement the
__call__method so that the object can be called like a function
💡 Best Practices
1. When to use parallel execution?
✅ Applicable scenarios:
- Search multiple independent data sources (such as querying databases, APIs, and search engines simultaneously)
- Multiple independent processing tasks (such as simultaneous text classification, entity extraction, sentiment analysis)
- Scenarios that require multiple Agents to work at the same time
❌ Not applicable scenarios:
- There are dependencies between tasks
- Requires strict execution order
- Limited resources (such as API call limits)
2. Reducer Selection Guide
| Scenario | Reducer | Description |
|---|---|---|
| Collect all results | operator.add | Splice all updates |
| Sorting required | Customized sorting_reducer | Sorting after merging |
| Remove duplicates | Customize unique_reducer | Only keep unique values |
| Only keep the latest | Customize lambda left, right: right | Overwrite mode |
| Keep the latest N | Custom keep_last_n | Sliding window |
3. State design suggestions
class State(TypedDict):
# 输入字段(不会被并行更新)
question: str
# 并行收集的数据(使用 reducer)
search_results: Annotated[list, operator.add]
# 最终输出(单一节点更新)
answer: str🚀 Advanced skills
Stable Sorting
For scenarios that require precise control of the order, you can use the "temporary field + sink node" mode:
class State(TypedDict):
question: str
temp_results: dict # 临时存储并行结果
final_results: list # 排序后的最终结果
def collect_results(state):
"""汇聚节点:合并并排序临时结果"""
results = state['temp_results']
# 按自定义顺序排序
ordered = [results['source1'], results['source2'], results['source3']]
return {"final_results": ordered, "temp_results": {}} # 清空临时字段For details, see Official Document
📖 Further reading
- LangGraph Parallel Execution Official Document
- LangGraph State and Reducer detailed explanation
- Python
typingmodule documentation
Summary: Parallel execution is a powerful feature of LangGraph. Through the reasonable use of reducers and graph structure design, efficient multi-task and multi-agent systems can be built. Mastering this concept is a critical step into advanced LangGraph development!