Parallel execution, branching and merging

Topic 1 of 5 in Advanced control flow23 min readIntermediateFree course

Overview

In the previous lesson, Project: an intelligent query router, you built a workflow that selects an appropriate processing path based on an incoming query.

Routing answers an important question: which node should execute next?

However, many real-world AI applications need to execute several operations rather than choose just one.

Consider an AI-powered contract analysis system. Given a contract, the application might need to:

  • Extract important entities and dates.
  • Identify potentially risky clauses.
  • Generate a concise document summary.
  • Retrieve relevant compliance requirements.
  • Combine the findings into a comprehensive report.

These operations can often execute independently. Making each operation wait for the previous one introduces unnecessary latency.

LangGraph supports concurrent execution through its graph structure. You declare independent branches, define how their state updates combine, and specify when downstream processing becomes eligible to execute.

This introduces three fundamental workflow patterns:

  • Fan-out: Distributing execution across multiple nodes.
  • Fan-in: Synchronizing multiple execution paths.
  • Aggregation: Combining outputs into shared state or a final result.

Together, these patterns support document analysis, multi-source retrieval, parallel LLM evaluation, multi-agent collaboration and research workflows.

In this lesson, you will implement these patterns and understand the execution guarantees that make them reliable.

Environment setup

Install LangGraph 1.x:

Terminal
pip install -U "langgraph>=1.2,<2"

The examples use deterministic Python functions instead of paid model calls so that you can study execution behavior without credentials, network latency or model variability.

The APIs have been checked against the current LangGraph documentation. The examples include expected outputs and assertions, but have not been executed in the lesson-authoring environment.

Sequential vs parallel

Sequential execution

A sequential workflow executes dependent operations one after another.

Suppose a document must first be downloaded, then converted into text, and finally analyzed.

The conversion node cannot run before the download finishes because its input does not yet exist.

Sequential execution is appropriate when a later operation depends on an earlier operation’s output.

Parallel execution

Parallel execution is appropriate when multiple operations can consume the same available input independently.

For example, once document text exists, calculating its word count and identifying email addresses do not depend on each other.

The following diagram illustrates a fan-out and fan-in document-processing workflow.

Sequential vs parallel diagram: START to Load document; Load document to Extract entities; Load document to Analyze risks; Load document to Summarize document; Extract entities to Merge findings; Analyze risks to Merge findings; Summarize document to Merge findings; Merge findings to END.

The three analysis nodes become eligible to execute together. The merge node executes after the required analysis work finishes.

Characteristic Sequential execution Parallel execution
Dependencies Operations depend on earlier results Operations are independent
Execution One operation follows another Multiple operations can overlap
Ideal latency Sum of operation durations Longest concurrent path
Shared state writes Usually straightforward May require reducers
Resource consumption More evenly distributed Potentially concentrated
Typical use case Download and parse Independent document analyses

Comparing execution times

The following complete example constructs both sequential and parallel versions of the same workflow. Artificial delays simulate independent network requests.

Python
import time
from typing import TypedDict

from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    query: str
    documents: str
    customer_data: str
    answer: str

def search_documents(state: State):
    time.sleep(1)
    return {"documents": "Refund policy: 30 days"}

def search_customer(state: State):
    time.sleep(1.5)
    return {"customer_data": "Purchase age: 12 days"}

def combine(state: State):
    return {
        "answer": (
            f'{state["documents"]}; '
            f'{state["customer_data"]}'
        )
    }

def build_graph(parallel: bool):
    builder = StateGraph(State)

    builder.add_node("documents", search_documents)
    builder.add_node("customer", search_customer)
    builder.add_node("combine", combine)

    builder.add_edge(START, "documents")

    if parallel:
        builder.add_edge(START, "customer")
        builder.add_edge(
            ["documents", "customer"], "combine"
        )
    else:
        builder.add_edge("documents", "customer")
        builder.add_edge("customer", "combine")

    builder.add_edge("combine", END)

    return builder.compile()

for parallel in [False, True]:
    graph = build_graph(parallel)

    start = time.perf_counter()

    result = graph.invoke(
        {"query": "Am I eligible for a refund?"},
        config={"max_concurrency": 2},
    )

    elapsed = time.perf_counter() - start
    mode = "Parallel" if parallel else "Sequential"

    print(f"{mode}: {elapsed:.2f} seconds")
    print(result["answer"])

Expected output, with approximate timings:

Text
Sequential: 2.51 seconds
Refund policy: 30 days; Purchase age: 12 days
Parallel: 1.51 seconds
Refund policy: 30 days; Purchase age: 12 days

Sequential execution takes approximately 2.5 seconds because both delays accumulate. Parallel execution takes approximately 1.5 seconds because the operations overlap.

The final answer remains identical.

Real-world performance also depends on scheduling overhead, concurrency limits, connection pools and external service capacity. Parallelization improves latency but does not eliminate the underlying computational work.

For CPU-intensive Python operations, concurrency does not necessarily provide equivalent speedups because of the Global Interpreter Lock in conventional GIL-enabled CPython environments.

Merging results safely

The concurrent state update problem

In the previous example, each analysis node wrote to a different state field:

  • The document search wrote to documents.
  • The customer search wrote to customer_data.

Because these fields have separate writers, LangGraph can combine their updates without ambiguity.

Now imagine that both nodes write to a shared field named findings.

A standard state declaration such as findings: list[str] uses the default overwrite behavior. If two parallel nodes update that field during the same super-step, LangGraph cannot safely determine a single replacement value.

It raises an InvalidUpdateError, associated with the INVALID_CONCURRENT_GRAPH_UPDATE error.

This is intentional. Silently accepting one update would risk losing the other branch’s output.

Using state reducers

A reducer is a function that defines how an existing state value combines with an incoming update.

Its conceptual signature is:

reducer(existing_value, incoming_update) -> combined_value

Python’s operator.add provides a convenient reducer for lists because adding two lists concatenates them.

Declare the reducer through Annotated in the state schema.

The following example demonstrates the failure first and then fixes it using a reducer.

Python
import operator
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.errors import InvalidUpdateError

class UnsafeState(TypedDict):
    findings: list[str]

class SafeState(TypedDict):
    findings: Annotated[list[str], operator.add]

def analyze_security(state):
    return {"findings": ["Security review completed"]}

def analyze_quality(state):
    return {"findings": ["Quality review completed"]}

def build_graph(schema):
    builder = StateGraph(schema)

    builder.add_node("security", analyze_security)
    builder.add_node("quality", analyze_quality)

    builder.add_edge(START, "security")
    builder.add_edge(START, "quality")

    builder.add_edge("security", END)
    builder.add_edge("quality", END)

    return builder.compile()

unsafe_graph = build_graph(UnsafeState)

try:
    unsafe_graph.invoke({"findings": []})
except InvalidUpdateError:
    print("Concurrent update rejected")

safe_graph = build_graph(SafeState)

result = safe_graph.invoke({"findings": []})

print(sorted(result["findings"]))

assert len(result["findings"]) == 2

Expected output:

Text
Concurrent update rejected
['Quality review completed', 'Security review completed']

The reducer preserves both updates. Each node returns only its contribution, and LangGraph handles accumulation.

Choosing the right reducer

Different state fields require different merging strategies.

Reducer Behavior Suitable use case
Default Replaces the previous value Single-writer fields
operator.add for lists Concatenates items Findings and search results
operator.add for integers Adds numeric values Counters and token totals
operator.or_ for sets Combines unique elements Deduplicated identifiers
add_messages Appends or updates messages by ID Agent message state
Custom reducer Implements domain-specific rules Structured result reconciliation

For predictable behavior, prefer reducers that are associative, free of side effects and, when appropriate, commutative.

Associativity means grouping updates differently does not change the result. Commutativity means changing their order does not change the result.

List concatenation is associative but not commutative. It preserves contributions but does not make their ordering independent of the order in which updates are applied.

Avoid duplicating existing state

When using an additive reducer, a node should return new findings rather than the existing list plus new findings.

Returning state["findings"] + ["new result"] causes the reducer to combine the existing list with another copy of that same list.

As the graph grows, this mistake can introduce duplicate results and excessive memory consumption.

Treat node outputs as state updates, not complete replacement snapshots.

Fan-in: waiting for all branches

Fan-in determines when a downstream node may execute.

Consider a document report that requires both metadata extraction and risk analysis. The report must not execute until both results are available.

Separate edges versus an explicit join

LangGraph supports two important incoming-edge configurations.

  • Separate edges connect each predecessor individually to the destination.
  • A list-based edge requires every listed predecessor to complete before activating the destination.

With equal-length branches, separate edges can appear to behave identically to a list-based join because both predecessors finish in the same super-step.

The difference becomes important when branches have unequal lengths.

For example, risk analysis might require an initial scan followed by a verification step, whereas metadata extraction requires only one node.

Handling unequal branch lengths

The following example compares separate incoming edges with an explicit synchronization barrier.

Python
import operator
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    findings: Annotated[list[str], operator.add]
    merge_count: Annotated[int, operator.add]

def metadata(state: State):
    return {"findings": ["Metadata extracted"]}

def risk_scan(state: State):
    return {"findings": ["Risk scan completed"]}

def verify_risks(state: State):
    return {"findings": ["Risks verified"]}

def merge(state: State):
    print("Merge sees:", sorted(state["findings"]))
    return {"merge_count": 1}

def build_graph(explicit_join: bool):
    builder = StateGraph(State)

    builder.add_node("metadata", metadata)
    builder.add_node("risk_scan", risk_scan)
    builder.add_node("verify_risks", verify_risks)
    builder.add_node("merge", merge)

    builder.add_edge(START, "metadata")
    builder.add_edge(START, "risk_scan")
    builder.add_edge("risk_scan", "verify_risks")

    if explicit_join:
        builder.add_edge(
            ["metadata", "verify_risks"], "merge"
        )
    else:
        builder.add_edge("metadata", "merge")
        builder.add_edge("verify_risks", "merge")

    builder.add_edge("merge", END)

    return builder.compile()

for explicit_join in [False, True]:
    print("\nExplicit join:", explicit_join)

    graph = build_graph(explicit_join)

    result = graph.invoke({
        "findings": [],
        "merge_count": 0,
    })

    print("Merge executions:", result["merge_count"])

    expected = 1 if explicit_join else 2
    assert result["merge_count"] == expected

Expected output:

Text
Explicit join: False
Merge sees: ['Metadata extracted', 'Risk scan completed']
Merge sees: ['Metadata extracted', 'Risk scan completed', 'Risks verified']
Merge executions: 2

Explicit join: True
Merge sees: ['Metadata extracted', 'Risk scan completed', 'Risks verified']
Merge executions: 1

With separate incoming edges, metadata completion activates the merge node before verification has finished. Verification completion activates it again in a later super-step.

With the list-based edge, the merge waits for both terminal branch nodes.

Note: A list-based join waits for every specified predecessor. If conditional routing skips one of those predecessors, the join will not execute. The graph may finish without producing the intended merged output.

This makes explicit joins particularly suitable for fixed, mandatory processing branches.

Super-steps

Understanding super-steps explains why parallel nodes behave differently from ordinary sequential function calls.

LangGraph executes compiled graphs using its Pregel runtime, which follows a Bulk Synchronous Parallel execution model.

A super-step is a logical round of graph execution.

Each round involves three conceptual phases:

  1. Planning: Determine which nodes are eligible to execute.
  2. Execution: Run the selected nodes, concurrently where resources permit.
  3. Update: Apply their returned state updates and determine subsequent work.

During execution, sibling nodes operate on the same logical pre-step state. Updates produced by one sibling are not immediately visible to another.

Consider the explicit join workflow from the previous example.

Logical round Active nodes State after completion
Initialization Input processing Empty findings
1 Metadata, risk scan Two findings
2 Verify risks Three findings
3 Merge Merge count becomes one

These are illustrative user-node execution rounds rather than exact internal checkpoint step numbers.

Notice that two nodes execute during the first round, but this still constitutes one super-step.

A super-step is not measured by wall-clock time or by the number of individual nodes executed.

State visibility

Suppose two parallel nodes both read a counter initialized to zero.

Even if the first node finishes immediately, the second node still reads the pre-step counter rather than the first node’s newly returned update.

The reducer applies their contributions at the update boundary.

Therefore, a node that requires another node’s output must be placed in a later execution round through an appropriate dependency edge.

Do not attempt to communicate between sibling nodes by mutating input state, modifying shared lists in place or relying on global Python variables. These techniques bypass the execution guarantees and can introduce race conditions.

This execution model also explains why recursion limits measure graph execution rounds rather than ordinary Python call-stack depth, a distinction that becomes particularly important in cyclic workflows.

What happens on failure

Super-step consistency

Suppose three parallel nodes execute:

  • Node A successfully retrieves documents.
  • Node B fails while calling an external API.
  • Node C successfully extracts metadata.

If Node B’s exception remains unhandled, the super-step cannot successfully commit its combined state updates.

This prevents downstream nodes from receiving an inconsistent, partially completed state as though the entire round had succeeded.

With a configured checkpointer, LangGraph can retain completed task writes separately from the committed state snapshot. Successfully recorded sibling outputs can then be reused when execution resumes.

This is known as pending writes recovery.

Recovering a failed parallel branch

The following example demonstrates a temporary service failure, checkpoint-based recovery and node-level retries.

Python
import operator
import time
from typing import Annotated, TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START, END
from langgraph.types import RetryPolicy

class State(TypedDict):
    findings: Annotated[list[str], operator.add]
    report: str

service_available = False
local_executions = 0

def local_analysis(state: State):
    global local_executions

    local_executions += 1
    print("Local analysis executed")

    return {"findings": ["Local analysis"]}

def remote_analysis(state: State):
    # Give the local branch time to finish.
    time.sleep(0.3)

    print("Remote analysis attempted")

    if not service_available:
        raise ConnectionError("Service unavailable")

    return {"findings": ["Remote analysis"]}

def merge(state: State):
    return {"report": " | ".join(sorted(state["findings"]))}

builder = StateGraph(State)

builder.add_node("local", local_analysis)

builder.add_node(
    "remote",
    remote_analysis,
    retry_policy=RetryPolicy(
        max_attempts=2,
        initial_interval=0.1,
        jitter=False,
        retry_on=ConnectionError,
    ),
)

builder.add_node("merge", merge)

builder.add_edge(START, "local")
builder.add_edge(START, "remote")
builder.add_edge(["local", "remote"], "merge")
builder.add_edge("merge", END)

graph = builder.compile(checkpointer=InMemorySaver())

config = {
    "configurable": {"thread_id": "parallel-recovery"},
    "max_concurrency": 2,
}

try:
    graph.invoke(
        {"findings": []},
        config,
        durability="sync",
    )
except ConnectionError:
    print("Run failed; recovery required")

service_available = True

result = graph.invoke(
    None,
    config,
    durability="sync",
)

print(result["report"])
print("Local executions:", local_executions)

assert local_executions == 1
assert len(result["findings"]) == 2

Expected output under normal scheduling:

Text
Local analysis executed
Remote analysis attempted
Remote analysis attempted
Run failed; recovery required
Remote analysis attempted
Local analysis | Remote analysis
Local executions: 1

The retry policy permits two total attempts, including the initial attempt.

After the remote service becomes available, invoke(None, config) continues unfinished work using the same checkpointed thread.

The global variables and artificial delay are demonstration instruments, not production state-management techniques.

Production failure considerations

InMemorySaver is appropriate for local demonstrations but does not survive process termination. Production systems should use durable checkpointing, typically backed by PostgreSQL.

Additionally, state consistency is not the same as transactional consistency across external systems.

If a branch sends an email, charges a payment or inserts a database record before failing, LangGraph cannot automatically reverse that operation.

Retries can repeat external side effects. Protect such operations using idempotency keys, database uniqueness constraints or application-level compensation.

For optional branches, catching an anticipated exception and returning a structured failure result can allow the workflow to produce a meaningful partial report. Mandatory branch failures should normally prevent publication of incomplete results.

Branching with conditions

Fixed parallel branches always execute. Conditional branching allows the workflow to select a subset of available operations at runtime.

For example, a lightweight document review might require only a summary, whereas a comprehensive review requires a summary and a compliance check.

A routing function passed to add_conditional_edges() can return one destination or a collection of destinations.

The selected destinations become eligible for execution; unselected destinations are skipped.

The following diagram shows conditional fan-out into a common finalization node.

Branching with conditions diagram: START to Inspect request; Inspect request to Full review?; Full review? to Summarize (Always); Full review? to Compliance check (If yes); Summarize to Finalize report; Compliance check to Finalize report; Finalize report to END.

Because the compliance branch is optional, an unconditional list-based join would be inappropriate.

Instead, the following example uses separate incoming edges and a deferred finalization node.

Python
import operator
from typing import Annotated, Literal, TypedDict

from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    document: str
    mode: Literal["quick", "full"]
    findings: Annotated[list[str], operator.add]
    report: str

def inspect(state: State):
    if state["mode"] not in {"quick", "full"}:
        raise ValueError("Unsupported review mode")

    return {}

def route(state: State) -> list[
    Literal["summarize", "compliance"]
]:
    if state["mode"] == "full":
        return ["summarize", "compliance"]

    return ["summarize"]

def summarize(state: State):
    return {
        "findings": [
            f'Document contains {len(state["document"].split())} words'
        ]
    }

def compliance(state: State):
    restricted = "confidential" in state["document"].lower()

    return {
        "findings": [
            f"Confidential content: {restricted}"
        ]
    }

def finalize(state: State):
    return {
        "report": " | ".join(sorted(state["findings"]))
    }

builder = StateGraph(State)

builder.add_node("inspect", inspect)
builder.add_node("summarize", summarize)
builder.add_node("compliance", compliance)
builder.add_node("finalize", finalize, defer=True)

builder.add_edge(START, "inspect")

builder.add_conditional_edges(
    "inspect",
    route,
    ["summarize", "compliance"],
)

builder.add_edge("summarize", "finalize")
builder.add_edge("compliance", "finalize")
builder.add_edge("finalize", END)

graph = builder.compile()

for mode in ["quick", "full"]:
    result = graph.invoke({
        "document": "Confidential internal report",
        "mode": mode,
        "findings": [],
    })

    print(f'{mode}: {result["report"]}')

Expected output:

Text
quick: Document contains 3 words
full: Confidential content: True | Document contains 3 words

The defer=True setting delays finalization until other pending graph work has completed.

Unlike an explicit join, deferral is not restricted to particular predecessors. It is useful for end-of-workflow aggregation but may also wait for unrelated pending tasks.

This example selects among a predefined collection of nodes. Dynamically creating many work items for an unknown number of document sections requires the Send API, which will be covered in a later lesson.

Order of results

Concurrent execution introduces multiple notions of ordering:

  • The order in which nodes become eligible.
  • The order in which nodes begin or finish execution.
  • The order in which state contributions are combined.
  • The order required by the final business output.

These orders should not be assumed to be identical.

Even if repeated local runs appear to produce stable list ordering, the application should not treat that behavior as a business-level guarantee.

A reliable approach is to attach explicit ordering metadata to every contribution.

For example, a document analysis branch can return a finding containing its document identifier, section index, category and result.

The merge node can then use Python’s sorted() with a key such as (section_index, category).

For retrieval workflows, ordering might instead depend on relevance scores followed by a stable document identifier to break ties.

Tip: Keep concurrent workers responsible for producing independent results, and centralize sorting, deduplication, prioritization and final formatting in the aggregation node.

Explicit ordering makes reports more reproducible, simplifies automated tests and prevents prompt construction from depending accidentally on execution timing.

Production design guidelines

Control concurrency

A graph containing many independent branches can create bursts of simultaneous API requests.

Set max_concurrency as a top-level invocation configuration field. This limits concurrent execution within the applicable graph execution context.

Choose the limit based on provider rate limits, database connection pools, memory consumption and downstream service capacity.

A per-invocation concurrency limit does not replace application-wide rate limiting across multiple users, processes or graph runs.

For network-heavy asynchronous workloads, use asynchronous nodes with non-blocking clients and execute the graph using ainvoke() or astream(). Avoid calling blocking functions directly inside asynchronous nodes.

Validate aggregation

A successful worker should return structured information with a stable identifier and, where appropriate, an execution status.

The aggregation node should verify that all required results exist before producing an authoritative report.

For optional operations, distinguish between skipped, failed and successfully completed work.

Tests should cover empty inputs, missing results, unequal branch lengths, service failures and repeated executions. Test business outputs rather than relying on incidental branch ordering or timing.

Observe parallel workflows

Use streaming updates and tracing to identify slow branches, retries and unexpected executions of aggregation nodes.

Pay particular attention to the critical path: the longest dependency chain that determines overall workflow latency.

Accelerating an already-fast branch may provide little improvement when a different branch dominates execution time.

For more details on the APIs used throughout this lesson, consult the official LangGraph control flow guide, runtime documentation, checkpointers guide, and fault tolerance guide.

Connection to the next lesson

The workflows in this lesson move forward through independent branches before converging.

Real agentic systems, however, often need to revisit earlier nodes. A document reviewer might reject an analysis and request another attempt, or a retrieval agent might search repeatedly until sufficient evidence becomes available.

In the next lesson, Cycles, feedback loops and recursion limits, you will extend these execution patterns to iterative workflows, define termination conditions and prevent uncontrolled graph execution.

Your understanding of state reducers, synchronization barriers and super-steps will be essential when designing workflows that repeatedly execute the same nodes.

Exercise

Build a parallel document analyzer

Build a document-processing graph that simultaneously calculates word statistics, extracts email addresses, and identifies risk-related keywords. Merge the results using a state reducer and generate a structured report only after all three branches have completed. Ensure the final report has deterministic ordering regardless of branch execution order, and verify its correctness using assertions.

Python
import operator
import re
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END


class Finding(TypedDict):
    order: int
    category: str
    value: str


class DocumentState(TypedDict):
    document: str
    findings: Annotated[list[Finding], operator.add]
    report: str


def analyze_words(state: DocumentState) -> dict:
    # TODO: Count the words and return a finding with order 1.
    raise NotImplementedError


def extract_emails(state: DocumentState) -> dict:
    # TODO: Extract email addresses using a regular expression.
    # Return a finding with order 2.
    raise NotImplementedError


def detect_risks(state: DocumentState) -> dict:
    # TODO: Detect the keywords urgent, confidential and penalty.
    # Return a finding with order 3.
    raise NotImplementedError


def generate_report(state: DocumentState) -> dict:
    # TODO: Sort findings by order and construct the report.
    raise NotImplementedError


builder = StateGraph(DocumentState)

builder.add_node("analyze_words", analyze_words)
builder.add_node("extract_emails", extract_emails)
builder.add_node("detect_risks", detect_risks)
builder.add_node("generate_report", generate_report)

# TODO: Fan out from START to all three analysis nodes.
# TODO: Create a fan-in edge that waits for all three nodes.
# TODO: Connect generate_report to END.

graph = builder.compile()

result = graph.invoke({
    "document": (
        "Urgent confidential notice. Contact legal@example.com "
        "before the penalty deadline."
    ),
    "findings": [],
})

print(result["report"])

Summary

  • Multiple outgoing edges allow independent nodes to execute concurrently within the same super-step.
  • Parallel nodes read the same logical state snapshot and cannot immediately observe sibling updates.
  • State reducers define how multiple updates to the same state field are combined safely.
  • A list-based incoming edge creates an explicit synchronization barrier that waits for every specified predecessor.
  • Conditional edges can select one or several branches dynamically at runtime.
  • Checkpointing and node-level retry policies support recovery from failures during parallel execution.
  • Deterministic output requires explicit ordering rather than assumptions about branch completion or reducer update order.