Subgraphs — reusable graph components
Overview
As agentic AI applications grow, their workflows become increasingly difficult to manage inside a single graph. A production customer support system might classify tickets, retrieve customer information, investigate billing issues, search technical documentation, generate responses, validate policies, and request human approval.
Each responsibility may itself require multiple nodes, conditional transitions, retries, tool calls, and reasoning loops.
Although LangGraph allows you to place all these operations inside one StateGraph, doing so eventually produces a large, tightly coupled workflow that is difficult to understand, maintain, and extend.
Subgraphs provide a mechanism for composing smaller workflows into larger workflows.
A subgraph is a compiled LangGraph graph used as a component within another graph. The enclosing graph is called the parent graph, while the embedded graph is called the child graph or subgraph.
From the parent’s perspective, the child graph can appear as a single node. Internally, however, that node may execute an entire multi-step workflow.
In the previous lesson, you built a research, writing, and review team. Imagine extending that system so that the research team performs query generation, document retrieval, source validation, and evidence synthesis. Rather than exposing every research operation in the main workflow, you could encapsulate them inside a dedicated research subgraph.
This lesson begins the transition from implementing individual agent workflows to designing modular agentic applications.
The following diagram illustrates a customer support workflow containing an investigation subgraph.
The parent graph coordinates the overall business process, while the investigation component owns the internal sequence of investigative operations.
Environment setup
Use Python 3.11 or later and install LangGraph 1.x with support for version 2 streaming.
python -m pip install -U "langgraph>=1.1,<2"The examples in this lesson deliberately use deterministic Python functions instead of external LLM calls. This allows you to concentrate on graph composition without introducing model variability, API credentials, or network costs.
The examples follow the current documented LangGraph 1.x interfaces. Their expected outputs are derived from the code; execution was not independently verified in an installed LangGraph environment.
Why subgraphs?
The limitations of monolithic graphs
Consider an enterprise support application that contains fifty nodes.
Some nodes implement billing operations, others handle technical troubleshooting, and several perform compliance checks. All nodes are registered in the same graph builder, and their transitions are defined together.
Initially, this design may be manageable. Over time, however, several architectural problems emerge:
- Changes to billing logic require navigating unrelated technical support code.
- Different teams modify the same graph construction module.
- Internal implementation details become visible throughout the application.
- Reusing an existing workflow requires copying nodes and transitions.
- Testing a specific business capability becomes unnecessarily complicated.
- Understanding the overall workflow requires inspecting implementation details.
These problems are fundamentally related to software architecture rather than artificial intelligence.
Traditional software addresses similar problems through functions, classes, packages, and modular services. LangGraph subgraphs apply modularity at the workflow level.
Benefits of modular graph architecture
Reusability: A compiled identity verification graph can be embedded in customer support, account recovery, and onboarding workflows.
Encapsulation: The parent graph does not need to understand how the verification component performs document validation or fraud checks.
Separation of concerns: Each graph owns a specific business capability rather than an arbitrary collection of operations.
Independent development: Different engineering teams can maintain separate graph components while agreeing on their state contracts.
Testability: A child graph can be invoked independently with controlled input before being integrated into the parent.
Observability: Internal operations remain graph operations that can be inspected through nested streaming and tracing.
Subgraphs also allow the parent workflow to remain focused on business orchestration rather than implementation details.
Functions, subgraphs, and services
Not every reusable operation should become a subgraph.
| Characteristic | Ordinary node | Subgraph | Separate service |
|---|---|---|---|
| Primary purpose | Individual operation | Multi-step workflow | Independent service capability |
| Internal graph transitions | No | Yes | Implementation-dependent |
| Execution boundary | Node | Nested graph | Network or process boundary |
| Independent invocation | Python function | Compiled graph | Service API |
| Separate deployment required | No | No | Typically |
| Implementation complexity | Low | Moderate | Higher |
| Typical use case | Validate input | Investigate ticket | External billing platform |
Use an ordinary function when the operation is naturally atomic. Use a subgraph when the component needs its own sequence, branching, loops, or graph-level behavior.
A subgraph is not automatically a microservice. It normally executes within the same application runtime as its parent. If independent scaling, process isolation, or separate deployment is required, an external service may be a more appropriate boundary.
Shared state: add the subgraph directly
The simplest composition pattern uses compatible state fields in both graphs.
LangGraph supports registering a compiled graph directly through the normal add_node() method.
parent_builder.add_node("investigation", compiled_subgraph)There is no special add_subgraph() method required.
The child must be compiled before registration, and the parent must subsequently be compiled before execution.
Understanding the shared state contract
Suppose a child graph declares these fields:
ticket: the customer’s original request.category: the classification result.findings: the investigation result.
The parent graph declares those same fields along with additional fields such as customer_id and response.
The overlapping fields form the communication contract between the two graphs.
When the child executes, it receives the applicable input fields from the parent. When it completes, its output fields that correspond to parent channels are applied to the parent’s state.
This is not equivalent to passing around one globally mutable Python dictionary. Each compiled graph maintains its own execution state and channel behavior. Communication occurs through graph inputs and outputs.
Identical state schemas are therefore convenient but not required. Compatible overlapping input and output fields are sufficient for direct composition.
Example 1: Build and embed an investigation subgraph
The following example creates a two-node investigation workflow and embeds it directly into a customer support graph.
The child classifies a ticket and generates findings. The parent then prepares the final customer response.
from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class InvestigationState(TypedDict):
ticket: str
category: NotRequired[str]
findings: NotRequired[str]
class SupportState(InvestigationState):
customer_id: str
response: NotRequired[str]
def classify(state: InvestigationState):
text = state["ticket"].lower()
if "charged" in text or "payment" in text:
category = "billing"
else:
category = "technical"
return {"category": category}
def investigate(state: InvestigationState):
if state["category"] == "billing":
findings = "Possible duplicate payment detected."
else:
findings = "Technical diagnostics required."
return {"findings": findings}
def build_investigation_graph():
builder = StateGraph(InvestigationState)
builder.add_node("classify", classify)
builder.add_node("investigate", investigate)
builder.add_edge(START, "classify")
builder.add_edge("classify", "investigate")
builder.add_edge("investigate", END)
return builder.compile()
investigation_graph = build_investigation_graph()
def prepare_response(state: SupportState):
return {
"response": (
f"Customer {state['customer_id']}: "
f"{state['findings']}"
)
}
parent_builder = StateGraph(SupportState)
parent_builder.add_node(
"investigation",
investigation_graph,
)
parent_builder.add_node(
"prepare_response",
prepare_response,
)
parent_builder.add_edge(START, "investigation")
parent_builder.add_edge(
"investigation",
"prepare_response",
)
parent_builder.add_edge("prepare_response", END)
support_graph = parent_builder.compile()
result = support_graph.invoke({
"customer_id": "C1001",
"ticket": "I was charged twice."
})
print(result)Expected output, formatted for readability:
{
"ticket": "I was charged twice.",
"category": "billing",
"findings": "Possible duplicate payment detected.",
"customer_id": "C1001",
"response": "Customer C1001: Possible duplicate payment detected."
}The investigation functions are illustrative business rules, not a real payment investigation system.
Step-by-step walkthrough
Step 1 — Define the child interface.
InvestigationState declares the information needed and produced by the investigation workflow.
The NotRequired annotation indicates that derived fields do not have to exist in the initial input. They are populated as execution progresses.
Step 2 — Define the parent interface.
SupportState inherits the investigation fields and introduces customer_id and response.
Inheritance reduces duplication, although independently defined schemas with compatible fields would also work.
Step 3 — Compile the child graph.
The build_investigation_graph() function constructs and compiles the investigation workflow. Its return value is an executable graph rather than an unfinished builder.
Step 4 — Register the compiled child.
The parent registers the compiled graph under the node name investigation. It does not individually register classify or investigate.
Step 5 — Execute the parent.
The parent receives a ticket, delegates investigation, receives the resulting state, and continues to response preparation.
Notice that customer_id remains available to the parent even though the child schema does not declare it.
Note: A
TypedDictdescribes a state contract for developers and type checkers; it does not provide comprehensive runtime validation. Validate untrusted application input at appropriate boundaries.
Reusing compiled graph components
The build_investigation_graph() factory also makes the component reusable.
You could import it into an email support graph, a live-chat graph, or an internal support automation workflow. Each parent can define different operations before and after investigation.
A useful architectural principle is to keep child graphs independent of their callers. The investigation component should not contain assumptions about whether its input originated from an email, a website, or a mobile application.
The official LangGraph subgraphs guide documents direct registration and explicit state transformation as the two principal composition patterns.
Nested graph execution
What happens internally?
LangGraph executes graph operations using its Pregel-inspired runtime, which organizes execution into super-steps.
During a super-step, scheduled nodes receive state derived from the available channels. Their updates are applied according to channel rules before subsequent dependent operations execute.
When a scheduled parent node is itself a compiled graph, that graph runs its own internal execution sequence.
For the previous example, the execution order is:
- The parent initializes its state from the invocation input.
- The parent schedules the
investigationnode. - The investigation graph receives its applicable input fields.
- The child executes
classify. - The child’s category channel is updated.
- The child executes
investigate. - The child reaches completion and produces its output.
- Compatible output fields are applied to parent channels.
- The parent executes
prepare_response. - The parent completes and returns its final state.
The child has its own internal scheduling boundaries. The parent does not treat every internal child node as a separate parent node.
This distinction matters when designing dependencies, parallel execution, and failure handling.
Parent and child execution boundaries
Under normal completion, a downstream parent node connected to a subgraph cannot begin until the subgraph has finished.
If the parent has independent parallel branches, those branches may execute concurrently with the subgraph. However, the parent’s next dependent super-step must respect the relevant completion and synchronization requirements.
Similarly, reaching END inside a child graph does not terminate the entire application. It completes that child invocation and returns control to the parent.
A child can itself contain another child graph, allowing several levels of composition.
The following diagram shows three nested architectural levels.
Avoid excessive nesting merely for architectural appearance. Introduce another graph boundary when it represents a meaningful responsibility.
Example 2: Observe nested execution with streaming
A normal invocation returns the final output. During debugging, you often need to see which internal child nodes executed and what they produced.
The subgraphs=True option enables nested events when streaming the parent graph.
This standalone example also demonstrates that a child can maintain internal fields that do not exist in the parent.
from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class ChildState(TypedDict):
question: str
evidence: NotRequired[str]
answer: NotRequired[str]
class ParentState(TypedDict):
question: str
answer: NotRequired[str]
def retrieve(state: ChildState):
return {
"evidence": "Refund processing takes 5 business days."
}
def compose(state: ChildState):
return {
"answer": state["evidence"]
}
child = (
StateGraph(ChildState)
.add_node("retrieve", retrieve)
.add_node("compose", compose)
.add_edge(START, "retrieve")
.add_edge("retrieve", "compose")
.add_edge("compose", END)
.compile()
)
parent = (
StateGraph(ParentState)
.add_node("knowledge_lookup", child)
.add_edge(START, "knowledge_lookup")
.add_edge("knowledge_lookup", END)
.compile()
)
inputs = {
"question": "When will my refund arrive?"
}
for chunk in parent.stream(
inputs,
stream_mode="updates",
subgraphs=True,
version="v2",
):
namespace = chunk["ns"]
location = (
" > ".join(
part.split(":", 1)[0]
for part in namespace
)
if namespace
else "parent"
)
print(location, chunk["data"])
result = parent.invoke(inputs)
assert "evidence" not in result
print("Final answer:", result["answer"])Representative output:
knowledge_lookup {'retrieve': {'evidence': 'Refund processing takes 5 business days.'}}
knowledge_lookup {'compose': {'answer': 'Refund processing takes 5 business days.'}}
parent {'knowledge_lookup': {...}}
Final answer: Refund processing takes 5 business days.The parent update is abbreviated because it may contain additional shared output fields.
With version 2 streaming, each chunk provides:
| Field | Purpose |
|---|---|
chunk["type"] |
Identifies the stream mode |
chunk["ns"] |
Identifies the execution namespace |
chunk["data"] |
Contains the event payload |
The root graph uses an empty namespace tuple. Nested executions have namespace entries containing node names and runtime task identifiers.
The example removes task identifiers to make the console output readable. In production observability systems, retain full namespaces when distinguishing concurrent executions.
See the official LangGraph streaming documentation for additional stream modes.
Managing shared state correctly
Shared reducers and accumulated values
A state contract includes more than field names and Python types. It also includes the meaning of each field and how updates are merged.
Consider a shared field declared as:
from typing import Annotated, TypedDict
import operator
class State(TypedDict):
audit_log: Annotated[list[str], operator.add]The reducer concatenates an incoming list with the existing list.
This is appropriate when ordinary nodes return only newly created audit entries. However, a compiled child graph may return its accumulated output state, including values it originally received from the parent.
Suppose the parent’s audit log contains:
["Ticket received"]The child appends an investigation entry and returns:
["Ticket received", "Investigation completed"]If the parent applies list concatenation to that complete output, the resulting list becomes:
[
"Ticket received",
"Ticket received",
"Investigation completed"
]The original entry is duplicated because an accumulated snapshot was treated as an incremental update.
Possible solutions include using replacement semantics for snapshot fields, separating accumulated input from incremental output, implementing an appropriate deduplicating reducer, or using a wrapper that returns only newly generated entries.
Reducers must be designed for the communication contract rather than selected simply because a field contains a list.
Sharing conversation messages
Agentic applications frequently share conversation history through MessagesState and the add_messages reducer.
from typing import NotRequired
from langgraph.graph import MessagesState
class AgentState(MessagesState):
category: NotRequired[str]Unlike ordinary list concatenation, add_messages merges messages using message identifiers. Existing messages with matching IDs can be updated rather than blindly appended.
This is useful when multiple graph components contribute to a conversation.
Nevertheless, sharing all messages is not always desirable. A specialist may produce tool results, internal reasoning-related content, or intermediate messages that should not enter the main conversation.
Preserve appropriate message IDs, define which messages cross component boundaries, and avoid exposing unnecessary internal content.
The Graph API documentation provides further details on channel and reducer semantics.
When the schemas differ
Direct registration does not require every state field to be identical.
There are three important situations:
| State relationship | Integration approach |
|---|---|
| Identical schemas | Register the compiled child directly |
| Compatible shared fields | Register directly and use child-local fields where needed |
| Different field names or representations | Invoke the child inside a wrapper node |
For example, the parent may represent a customer’s request using a ticket field, while a specialist retrieval graph expects a query field.
Similarly, the child might return retrieved_text, while the parent expects findings.
LangGraph does not automatically infer that these differently named fields represent equivalent business information.
A wrapper node makes the transformation explicit.
Example 3: Connect incompatible state schemas
The following example builds a retrieval component whose state fields are completely independent of its parent’s fields.
from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class RetrievalState(TypedDict):
query: str
retrieved_text: NotRequired[str]
class SupportState(TypedDict):
ticket: str
findings: NotRequired[str]
def retrieve(state: RetrievalState):
query = state["query"].lower()
if "password" in query:
text = "Use the password reset page."
else:
text = "Contact the support team."
return {"retrieved_text": text}
retrieval_graph = (
StateGraph(RetrievalState)
.add_node("retrieve", retrieve)
.add_edge(START, "retrieve")
.add_edge("retrieve", END)
.compile()
)
def call_retrieval(state: SupportState):
child_input = {
"query": state["ticket"]
}
child_output = retrieval_graph.invoke(
child_input
)
return {
"findings": child_output["retrieved_text"]
}
support_graph = (
StateGraph(SupportState)
.add_node("retrieval", call_retrieval)
.add_edge(START, "retrieval")
.add_edge("retrieval", END)
.compile()
)
result = support_graph.invoke({
"ticket": "I forgot my password."
})
print(result)Expected output:
{
"ticket": "I forgot my password.",
"findings": "Use the password reset page."
}The wrapper performs two transformations:
- Converts parent state into the child’s input contract.
- Converts child output into an appropriate parent update.
Unlike direct registration, the parent registers the wrapper function rather than the compiled graph object itself.
Wrappers introduce additional mapping code, but they provide greater control over information exchange and reduce coupling between independently designed components.
The next lesson explores this integration pattern in depth, including private message histories and more sophisticated communication contracts.
Production considerations
Persistence boundaries
Graph composition and persistence are separate architectural concerns.
Embedding a child graph does not automatically give it independent durable memory.
By default, a child compiled using compile() can inherit the parent’s checkpointer when one is configured. Its internal state starts fresh for each new child invocation while checkpointing can support recovery within that invocation.
The principal child compilation modes are:
| Configuration | Intended behavior |
|---|---|
compile() |
Per-invocation persistence when inherited |
compile(checkpointer=True) |
Persistent child state across calls within a thread |
compile(checkpointer=False) |
Disable child checkpointing |
Persistence-enabled composition requires appropriate parent checkpointing configuration.
For example, a production billing specialist may need to pause for approval during an investigation. Another specialist may intentionally start fresh every time it receives a request.
These are different memory requirements, not different graph composition mechanisms.
The dedicated lesson on subgraph persistence and testing will address checkpoint namespaces, recovery, interruptions, and state inspection.
Organizing an enterprise application
A modular customer support application could use the following package structure:
support_system/
__init__.py
state.py
graph.py
subgraphs/
__init__.py
classification.py
billing.py
technical.py
compliance.py
tests/
test_classification.py
test_billing.py
test_technical.py
test_integration.pyEach subgraph module exposes a graph factory and an explicit state contract.
The parent imports these components and defines the business-level transitions between them. The implementation of an individual specialist remains within its own module.
This organization allows teams to change internal child topology without rewriting the parent, provided the public state contract remains compatible.
Tip: Treat a subgraph’s shared state fields as a public API. Changing their names, types, reducer behavior, or business meaning can break every parent graph that consumes the component.
Testing individual components
One immediate advantage of subgraphs is that you do not need to execute the complete parent workflow to verify a component.
For instance, the investigation graph from Example 1 can be invoked directly with a ticket. An assertion can verify the expected category without requiring a customer identifier or executing response preparation.
At the integration level, verify that parent-only fields survive child execution and that the child returns the values required by downstream nodes.
Keeping deterministic graph construction separate from external dependencies also makes it easier to introduce mock retrieval systems, test databases, and controlled model responses later.
Common mistakes and best practices
| Common mistake | Recommended practice |
|---|---|
| Registering an uncompiled builder | Compile the child before adding it as a node |
| Assuming field names are mapped automatically | Declare compatible fields or introduce a wrapper |
| Giving every child the entire application state | Define the smallest useful state contract |
| Mutating state dictionaries directly | Return explicit state updates |
| Ignoring reducer behavior at graph boundaries | Distinguish complete snapshots from incremental updates |
| Compiling graphs repeatedly inside executing nodes | Construct and reuse compiled components |
| Assuming subgraphs provide security isolation | Enforce access controls and data boundaries explicitly |
| Creating deeply nested graphs for simple operations | Introduce graph boundaries around meaningful workflows |
Another important distinction concerns data visibility. Child-local fields are useful for encapsulation, but they are not a security guarantee.
Internal information may still appear in nested streaming events, traces, checkpoints, or application logs. Sensitive information must be protected through deliberate redaction, access control, and data retention policies.
Likewise, graph boundaries do not make external side effects atomic. If a child performs a payment operation and a later node fails, the earlier payment is not automatically reversed. Production workflows still require idempotency, appropriate retry policies, and compensation mechanisms.
Preparing for modular enterprise support
The research, writing, and review team from the previous lesson demonstrated how specialized agents cooperate within a workflow. Subgraphs now give each specialization an architectural boundary of its own.
In the chapter’s enterprise customer support project, the parent graph will coordinate ticket intake, classification, specialist selection, compliance checks, and response delivery.
Billing and technical specialists will be implemented as reusable graph components, each containing its own business logic and internal execution flow.
The shared-state pattern introduced here is particularly effective when components participate in the same business process and exchange a stable set of fields.
However, production specialists often need separate conversation histories, different data representations, restricted information access, and independent internal state.
The next lesson, Subgraphs with different state and communication between graphs, extends this architecture by exploring explicit state transformation and controlled information exchange between independently designed graph components.
Build a reusable ticket assessment subgraph
Create a two-node subgraph that classifies customer support tickets and assigns their priority. Embed the same compiled subgraph directly into two different parent graphs representing email and chat support channels. Verify that both parent graphs receive the classification and priority while preserving their channel-specific state.
from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class AssessmentState(TypedDict):
ticket: str
category: NotRequired[str]
priority: NotRequired[str]
class SupportState(AssessmentState):
channel: NotRequired[str]
def classify_ticket(state: AssessmentState):
# TODO: Return billing, technical, or general.
raise NotImplementedError
def assign_priority(state: AssessmentState):
# TODO: Return high for urgent or outage tickets.
# Otherwise, return normal.
raise NotImplementedError
def build_assessment_graph():
# TODO: Connect classification and priority assignment.
# Return a compiled subgraph.
raise NotImplementedError
def build_support_graph(channel: str, assessment):
def set_channel(state: SupportState):
return {"channel": channel}
# TODO: Build a parent graph that first sets the channel
# and then executes the compiled assessment subgraph.
raise NotImplementedError
assessment = build_assessment_graph()
email_graph = build_support_graph("email", assessment)
chat_graph = build_support_graph("chat", assessment)
email_result = email_graph.invoke({
"ticket": "Urgent: I was charged twice."
})
chat_result = chat_graph.invoke({
"ticket": "The application has an outage."
})
print(email_result)
print(chat_result)
assert email_result["category"] == "billing"
assert email_result["priority"] == "high"
assert email_result["channel"] == "email"
assert chat_result["category"] == "technical"
assert chat_result["priority"] == "high"
assert chat_result["channel"] == "chat"from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class AssessmentState(TypedDict):
ticket: str
category: NotRequired[str]
priority: NotRequired[str]
class SupportState(AssessmentState):
channel: NotRequired[str]
def classify_ticket(state: AssessmentState):
text = state["ticket"].lower()
if any(word in text for word in [
"charged", "payment", "invoice", "refund"
]):
category = "billing"
elif any(word in text for word in [
"error", "outage", "crash", "application"
]):
category = "technical"
else:
category = "general"
return {"category": category}
def assign_priority(state: AssessmentState):
text = state["ticket"].lower()
priority = (
"high"
if "urgent" in text or "outage" in text
else "normal"
)
return {"priority": priority}
def build_assessment_graph():
builder = StateGraph(AssessmentState)
builder.add_node("classify_ticket", classify_ticket)
builder.add_node("assign_priority", assign_priority)
builder.add_edge(START, "classify_ticket")
builder.add_edge("classify_ticket", "assign_priority")
builder.add_edge("assign_priority", END)
return builder.compile()
def build_support_graph(channel: str, assessment):
def set_channel(state: SupportState):
return {"channel": channel}
builder = StateGraph(SupportState)
builder.add_node("set_channel", set_channel)
builder.add_node("assessment", assessment)
builder.add_edge(START, "set_channel")
builder.add_edge("set_channel", "assessment")
builder.add_edge("assessment", END)
return builder.compile()
assessment = build_assessment_graph()
email_graph = build_support_graph("email", assessment)
chat_graph = build_support_graph("chat", assessment)
email_result = email_graph.invoke({
"ticket": "Urgent: I was charged twice."
})
chat_result = chat_graph.invoke({
"ticket": "The application has an outage."
})
print(email_result)
print(chat_result)
assert email_result["category"] == "billing"
assert email_result["priority"] == "high"
assert email_result["channel"] == "email"
assert chat_result["category"] == "technical"
assert chat_result["priority"] == "high"
assert chat_result["channel"] == "chat"
print("All tests passed.")Summary
- A subgraph is a compiled LangGraph graph registered as a node within another graph.
- Subgraphs encapsulate multi-step workflows behind reusable and well-defined state interfaces.
- Parent and child graphs can communicate automatically through compatible shared state channels.
- Parent-only and child-only state fields allow components to maintain separate responsibilities without requiring identical schemas.
- Nested graphs execute their internal nodes before returning their output to the parent workflow.
- Reducer behavior must be considered carefully when accumulated state crosses graph boundaries.
- Independent state schemas can be connected through wrapper nodes that explicitly transform inputs and outputs.