Parallelization and orchestrator–worker

Topic 2 of 4 in Agentic workflow patterns26 min readAdvancedFree course

Overview

The previous lesson introduced prompt chaining and routing. Prompt chaining executes dependent operations sequentially, while routing selects a specialized processing path.

However, not every task depends on the output of a previous task, and not every request can be handled adequately by a single specialist.

Imagine building an AI system that reviews a technical article. The application must evaluate factual accuracy, readability, completeness, and writing style.

These evaluations can often run independently because each evaluator examines the same original article. Waiting for the accuracy review before starting the readability review creates unnecessary latency.

Alternatively, consider generating a comprehensive report. Different requests may require different numbers of sections. A report about Python decorators might need three sections, whereas a report about distributed database architectures might require five.

Defining a fixed collection of workers for every possible report would be unnecessarily restrictive.

This lesson introduces two architectural patterns that address these problems:

  • Parallelization: Execute multiple independent operations concurrently and aggregate their outputs.
  • Orchestrator–worker: Dynamically determine which operations are required, delegate them to workers, and combine their results.

Parallelization has two important variations: sectioning and voting. Sectioning divides responsibilities, whereas voting introduces redundancy to improve decision reliability.

Pattern Task allocation Execution behavior
Prompt chaining Predefined Sequential
Routing Selects predefined path Conditional
Sectioning Predefined subtasks Concurrent
Voting Repeated decision task Concurrent
Orchestrator–worker Dynamically generated subtasks Dynamic fan-out and fan-in

The architectural challenge is not simply making more LLM calls. It is determining which calls should run independently, what information each call needs, and how their outputs should be combined safely.

Environment setup

Install the required packages:

Terminal
pip install -U "langgraph>=1,<2" "langchain>=1,<2" langchain-openai "pydantic>=2,<3" typing-extensions

Configure your OpenAI API key:

Terminal
export OPENAI_API_KEY="your-api-key"

For PowerShell:

POWERSHELL
$env:OPENAI_API_KEY = "your-api-key"

The examples use the LangGraph 1.x Graph API and the course model, openai:gpt-5.4-mini. They assume that your API account has access to this model.

Run each complete example independently. The graph APIs follow the official workflow patterns, Graph API overview, and control flow documentation. Live model execution has not been verified, and generated outputs are illustrative.

Parallelization: sectioning

Sectioning divides a larger task into smaller, independent tasks that contribute different information to a shared objective.

For example, a software architecture review might assign separate workers to assess security, scalability, and maintainability.

Each worker receives the same architecture description but evaluates it from a different perspective. An aggregation stage combines the resulting findings into a consolidated review.

Sectioning is appropriate when the responsibilities can be identified before execution begins and do not require one another’s intermediate results.

Fan-out and fan-in

Concurrent graph workflows typically contain two structural operations:

  • Fan-out: Distribute work across multiple execution branches.
  • Fan-in: Collect the completed branch outputs before continuing.

The following graph distributes an architecture description to three independent reviewers and waits for their results.

Parallelization: sectioning diagram: START to Security Review; START to Scalability Review; START to Maintainability Review; Security Review to Aggregate Reviews; Scalability Review to Aggregate Reviews; Maintainability Review to Aggregate Reviews; Aggregate Reviews to END.

The aggregation stage can be deterministic Python code, an LLM-based synthesizer, or a combination of both.

Deterministic aggregation is preferable when the individual results already have the required structure. An LLM synthesizer becomes useful when findings overlap, contradict one another, or require a coherent narrative.

Example 1: Parallel architecture review

This example creates three independent review nodes. Each writes to a different state field, and a multi-source edge ensures that aggregation waits for all three reviewers.

Python
from typing_extensions import TypedDict

from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END

model = init_chat_model("openai:gpt-5.4-mini")

class ReviewState(TypedDict, total=False):
    architecture: str
    security: str
    scalability: str
    maintainability: str
    report: str

def review(state: ReviewState, perspective: str) -> str:
    response = model.invoke([
        SystemMessage(content=(
            f"You are a {perspective} reviewer. "
            "Identify two important risks and practical mitigations. "
            "Distinguish missing information from confirmed problems. "
            "Keep your response under 120 words."
        )),
        HumanMessage(content=state["architecture"]),
    ])

    return response.text

def security_review(state: ReviewState):
    return {"security": review(state, "security")}

def scalability_review(state: ReviewState):
    return {"scalability": review(state, "scalability")}

def maintainability_review(state: ReviewState):
    return {"maintainability": review(state, "maintainability")}

def aggregate(state: ReviewState):
    report = (
        "## Security\n"
        + state["security"]
        + "\n\n## Scalability\n"
        + state["scalability"]
        + "\n\n## Maintainability\n"
        + state["maintainability"]
    )

    return {"report": report}

builder = StateGraph(ReviewState)

builder.add_node("security", security_review)
builder.add_node("scalability", scalability_review)
builder.add_node("maintainability", maintainability_review)
builder.add_node("aggregate", aggregate)

builder.add_edge(START, "security")
builder.add_edge(START, "scalability")
builder.add_edge(START, "maintainability")

builder.add_edge(
    ["security", "scalability", "maintainability"],
    "aggregate",
)

builder.add_edge("aggregate", END)

app = builder.compile()

result = app.invoke(
    {
        "architecture": (
            "A FastAPI service uses PostgreSQL for persistence, "
            "Redis for caching, and a single background worker "
            "for processing customer orders. "
            "The service exposes a public REST API."
        ),
    },
    config={
        "max_concurrency": 3,
        "recursion_limit": 10,
    },
)

print(result["report"])

An illustrative output is:

Text
## Security
Verify authentication and authorization on public endpoints.
Protect database credentials using a secrets manager.

## Scalability
A single background worker may become a processing bottleneck.
Consider horizontal worker scaling and queue monitoring.

## Maintainability
Define clear boundaries between API, persistence, and worker logic.
Introduce integration tests and centralized configuration.

The graph performs three logical model calls followed by one deterministic aggregation operation.

Understanding concurrent execution internally

LangGraph executes graph operations using a runtime inspired by the Pregel computation model.

Execution progresses through discrete supersteps. Independent nodes eligible for execution in the same superstep can run concurrently.

For this example:

  1. The runtime receives the architecture description.
  2. All three reviewers become eligible for execution.
  3. Each reviewer reads the architecture and produces its own update.
  4. The runtime merges the completed updates.
  5. The aggregation node reads the combined state.
  6. Execution reaches END.

Reviewers do not receive one another’s intermediate updates during their shared superstep. Their independence is intentional.

The list passed to add_edge() establishes an explicit synchronization requirement. Every listed source must complete before the destination becomes eligible.

This distinction matters when parallel branches have different depths. Independently connecting each branch endpoint to an aggregator is not a general substitute for an explicit multi-source join when those endpoints complete in different supersteps.

Synchronous nodes can perform concurrent network-bound model requests without manually creating Python threads. For an asynchronous web service, use asynchronous nodes with model.ainvoke() and execute the graph with app.ainvoke().

Concurrent writes and reducers

In the preceding example, each reviewer writes to a separate state field. Therefore, ordinary replacement behavior is sufficient.

Now imagine that every reviewer returns an update like:

Python
return {"findings": ["A potential risk was identified."]}

Multiple concurrent updates target the same key. Without a reducer that supports combining them, LangGraph can raise InvalidUpdateError.

Define a reducer using Annotated:

Python
import operator
from typing import Annotated
from typing_extensions import TypedDict

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

The annotation instructs LangGraph to combine list updates through concatenation.

Each worker should return only its newly generated findings, not the entire accumulated list. Returning previously collected values repeatedly can introduce duplicates.

Reducers are part of the workflow’s data consistency design. They determine how independently produced updates become a shared application state.

For numeric counters, addition may be appropriate. For collections, concatenation may be sufficient. For production records requiring deduplication, a custom reducer based on stable identifiers may be more appropriate.

Note: Do not rely on parallel task completion order to establish business ordering. Assign stable identifiers or sequence numbers and explicitly sort results during aggregation.

Parallelization: voting

Voting executes the same decision-making task multiple times and combines the resulting judgments.

Unlike sectioning, voting intentionally introduces overlapping work.

Suppose an application must determine whether a customer message represents a service outage. A single classification might be wrong because the message is ambiguous.

Three independent classifiers can evaluate the message, with the application selecting an outcome using majority voting.

Voting is also useful for candidate answer selection, document classification, content quality assessment, and other decisions with a reasonably well-defined output space.

Voting strategies

Different applications require different aggregation policies.

Strategy Decision rule Appropriate use
Majority voting More than half agree Ordinary classification
Unanimous voting Every voter agrees Conservative acceptance
Threshold voting Minimum agreement count Configurable quality gates
Weighted voting Voters have different weights Validated specialist expertise
Any-veto voting One valid rejection blocks acceptance Mandatory risk checks
Score aggregation Combine numeric assessments Quality measurement

A voting policy must also define what happens when agreement is insufficient.

For example, three voters selecting three different categories produce no majority. The application should return an explicit uncertain outcome rather than silently selecting an arbitrary category.

Example 2: Majority-vote classification

The following workflow uses three classification prompts, a shared reducer, and deterministic majority voting to classify support requests.

Python
import operator
from collections import Counter
from typing import Annotated, Literal
from typing_extensions import TypedDict

from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END

model = init_chat_model("openai:gpt-5.4-mini")

Category = Literal["billing", "technical", "general"]

class Classification(BaseModel):
    category: Category

classifier = model.with_structured_output(Classification)

class Vote(TypedDict):
    voter: str
    category: Category

class VotingState(TypedDict, total=False):
    request: str
    votes: Annotated[list[Vote], operator.add]
    decision: str
    agreement: float

def classify(
    state: VotingState,
    voter: str,
    perspective: str,
):
    result = classifier.invoke([
        SystemMessage(content=(
            "Classify the request as billing, technical, or general. "
            "Billing covers payments, invoices, and charges. "
            "Technical covers errors and software failures. "
            "General covers other requests. "
            f"Classification approach: {perspective}"
        )),
        HumanMessage(content=state["request"]),
    ])

    return {
        "votes": [{
            "voter": voter,
            "category": result.category,
        }],
    }

def voter_one(state: VotingState):
    return classify(state, "one", "Focus on the primary user intent.")

def voter_two(state: VotingState):
    return classify(state, "two", "Identify the underlying problem.")

def voter_three(state: VotingState):
    return classify(state, "three", "Identify the appropriate support team.")

def aggregate_votes(state: VotingState):
    votes = state["votes"]

    if len(votes) != 3:
        raise ValueError("Expected exactly three votes.")

    if {vote["voter"] for vote in votes} != {"one", "two", "three"}:
        raise ValueError("Missing or duplicate voter.")

    counts = Counter(vote["category"] for vote in votes)

    winner, count = counts.most_common(1)[0]

    return {
        "decision": winner if count > len(votes) / 2 else "uncertain",
        "agreement": count / len(votes),
    }

builder = StateGraph(VotingState)

builder.add_node("voter_one", voter_one)
builder.add_node("voter_two", voter_two)
builder.add_node("voter_three", voter_three)
builder.add_node("aggregate", aggregate_votes)

voters = ["voter_one", "voter_two", "voter_three"]

for voter in voters:
    builder.add_edge(START, voter)

builder.add_edge(voters, "aggregate")
builder.add_edge("aggregate", END)

app = builder.compile()

result = app.invoke(
    {
        "request": (
            "The checkout page failed, but my credit card "
            "was charged twice."
        ),
    },
    config={"max_concurrency": 3, "recursion_limit": 10},
)

print("Votes:", result["votes"])
print("Decision:", result["decision"])
print("Agreement:", f"{result['agreement']:.1%}")

One possible output is:

Text
Votes: [
    {'voter': 'one', 'category': 'billing'},
    {'voter': 'two', 'category': 'technical'},
    {'voter': 'three', 'category': 'billing'}
]
Decision: billing
Agreement: 66.7%

If all three voters choose different categories, the result is uncertain. A downstream routing stage could then request clarification or escalate the request.

Why voting can improve reliability

Voting can reduce the influence of occasional classification errors when voters possess sufficiently diverse error patterns.

For an idealized binary classification problem, assume three statistically independent voters, each with 80% accuracy.

The probability that the majority is correct is:

[ P(\text{correct majority}) = 0.8^3 + 3(0.8^2)(0.2) = 0.896 ]

Under these assumptions, majority voting increases accuracy from 80% to 89.6%.

However, real LLM outputs are not necessarily statistically independent. Calls using the same model, training data, and similar prompts may reproduce the same error.

Diversity can be introduced through different prompt formulations, models, evidence sources, or analytical perspectives.

The agreement field in the example measures observed consensus, not calibrated confidence. Three agreeing models can still be incorrect. External verification remains necessary when factual correctness matters.

For open-ended answers, exact string voting is usually unsuitable because equivalent answers can have different wording. Instead, normalize answers into structured categories, extract comparable values, or use a separately validated comparison mechanism.

Orchestrator–worker

Static parallelization works well when the required branches are known during graph construction.

Many realistic problems do not satisfy that assumption.

A research report may require different subjects depending on the question. A document-processing system may encounter an unknown number of documents. A software maintenance workflow may identify a different set of affected modules for each change.

The orchestrator–worker pattern introduces runtime task decomposition.

An orchestrator examines the objective and produces a task plan. A dispatcher creates worker invocations from that plan. Each worker completes an assigned task, and an aggregation stage combines the results.

The following diagram illustrates a dynamic plan that produces an input-dependent number of workers.

Orchestrator–worker diagram: START to Orchestrator; Orchestrator to Validate Plan; Validate Plan to Worker One; Validate Plan to Worker Two; Validate Plan to Additional Workers; Worker One to Aggregate Results; Worker Two to Aggregate Results; Additional Workers to Aggregate Results; Aggregate Results to END.

The orchestrator decides the work to perform, but application code retains control over the available worker implementations, permitted actions, and execution limits.

Dynamic task decomposition with Send

LangGraph provides Send for dynamic fan-out:

Python
from langgraph.types import Send

A Send object specifies a destination node and an input payload:

Python
Send(
    "worker",
    {
        "task_id": 0,
        "instruction": "Explain database indexing.",
    },
)

Returning a list of these objects from a conditional edge function schedules multiple invocations of the destination node.

The graph contains one registered worker implementation, but that implementation can execute multiple times with different input states.

This is fundamentally different from adding graph nodes dynamically after compilation.

The graph structure remains stable. The number of scheduled worker tasks changes at runtime.

The official Send and Command documentation describes this mechanism.

Shared state versus worker state

The parent graph typically stores the original objective, generated plan, accumulated results, and final output.

Each worker receives only the information needed for its assignment.

For example, a report-writing worker might receive the report topic, section identifier, section title, and instructions. It does not need access to every other worker’s intermediate state.

A worker-specific TypedDict makes this contract explicit, but it is not a security boundary. Actual access restrictions must be enforced through application permissions and controlled tool interfaces.

Workers return updates targeting channels defined in the parent graph’s state schema. A reducer combines the concurrent updates.

Example 3: Dynamic technical report generation

This complete example uses an LLM orchestrator to select between two and five report sections. Each section is assigned to a separate worker invocation, and the final report is assembled in the original plan order.

Python
import operator
from typing import Annotated
from typing_extensions import TypedDict

from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END
from langgraph.types import Send

model = init_chat_model("openai:gpt-5.4-mini")

MAX_WORKERS = 5

class Section(BaseModel):
    title: str
    instructions: str

class ReportPlan(BaseModel):
    sections: list[Section] = Field(
        min_length=2,
        max_length=5,
    )

planner = model.with_structured_output(ReportPlan)

class Task(TypedDict):
    index: int
    title: str
    instructions: str

class SectionResult(TypedDict):
    index: int
    title: str
    content: str

class ReportState(TypedDict, total=False):
    topic: str
    tasks: list[Task]
    completed: Annotated[list[SectionResult], operator.add]
    report: str

class WorkerState(TypedDict):
    topic: str
    task: Task

def orchestrator(state: ReportState):
    plan = planner.invoke([
        SystemMessage(content=(
            "Design a technical report for Python developers. "
            "Create between two and five independent sections. "
            "Give each section a unique title and focused instructions. "
            "Avoid overlapping sections and tasks requiring "
            "the output of another section."
        )),
        HumanMessage(content=state["topic"]),
    ])

    tasks: list[Task] = [
        {
            "index": index,
            "title": section.title.strip(),
            "instructions": section.instructions.strip(),
        }
        for index, section in enumerate(plan.sections)
    ]

    if not 2 <= len(tasks) <= MAX_WORKERS:
        raise ValueError("Worker budget exceeded or plan too small.")

    if any(not task["title"] or not task["instructions"] for task in tasks):
        raise ValueError("Incomplete task definition.")

    titles = {task["title"].casefold() for task in tasks}

    if len(titles) != len(tasks):
        raise ValueError("Duplicate section titles.")

    return {"tasks": tasks}

def dispatch_workers(state: ReportState) -> list[Send]:
    return [
        Send(
            "write_section",
            {
                "topic": state["topic"],
                "task": task,
            },
        )
        for task in state["tasks"]
    ]

def write_section(state: WorkerState):
    task = state["task"]

    response = model.invoke([
        SystemMessage(content=(
            "Write only the assigned technical report section. "
            "Use approximately 100 words. "
            "Do not include the section heading. "
            "Avoid invented statistics or unsupported claims."
        )),
        HumanMessage(content=(
            f"Report topic: {state['topic']}\n"
            f"Section: {task['title']}\n"
            f"Instructions: {task['instructions']}"
        )),
    ])

    content = response.text.strip()

    if not content:
        raise ValueError("Worker returned empty content.")

    return {
        "completed": [{
            "index": task["index"],
            "title": task["title"],
            "content": content,
        }],
    }

def aggregate(state: ReportState):
    ordered = sorted(
        state["completed"],
        key=lambda item: item["index"],
    )

    expected = list(range(len(state["tasks"])))
    actual = [item["index"] for item in ordered]

    if actual != expected:
        raise ValueError("Missing or duplicate worker results.")

    sections = [
        f"## {item['title']}\n\n{item['content']}"
        for item in ordered
    ]

    return {
        "report": f"# {state['topic']}\n\n" + "\n\n".join(sections)
    }

builder = StateGraph(ReportState)

builder.add_node("orchestrator", orchestrator)
builder.add_node("write_section", write_section)
builder.add_node("aggregate", aggregate)

builder.add_edge(START, "orchestrator")

builder.add_conditional_edges(
    "orchestrator",
    dispatch_workers,
    ["write_section"],
)

builder.add_edge("write_section", "aggregate")
builder.add_edge("aggregate", END)

app = builder.compile()

result = app.invoke(
    {"topic": "Caching strategies for Python web applications"},
    config={
        "max_concurrency": 3,
        "recursion_limit": 10,
    },
)

print("Number of workers:", len(result["tasks"]))
print(result["report"])

An illustrative execution produces four tasks:

Text
Number of workers: 4

## Cache Fundamentals
...

## In-Memory Caching
...

## Distributed Caching with Redis
...

## Invalidation and Cache Consistency
...

The plan may differ between invocations because task decomposition is performed by the model.

Walking through the dynamic execution

First, the orchestrator produces a structured plan. Application code validates its size, required fields, and duplicate titles.

Next, the conditional edge function creates one Send per approved task. Each payload contains the information required for its assigned section.

The worker implementation executes independently for each payload. Every invocation returns a single result inside a list.

LangGraph merges these updates through operator.add. Because all dispatched workers occupy the same execution stage in this example, aggregation runs after the worker superstep completes.

Finally, the aggregator verifies completeness, restores the planned ordering, and constructs the report.

If four sections are generated, this workflow requires five logical model invocations: one planning call and four worker calls. Aggregation requires no additional model call.

Handling dependencies between workers

A task is not independent merely because it has a separate title.

For example, generating a database schema and implementing queries against that schema creates a dependency. The query worker needs the completed schema.

Such tasks should execute in dependency order rather than in the same worker batch.

A more sophisticated orchestrator can generate dependency identifiers, validate that the resulting dependency graph is acyclic, and dispatch only tasks whose prerequisites are complete.

The single-round orchestrator implemented here deliberately restricts workers to independent assignments. This keeps execution bounded and avoids introducing the more complex planning and replanning architecture covered later in the chapter.

Controlling cost

Parallelization often improves response time, but it does not inherently reduce token consumption.

An orchestrator can also generate more work than the user actually requires. Without explicit execution limits, dynamic delegation can become expensive even when the graph contains no loops.

Latency versus total work

Suppose three independent model calls require two, three, and four seconds.

Sequential execution takes approximately:

[ T_{\text{sequential}} = 2 + 3 + 4 = 9 \text{ seconds} ]

With sufficient concurrency, parallel execution takes approximately:

[ T_{\text{parallel}} = \max(2,3,4) = 4 \text{ seconds} ]

These estimates exclude scheduling, network contention, queueing, retries, and aggregation overhead.

The number of model calls remains three. Parallel execution improves elapsed time, not necessarily computational efficiency.

The planning and aggregation stages also remain on the critical path in an orchestrator–worker system.

Establish separate execution limits

A production workflow should distinguish several kinds of budgets.

Control Purpose
Maximum worker count Limits total delegated tasks
max_concurrency Limits concurrent graph task execution
recursion_limit Limits graph supersteps
Input token budget Limits context sent to models
Output token budget Limits generated tokens
Retry budget Limits repeated attempts
Request deadline Limits total elapsed time
Monetary budget Limits permitted expenditure

The following complete model configuration illustrates provider-level request controls:

Python
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "openai:gpt-5.4-mini",
    max_tokens=1200,
    timeout=30,
    max_retries=2,
)

response = model.invoke(
    "Explain database connection pooling in three sentences."
)

print(response.text)
print("Token usage:", response.usage_metadata)

The output contains a short explanation and, when supplied by the provider, token usage metadata. These settings configure the OpenAI model integration rather than the LangGraph scheduler.

For graph-level execution, use:

Python
config = {
    "max_concurrency": 3,
    "recursion_limit": 10,
}

A five-worker plan with a concurrency limit of three still contains five worker tasks. The concurrency setting limits how many can execute concurrently; it does not discard the remaining tasks.

Likewise, a small recursion limit does not prevent a single superstep from containing many worker invocations.

Tip: Treat worker count, concurrency, and recursion limits as independent controls. A recursion limit alone is not an effective spending limit for dynamically parallel workflows.

Estimating request cost

Consider an illustrative orchestrator–worker application processing 10,000 requests.

Assume a planner costs $0.002 per invocation, each worker costs $0.004, and optional LLM synthesis costs $0.003.

Average workers Cost per request with synthesis Total cost
2 $0.013 $130
3 $0.017 $170
5 $0.025 $250
10 $0.045 $450

These are hypothetical values, not actual model prices.

The example demonstrates why controlling task decomposition matters. Even modest increases in average worker count can significantly affect operating expenditure at scale.

Reduce repeated input context, avoid unnecessary synthesis calls, choose appropriately sized models, and introduce caching where repeated work can safely reuse previous results.

For strict monetary enforcement, reserve budget before dispatching workers. Monitoring expenditure only after concurrent calls complete can allow a workflow to exceed its intended budget.

Production reliability and common mistakes

Managing worker failures

An ordinary worker exception can prevent the graph from reaching its aggregation stage.

Choose an explicit failure policy:

  • Fail the entire operation when every result is mandatory.
  • Retry transient infrastructure failures with bounded retry policies.
  • Return structured worker failure records when partial completion is acceptable.
  • Escalate missing critical results for human review.

With checkpointing enabled, LangGraph can retain successful pending writes from a failed superstep, helping avoid repeating completed tasks when execution resumes.

External side effects still require idempotency. A worker that writes to a database or triggers an external action must tolerate re-execution without duplicating its effects.

Testing concurrency and aggregation

Test reducers and aggregation functions independently of live model calls.

Include cases containing missing results, duplicate identifiers, unexpected identifiers, invalid scores, and different result orders.

For voting workflows, test disagreement explicitly. For orchestrators, test empty plans, oversized plans, duplicate assignments, and tasks with hidden dependencies.

Also remember that additive reducers accumulate values. If a checkpointed thread is reused for a new independent workload, previously collected results may remain unless the application resets the relevant state or uses a new thread.

Observability and evaluation

Parallel workflows require branch-level visibility.

Use LangSmith tracing to inspect planner outputs, worker inputs, individual execution times, token consumption, retries, and final aggregation.

Measure end-to-end latency alongside the slowest worker duration. Average latency alone can hide expensive outliers.

Evaluate voting systems against labeled examples before claiming reliability improvements. For orchestrator–worker systems, assess task coverage, unnecessary delegation, duplicate work, and final output quality.

Choosing between static and dynamic parallelization

Prefer sectioning when responsibilities are stable and independently executable. Prefer voting when multiple judgments can improve a bounded decision and disagreement has an explicit handling policy.

Use an orchestrator–worker architecture when the number or identity of required tasks genuinely depends on the input.

For the chapter’s self-evaluating content-generation project, these patterns can support both content generation and review. An orchestrator can determine the required article sections, workers can generate them concurrently, and parallel evaluators can assess the resulting draft against complementary quality criteria.

Voting can help consolidate repeated judgments, while deterministic gates enforce mandatory requirements.

These mechanisms provide the foundation for the next lesson, Evaluator–optimizer and reflection, where you will learn how evaluation results become actionable feedback, how generated content can be revised through controlled loops, and how to prevent self-correction workflows from consuming unbounded time and resources.

Exercise

Build a parallel content review system

Build an orchestrator–worker workflow that dynamically selects between two and four review criteria for a supplied article. Dispatch one worker per criterion using Send, and aggregate the structured review results into an overall quality score. Accept the article only when its average score is at least eight and no individual score is below six. Limit concurrent workers to two and preserve the original criterion order in the final report.

Python
import operator
from typing import Annotated
from typing_extensions import TypedDict
from pydantic import BaseModel, Field

from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END
from langgraph.types import Send

model = init_chat_model("openai:gpt-5.4-mini")

MAX_WORKERS = 4

class ReviewPlan(BaseModel):
    criteria: list[str] = Field(min_length=2, max_length=4)

class Assessment(BaseModel):
    score: int = Field(ge=0, le=10)
    feedback: str

class ReviewResult(TypedDict):
    index: int
    criterion: str
    score: int
    feedback: str

class State(TypedDict, total=False):
    article: str
    criteria: list[str]
    reviews: Annotated[list[ReviewResult], operator.add]
    average_score: float
    accepted: bool
    report: str

class WorkerState(TypedDict):
    index: int
    article: str
    criterion: str

planner = model.with_structured_output(ReviewPlan)
reviewer = model.with_structured_output(Assessment)

def orchestrator(state: State):
    # TODO: Generate and validate the review criteria.
    raise NotImplementedError

def dispatch_workers(state: State):
    # TODO: Return one Send object per criterion.
    raise NotImplementedError

def review_worker(state: WorkerState):
    # TODO: Evaluate the article against one criterion.
    # Return a single-element list under the reviews key.
    raise NotImplementedError

def aggregate(state: State):
    # TODO: Sort results by index.
    # TODO: Verify that all expected reviews exist.
    # TODO: Calculate the average and acceptance decision.
    # TODO: Construct the final review report.
    raise NotImplementedError

builder = StateGraph(State)

# TODO: Register the orchestrator, worker, and aggregator.
# TODO: Add the dynamic fan-out and fan-in edges.

# app = builder.compile()
# result = app.invoke(
#     {"article": "Python is widely used for automation."},
#     config={"max_concurrency": 2, "recursion_limit": 10},
# )
# print(result["report"])

Summary

  • Parallelization executes independent tasks concurrently to reduce latency or collect multiple perspectives on a problem.
  • Sectioning divides work into complementary subtasks whose outputs are combined into a final result.
  • Voting repeats a decision-making task across multiple model invocations and aggregates their judgments using an explicit policy.
  • LangGraph uses supersteps and reducers to coordinate concurrent execution and merge parallel state updates.
  • The orchestrator–worker pattern dynamically determines the required subtasks instead of relying exclusively on predefined branches.
  • The Send API dispatches multiple invocations of a worker node with individually assigned input states.
  • Production workflows must independently constrain worker counts, concurrency, token consumption, retries, and aggregation behavior.