How LangGraph State and Reducers Handle Concurrent Updates
This hands-on explainer, tested with @langchain/langgraph 1.6.0, shows how LangGraph separates state schemas from reducers: nodes return updates instead of directly modifying shared state. Runnable examples cover default overwriting, custom accumulation, concurrent-write errors, merging and deleting messages by ID, forced overwrites, and input/output schemas. The author notes that merge ordering observed in simple graphs follows task-path and node-name sorting, but says the official documentation does not guarantee this behavior. The article also warns that input and output schemas filter invoke results but not streamed state values.
Reducers provide explicit rules for combining concurrent updates, exposing invalid parallel writes instead of silently losing data. Message-ID merging also gives agents a unified way to append, replace, and delete history entries.
State 与 Reducer:一本谁都能写的账本,怎么不打架
上一篇我们把 20 行 while 循环和 LangGraph 版逐行对了一遍,结尾留了个问题: 节点只
return { messages: [新消息] },为什么最后历史里是 7 条而不是 1 条?谁把它们拼起来的? 这一篇拆 L1 状态层。主角两个:State(账本长什么样)和 Reducer(新写的内容怎么记进账本)。
兄弟们,先回忆一下 while 循环里的状态是怎么管的:
const res = await model.invoke(messages);
messages.push(res);
// ...
messages.push(...results);
一个数组,谁要写就 push。简单粗暴,而且从来没出过问题。
为什么没出问题?因为整个循环只有一个人在写。