Parallel Agents, Handoffs and Memory in LangGraph: Send to Fan Out, Command to Hand Off, a Postgres Saver to Remember
Three LangGraph ideas in three small files: Send fans three support documents out to parallel summarisers and operator.add collects them (a fourth document needs no new graph code), Command(goto="support") lets a sales agent hand a password question to support, and PostgresSaver keeps thread customer-42 alive across two separate runs.
What you will learn
- Fan work out to parallel branches with Send and collect results with operator.add (map-reduce)
- Hand a conversation from one agent to another with Command(goto=...)
- Keep a thread's history across process restarts with PostgresSaver and a thread_id
- Start and remove the Postgres container with Docker Compose
Before you start
- LangGraph Nodes, Edges and State
- Supervisor and Worker Agents in LangGraph
So far our graphs ran one node at a time and forgot everything when the program ended. This article adds three things that real agent apps need: several agents working at the same time, a chat that can move from one agent to another, and a conversation that survives a restart. Each idea gets one numbered file in the project S01L08_ParallelAgentsHandoffs.
A small llm.py decides which model answers. Without a key in .env it returns a stand-in test model whose replies all start with "test model reply", so you always know where an answer came from. With an OPENAI_API_KEY it returns the real model, and the graph code stays the same.
Map-reduce: several chefs, one head chef
Picture a busy kitchen. Instead of one cook making every dish one after the other, several chefs cook at the same time, and a head chef plates everything together. Our dishes are three support documents: a refund policy, a shipping FAQ and a privacy note.
In 01_map_reduce.py the overall state has a summaries list annotated with operator.add, so every parallel branch appends to it instead of replacing it. Each branch gets its own small state, DocState, with just one document.
import operator
from typing import Annotated, TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
from llm import get_model
DOCUMENTS = {
"refund-policy": "Refunds are paid within 14 days. Digital goods need a reason.",
"shipping-faq": "Orders ship in 2 days. Tracking is emailed after dispatch.",
"privacy-note": "We keep chat logs for 30 days. You can ask us to delete them.",
}
class OverallState(TypedDict):
documents: dict[str, str]
summaries: Annotated[list[str], operator.add] # every parallel branch appends here
overview: str
class DocState(TypedDict):
name: str
text: str
def fan_out(state: OverallState):
# One Send per document: each runs the "summarise" node with its own small state.
return [Send("summarise", {"name": n, "text": t}) for n, t in state["documents"].items()]
def summarise(state: DocState) -> dict:
reply = get_model().invoke("SUMMARIZE: " + state["text"]).content
return {"summaries": [f"{state['name']}: {reply}"]}
def combine(state: OverallState) -> dict:
reply = get_model().invoke("COMBINE: " + " | ".join(sorted(state["summaries"]))).content
return {"overview": reply}
def build():
g = StateGraph(OverallState)
g.add_node("summarise", summarise)
g.add_node("combine", combine)
g.add_conditional_edges(START, fan_out, ["summarise"])
g.add_edge("summarise", "combine")
g.add_edge("combine", END)
return g.compile()
The conditional edge from START calls fan_out, and that is where the graph splits. summarise returns a list with one item, and the reducer joins the three lists. Every branch then flows into combine, which runs once.
The run takes about a second and prints three summaries sorted by name (privacy note, refund policy, shipping FAQ) and the overview. The stand-in model just quotes the start of each text:
privacy-note: test model reply: short summary, starts with 'We keep chat logs for 30 days'
...
overview -> test model reply: 3 documents, one overview
Now add a fourth document, a warranty card ("every device has a twelve month warranty"), to the dictionary and run again. Nothing else changes. fan_out creates four Sends instead of three, a fourth summary for warranty-card appears, and the overview says 4 documents. The fan-out grows with the data, and you wrote no new graph code.
Handoff: the agent decides where the chat goes
Next, one conversation and two agents. Every chat starts with the sales agent. If the customer writes "I forgot my password", sales finds the word "password" in its list of support words. Sales doesn't answer. It returns a Command with goto="support", and the chat moves to the support agent. A question like "How much is the Pro plan?" stays with sales.
from typing import Literal, TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
from llm import get_model
SUPPORT_WORDS = ("password", "login", "error", "reset")
class ChatState(TypedDict):
question: str
active: str
answers: list[str]
def sales(state: ChatState) -> Command[Literal["support", "__end__"]]:
q = state["question"].lower()
if any(w in q for w in SUPPORT_WORDS):
# Not a sales question: hand the conversation to the other agent.
return Command(update={"active": "support"}, goto="support")
reply = get_model().invoke("SALES: " + state["question"]).content
return Command(update={"active": "sales", "answers": state["answers"] + ["[sales] " + reply]}, goto=END)
def support(state: ChatState) -> dict:
reply = get_model().invoke("SUPPORT: " + state["question"]).content
return {"active": "support", "answers": state["answers"] + ["[support] " + reply]}
def build():
g = StateGraph(ChatState)
g.add_node("sales", sales)
g.add_node("support", support)
g.add_edge(START, "sales") # every chat starts with sales
g.add_edge("support", END)
return g.compile()
Look at what's missing: there is no edge from sales to support. The Command draws that path at run time, and the return type Command[Literal["support", "__end__"]] tells LangGraph where sales is allowed to go. A Command carries both the state update and the next node in one return value.
Running both questions through the same graph, the Pro plan question is handled by sales (the plan is billed per seat, monthly or yearly), and "I forgot my password" is handled by support, which says how to reset the password from Settings.
Command(goto=...) lets the node itself decide, which suits handoffs: the agent that read the question is the one that knows it belongs elsewhere.Memory that survives a restart
Agent state normally lives in the Python process. When the process ends, the conversation is gone. A checkpointer saves the whole state of a thread after each run, and loads it back next time the same thread_id comes in.
First we need a database. compose.yaml runs Postgres 17 from the pgvector/pgvector:pg17 image, with a database called agents, port 5440 on your machine mapped to Postgres in the container, and a named volume so the data survives a container restart. Start only the db service:
docker compose up -d db
import operator
import os
import sys
from typing import Annotated, TypedDict
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.graph import END, START, StateGraph
from llm import get_model
DB_URI = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@localhost:5440/agents?sslmode=disable")
class MemState(TypedDict):
question: str
history: Annotated[list[str], operator.add]
def answer(state: MemState) -> dict:
reply = get_model().invoke(state["question"]).content
return {"history": [f"you: {state['question']}", f"agent: {reply}"]}
def build(checkpointer):
g = StateGraph(MemState)
g.add_node("answer", answer)
g.add_edge(START, "answer")
g.add_edge("answer", END)
return g.compile(checkpointer=checkpointer)
def run(question: str, thread_id: str = "customer-42") -> list[str]:
with PostgresSaver.from_conn_string(DB_URI) as saver:
saver.setup() # creates the checkpoint tables the first time
app = build(saver)
cfg = {"configurable": {"thread_id": thread_id}}
return app.invoke({"question": question}, cfg)["history"]
Compiling with checkpointer= is the only change memory needs in the graph. setup() creates the checkpoint tables on the first run and does nothing later. The config carries the thread id, so every run with customer-42 continues the same conversation. The question comes from the command line.
First run, python 03_postgres_memory.py "My name is Priya":
you: My name is Priya
agent: test model reply: got it: My name is Priya
Second run, a brand new process with "What is my name?":
you: My name is Priya
agent: test model reply: got it: My name is Priya
you: What is my name?
agent: test model reply: got it: What is my name?
The first two lines came back from Postgres, not from the program's memory. (The stand-in model only echoes, so it doesn't actually say "Priya". A real model would, because it now sees the whole history.)
The project's tests check the map-reduce (three summaries and the overview), that each question goes to the right agent, and the Postgres thread. The Postgres test skips itself when the database isn't running. With the database up, python -m pytest -q shows 6 passed in 1.14 s. When you're done, docker compose down -v removes the container, the network and the volume, so the saved threads are gone too.
Common mistakes
- A plain list for parallel results. Without
operator.add, parallel branches overwrite each other and you keep one summary. - Adding a static edge as well as a Command. If sales returns
Command(goto=...), don't also drawsales -> support; the Command is the route. - A new thread id every run. Memory is keyed by
thread_id. Generate it once per conversation and reuse it. - Forgetting
-vmeans data stays.docker compose downkeeps the volume;down -vdeletes it. Pick on purpose.
Quick recap
| Need | LangGraph tool | In the project |
|---|---|---|
| Many agents at once | Send from a conditional edge | one summariser per document |
| Collect their results | Annotated[list, operator.add] | summaries |
| Pass the chat on | Command(update=..., goto=...) | sales to support |
| Remember across restarts | PostgresSaver + thread_id | customer-42 |
Try it yourself
Give support a way to hand the chat back: return Command[Literal["sales", "__end__"]] when the question mentions "price". Then combine ideas two and three: compile the handoff graph with the Postgres saver and check that the second question on the same thread still knows which agent was active.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.
What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.
Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.
LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.
