Synchronous and asynchronous execution

Topic 1 of 4 in Streaming, async & Functional API24 min readAdvancedFree course

Overview

In the previous lesson, you learned how Adaptive RAG, Self-RAG, and answer validation improve the reliability of retrieval-augmented generation systems. Those workflows frequently perform several expensive operations, including document retrieval, database queries, model inference, relevance grading, and answer verification.

Most of these operations spend significant time waiting for external services.

Imagine an enterprise AI assistant that must retrieve customer information, inspect recent transactions, search a knowledge base, and generate a personalized response. If every independent operation runs sequentially, the assistant becomes unnecessarily slow. If hundreds of users access it simultaneously, inefficient execution can also become a scalability bottleneck.

Asynchronous execution helps address these problems.

This lesson introduces two distinct forms of concurrency:

  • Within a workflow: Multiple independent graph nodes or tools execute concurrently.
  • Across workflows: Multiple graph executions progress concurrently for different users, requests, or background jobs.

Understanding both is essential when moving from experimental agents to production services.

Environment setup

Use Python 3.11 or newer and the LangGraph 1.x and LangChain 1.x APIs.

Terminal
pip install -U "langgraph>=1,<2" "langchain>=1,<2" langchain-openai httpx

For examples involving an OpenAI model, configure your API key.

Terminal
export OPENAI_API_KEY="your-api-key"

The examples use simulated external operations wherever possible, allowing you to study execution behavior without incurring model costs. The model-backed example requires credentials and access to the specified model.

Understanding synchronous and asynchronous execution

Synchronous execution

Synchronous execution means that a calling function waits until an operation returns before continuing.

Consider three independent operations:

  1. Retrieve customer information in one second.
  2. Retrieve transaction history in two seconds.
  3. Retrieve support tickets in one second.

If performed sequentially, their combined execution takes approximately four seconds.

Synchronous programming is straightforward because operations generally follow an easily understood execution order. However, a thread waiting for a network response cannot perform other ordinary work on that same thread during the wait.

Asynchronous execution

Asynchronous programming allows a coroutine to suspend its execution while waiting for an operation and lets the event loop advance other ready coroutines.

Python provides this functionality through asyncio.

The following example executes the same simulated requests sequentially and concurrently.

Python
import asyncio
import time

async def fetch(name: str, delay: float):
    await asyncio.sleep(delay)
    return f"{name} retrieved"

async def main():
    started = time.perf_counter()

    await fetch("Customer", 1)
    await fetch("Transactions", 2)
    await fetch("Tickets", 1)

    print(f"Sequential: {time.perf_counter() - started:.2f}s")

    started = time.perf_counter()

    results = await asyncio.gather(
        fetch("Customer", 1),
        fetch("Transactions", 2),
        fetch("Tickets", 1),
    )

    print(f"Concurrent: {time.perf_counter() - started:.2f}s")
    print(results)

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
Sequential: 4.00s
Concurrent: 2.00s
['Customer retrieved', 'Transactions retrieved', 'Tickets retrieved']

Actual timings include scheduling overhead.

Notice that every function is asynchronous in both cases. The difference is how the coroutines are scheduled.

Writing three consecutive await expressions still produces sequential execution. Using asyncio.gather() allows independent operations to overlap.

Concurrency versus parallelism

Concurrency means multiple operations make progress during overlapping time periods. Parallelism means multiple operations physically execute at the same instant.

An asynchronous event loop can manage many waiting network requests using one thread. CPU-intensive computation, however, generally requires a different strategy, such as multiple processes or native computation libraries.

For agentic AI applications, asynchronous programming is especially valuable because model inference, vector searches, database queries, and REST requests are predominantly I/O-bound from the application’s perspective.

invoke() and ainvoke()

A compiled LangGraph graph exposes both synchronous and asynchronous execution interfaces through its Runnable interface.

Method Execution Result
invoke() Synchronous Completed graph output
ainvoke() Asynchronous Awaitable graph output
batch() Synchronous batch Multiple graph outputs
abatch() Asynchronous batch Multiple graph outputs
stream() Synchronous iteration Incremental output
astream() Asynchronous iteration Incremental output

The streaming methods will be explored in the next lesson.

Running the same graph synchronously and asynchronously

The following example demonstrates both invocation methods using a synchronous node.

Python
import asyncio
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict, total=False):
    name: str
    greeting: str

def greet(state: State):
    return {"greeting": f"Hello, {state['name']}!"}

builder = StateGraph(State)
builder.add_node("greet", greet)
builder.add_edge(START, "greet")
builder.add_edge("greet", END)

graph = builder.compile()

async def main():
    result = await graph.ainvoke({"name": "Priya"})
    print("Async:", result)

if __name__ == "__main__":
    result = graph.invoke({"name": "Alex"})
    print("Sync:", result)

    asyncio.run(main())

Expected output:

Text
Sync: {'name': 'Alex', 'greeting': 'Hello, Alex!'}
Async: {'name': 'Priya', 'greeting': 'Hello, Priya!'}

Both methods preserve the graph’s state-update and routing semantics.

Calling invoke() blocks the calling thread until execution finishes or pauses at an interrupt. Calling ainvoke() returns a coroutine that must be awaited or scheduled.

LangGraph supports synchronous nodes during asynchronous execution by dispatching their synchronous work through an executor. However, an asynchronous-only node generally cannot be executed through invoke().

Also, synchronous graph execution does not necessarily mean that all internal nodes run sequentially. Independent branches can execute concurrently through the synchronous runtime.

Note: In Jupyter notebooks and asynchronous web frameworks, use await graph.ainvoke(...) inside the existing event loop instead of calling asyncio.run() again.

For additional method signatures, consult the LangGraph asynchronous invocation reference.

Asynchronous nodes

An asynchronous node is defined using async def. Like an ordinary node, it receives graph state and returns state updates.

The important difference is that it can await asynchronous operations without blocking the event loop.

Concurrent nodes within a graph

Consider a customer-support workflow that retrieves a customer profile and recent support tickets independently. A final node combines both results.

The following diagram shows the fan-out and fan-in execution pattern.

Asynchronous nodes diagram: START to Fetch Profile; START to Fetch Tickets; Fetch Profile to Combine Results; Fetch Tickets to Combine Results; Combine Results to END.

This example implements the complete workflow with simulated network operations.

Python
import asyncio
import time
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class SupportState(TypedDict, total=False):
    customer_id: str
    profile: str
    tickets: list[str]
    summary: str

async def fetch_profile(state: SupportState):
    await asyncio.sleep(1.5)

    return {
        "profile": f"{state['customer_id']}: Premium customer"
    }

async def fetch_tickets(state: SupportState):
    await asyncio.sleep(2)

    return {
        "tickets": ["Payment issue", "Delivery inquiry"]
    }

def combine_results(state: SupportState):
    return {
        "summary": (
            f"{state['profile']} | "
            f"{len(state['tickets'])} support tickets"
        )
    }

builder = StateGraph(SupportState)

builder.add_node("profile", fetch_profile)
builder.add_node("tickets", fetch_tickets)
builder.add_node("combine", combine_results)

builder.add_edge(START, "profile")
builder.add_edge(START, "tickets")
builder.add_edge(["profile", "tickets"], "combine")
builder.add_edge("combine", END)

graph = builder.compile()

async def main():
    started = time.perf_counter()

    result = await graph.ainvoke(
        {"customer_id": "CUST-101"}
    )

    print(result["summary"])
    print(f"Elapsed: {time.perf_counter() - started:.2f}s")

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
CUST-101: Premium customer | 2 support tickets
Elapsed: 2.00s

Sequential retrieval would require approximately 3.5 seconds. Concurrent retrieval takes approximately two seconds.

How LangGraph schedules concurrent nodes

LangGraph uses a superstep-based execution model inspired by Pregel.

Conceptually, the runtime selects eligible nodes, executes them, and applies their state updates at the superstep boundary. Nodes scheduled for the same superstep can execute concurrently.

In this example, both retrieval nodes receive the initial customer state. Neither requires the other’s output.

The explicit join:

Python
builder.add_edge(["profile", "tickets"], "combine")

ensures that the aggregation node waits for both branches.

If two concurrent nodes update the same state field, LangGraph needs an appropriate reducer to merge their updates. Without one, concurrent writes to an ordinary single-value field can raise InvalidUpdateError.

Prefer separate state fields for independent results or define a reducer such as Annotated[list[str], operator.add] when branches intentionally accumulate values.

See the Graph API overview for the underlying execution model.

Asynchronous model inference

Asynchronous nodes should also use asynchronous model interfaces.

The following example builds a minimal customer-support assistant using an asynchronous model call.

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

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

async def call_model(state: MessagesState):
    response = await model.ainvoke([
        SystemMessage(content="You are a concise support assistant."),
        *state["messages"],
    ])

    return {"messages": [response]}

builder = StateGraph(MessagesState)
builder.add_node("assistant", call_model)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)

graph = builder.compile()

async def main():
    result = await graph.ainvoke(
        {
            "messages": [
                HumanMessage(
                    content="How can I reset my password?"
                )
            ]
        },
        {"recursion_limit": 20},
    )

    print(result["messages"][-1].content)

if __name__ == "__main__":
    asyncio.run(main())

The expected result is a generated password-reset explanation. Its exact wording depends on the model.

The model request is awaited, allowing other workflows to progress while the provider generates a response. Native asynchronous provider integrations are preferable to executor-based asynchronous wrappers when handling substantial network concurrency.

Asynchronous tool execution

Agents regularly use tools to retrieve documents, query databases, call external APIs, or interact with enterprise systems.

Tools that perform network or database operations are strong candidates for asynchronous implementation.

LangChain’s @tool decorator supports coroutine functions directly.

Executing multiple asynchronous tools

The following example uses ToolNode to execute inventory and shipping lookups concurrently.

A deterministic AIMessage represents the tool requests that a real model would normally generate.

Python
import asyncio
import time
from langchain.tools import tool
from langchain.messages import AIMessage, ToolMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode

@tool
async def check_inventory(product_id: str) -> str:
    """Retrieve available inventory for a product."""
    await asyncio.sleep(1)
    return f"{product_id}: 15 units available"

@tool
async def check_shipping(product_id: str) -> str:
    """Retrieve the estimated shipping time for a product."""
    await asyncio.sleep(1.5)
    return f"{product_id}: ships in two days"

builder = StateGraph(MessagesState)
builder.add_node("tools", ToolNode([
    check_inventory,
    check_shipping,
]))

builder.add_edge(START, "tools")
builder.add_edge("tools", END)

graph = builder.compile()

async def main():
    request = AIMessage(
        content="",
        tool_calls=[
            {
                "name": "check_inventory",
                "args": {"product_id": "P101"},
                "id": "call-1",
                "type": "tool_call",
            },
            {
                "name": "check_shipping",
                "args": {"product_id": "P101"},
                "id": "call-2",
                "type": "tool_call",
            },
        ],
    )

    started = time.perf_counter()

    result = await graph.ainvoke({
        "messages": [request]
    })

    for message in result["messages"]:
        if isinstance(message, ToolMessage):
            print(message.content)

    print(f"Elapsed: {time.perf_counter() - started:.2f}s")

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
P101: 15 units available
P101: ships in two days
Elapsed: 1.50s

ToolNode handles concurrent tool execution and associates each response with its corresponding tool-call ID.

In a complete agent, the resulting tool messages return to the model, which can generate a final answer or request additional tools.

For a standard agent loop, use create_agent from langchain.agents. It supports asynchronous invocation and uses LangGraph internally. Choose ToolNode when constructing custom graph control flow.

See the ToolNode reference.

Calling an asynchronous tool directly

An asynchronous tool also exposes ainvoke() for independent execution and testing.

Python
import asyncio
from langchain.tools import tool

@tool
async def lookup_account(account_id: str) -> str:
    """Retrieve an account's current status."""
    await asyncio.sleep(0.2)
    return f"{account_id}: Active"

async def main():
    result = await lookup_account.ainvoke(
        {"account_id": "A101"}
    )
    print(result)

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
A101: Active

An asynchronous-only tool should not be called through its synchronous invoke() interface.

Independent read-only tools are usually safe to execute concurrently. Tools that modify shared records require transaction handling, conflict prevention, or deliberate sequencing.

Don’t block the event loop

One of the most common asynchronous programming mistakes is putting blocking operations inside an async def function.

Declaring a function asynchronous does not automatically make its contents non-blocking.

For example, the following operations can block an event loop:

  • time.sleep().
  • Synchronous HTTP requests.
  • Synchronous database queries.
  • Large CPU-intensive loops.
  • Synchronous model calls made directly inside asynchronous nodes.

Use asynchronous alternatives wherever possible.

Blocking operation Preferred asynchronous approach
time.sleep() await asyncio.sleep()
requests.get() httpx.AsyncClient.get() with await
model.invoke() await model.ainvoke()
Synchronous SQL driver Asynchronous SQL driver
Legacy blocking function await asyncio.to_thread()
CPU-heavy Python computation Process pool or external worker

Integrating legacy synchronous code

Sometimes an enterprise library has no asynchronous interface. Python’s asyncio.to_thread() can move blocking work into a separate thread.

The following example safely wraps a simulated legacy database operation inside an asynchronous graph node.

Python
import asyncio
import time
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict, total=False):
    record_id: str
    record: str

def legacy_database_lookup(record_id: str):
    time.sleep(1)
    return f"Record {record_id} retrieved"

async def lookup(state: State):
    result = await asyncio.to_thread(
        legacy_database_lookup,
        state["record_id"],
    )

    return {"record": result}

builder = StateGraph(State)
builder.add_node("lookup", lookup)
builder.add_edge(START, "lookup")
builder.add_edge("lookup", END)

graph = builder.compile()

async def main():
    results = await asyncio.gather(
        graph.ainvoke({"record_id": "101"}),
        graph.ainvoke({"record_id": "102"}),
    )

    print(results)

if __name__ == "__main__":
    asyncio.run(main())

Both database operations can overlap, producing their results in approximately one second instead of two.

Thread offloading is useful for blocking I/O, but thread capacity is finite. The underlying library must also be safe to use from the chosen thread.

Cancellation of the awaiting coroutine does not necessarily terminate work already running inside a worker thread.

For substantial CPU-intensive Python workloads, consider ProcessPoolExecutor or a dedicated computation service instead.

Tip: Reuse asynchronous HTTP clients and database connection pools across requests rather than creating a new connection for every tool invocation. Initialize and close these resources through your application’s lifecycle.

Concurrent workflows

Concurrency within a single graph improves request latency. Concurrency across graph executions improves the application’s capacity to serve many requests simultaneously.

A production agent server may receive hundreds of independent requests.

The following diagram shows how an application can limit concurrent workflow execution.

Concurrent workflows diagram: Incoming Requests to Request Queue; Request Queue to Concurrency Limiter; Concurrency Limiter to Graph Run One; Concurrency Limiter to Graph Run Two; Concurrency Limiter to Graph Run Three; Graph Run One to Results; Graph Run Two to Results; Graph Run Three to Results.

Bounded concurrency with asyncio.gather()

Starting thousands of graph executions simultaneously can exhaust connections, exceed model-provider quotas, and increase failure rates.

A semaphore limits how many operations enter a protected section concurrently.

This example processes six independent workflows with a maximum concurrency of three.

Python
import asyncio
import time
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict, total=False):
    document: str
    classification: str

async def classify(state: State):
    await asyncio.sleep(1)

    return {
        "classification": (
            "billing"
            if "invoice" in state["document"].lower()
            else "general"
        )
    }

builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_edge(START, "classify")
builder.add_edge("classify", END)

graph = builder.compile()

async def main():
    documents = [
        "Invoice payment",
        "Product question",
        "Invoice correction",
        "Delivery update",
        "Account information",
        "Invoice refund",
    ]

    semaphore = asyncio.Semaphore(3)

    async def process(document: str):
        async with semaphore:
            return await graph.ainvoke(
                {"document": document},
                {"recursion_limit": 20},
            )

    started = time.perf_counter()

    results = await asyncio.gather(
        *(process(document) for document in documents)
    )

    for result in results:
        print(result["classification"], result["document"])

    print(f"Elapsed: {time.perf_counter() - started:.2f}s")

if __name__ == "__main__":
    asyncio.run(main())

The six workflows execute in approximately two groups of three, taking roughly two seconds.

asyncio.gather() preserves input order in its returned results, even when individual executions finish in a different order.

For very large workloads, use a bounded queue with a fixed number of workers. A semaphore limits active operations but does not prevent gather() from scheduling a large number of waiting coroutines.

Batch execution

Compiled graphs also support abatch(), which offers a convenient interface for processing independent inputs.

Using the graph from the previous example:

Python
results = await graph.abatch(
    [
        {"document": "Invoice payment"},
        {"document": "Delivery update"},
        {"document": "Invoice refund"},
    ],
    config={
        "max_concurrency": 2,
        "recursion_limit": 20,
    },
    return_exceptions=True,
)

The result contains one output or exception per input.

Use abatch() for straightforward bulk processing and explicit semaphore-based scheduling when you require custom admission control, deadlines, or per-request behavior.

Runnable concurrency configuration is local to the relevant execution context; it is not a distributed service-wide quota.

Handling failures and cancellation

By default, asyncio.gather() propagates the first raised exception without automatically cancelling all remaining operations.

For independent batch jobs, return_exceptions=True allows successful results and failures to be collected together.

For related operations that should fail as a group, Python’s asyncio.TaskGroup provides structured concurrency and sibling cancellation when a task fails.

Production workflows also need:

  • Provider-level request timeouts and overall execution deadlines.
  • Retry policies for transient, retryable failures.
  • Idempotency keys for operations that produce external side effects.
  • Recursion limits to bound graph loops.
  • Rate limiting for requests and tokens, independently of concurrency limits.

An outer deadline can be implemented with asyncio.timeout() around an awaited invocation. LangGraph also supports asynchronous node timeouts through add_node(..., timeout=...).

A timeout does not reverse an external action that has already completed.

Asynchronous checkpointers and stores

Asynchronous graph execution requires compatible persistence infrastructure.

A checkpointer preserves graph execution state for a particular thread. A store holds application data and long-term memory that can be accessed across threads.

Component Development Async production
Checkpointer InMemorySaver AsyncPostgresSaver
Lightweight persistence AsyncSqliteSaver PostgreSQL preferred
Long-term store InMemoryStore AsyncPostgresStore

In-memory implementations are suitable for testing but lose their contents when the process terminates.

Using asynchronous persistence

Install the PostgreSQL integration for production persistence.

Terminal
pip install -U langgraph-checkpoint-postgres "psycopg[binary,pool]"

The following example supports both local in-memory execution and persistent PostgreSQL execution using the same asynchronous node.

For PostgreSQL mode, set DATABASE_URL to the connection string of an accessible PostgreSQL database.

Python
import asyncio
import os
from dataclasses import dataclass
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
from langgraph.store.postgres import AsyncPostgresStore

@dataclass
class Context:
    user_id: str

class State(TypedDict, total=False):
    message: str
    response: str

async def personalize(state: State, runtime: Runtime[Context]):
    store = runtime.store
    assert store is not None

    namespace = ("users", runtime.context.user_id)

    preference = await store.aget(namespace, "preferences")

    name = preference.value["name"] if preference else "customer"

    return {
        "response": f"Hello {name}, you said: {state['message']}"
    }

async def run_workflow(checkpointer, store):
    await store.aput(
        ("users", "U101"),
        "preferences",
        {"name": "Priya"},
    )

    builder = StateGraph(State, context_schema=Context)
    builder.add_node("personalize", personalize)
    builder.add_edge(START, "personalize")
    builder.add_edge("personalize", END)

    graph = builder.compile(
        checkpointer=checkpointer,
        store=store,
    )

    config = {
        "configurable": {"thread_id": "conversation-101"},
        "recursion_limit": 20,
    }

    result = await graph.ainvoke(
        {"message": "Check my account"},
        config,
        context=Context(user_id="U101"),
        durability="sync",
    )

    snapshot = await graph.aget_state(config)

    print(result["response"])
    print(snapshot.values)

async def main():
    database_url = os.getenv("DATABASE_URL")

    if database_url:
        async with (
            AsyncPostgresSaver.from_conn_string(
                database_url
            ) as checkpointer,
            AsyncPostgresStore.from_conn_string(
                database_url
            ) as store,
        ):
            await checkpointer.setup()
            await store.setup()

            await run_workflow(checkpointer, store)
    else:
        await run_workflow(
            InMemorySaver(),
            InMemoryStore(),
        )

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
Hello Priya, you said: Check my account
{'message': 'Check my account', 'response': 'Hello Priya, you said: Check my account'}

The example separates three different responsibilities:

  • thread_id identifies checkpointed graph execution state.
  • Runtime context identifies the user.
  • The store namespace isolates user-specific memory.

In production, derive user identity from trusted authentication rather than accepting arbitrary client-supplied identifiers.

The setup() operations initialize PostgreSQL persistence schemas and should normally be managed during deployment or initialization, not executed for every request.

Persistence during concurrent execution

Independent workflows should receive distinct thread IDs. Reuse a thread ID for successive turns in the same conversation, but serialize simultaneous writes to that conversation unless you have an explicit conflict-management strategy.

Asynchronous persistence also exposes methods such as:

  • graph.aget_state() and graph.aupdate_state().
  • graph.aget_state_history() through asynchronous iteration.
  • store.aget(), store.aput(), and store.asearch().

Execution mode and durability mode are separate concepts. An asynchronous invocation can use durability="sync" to require persisted progress before the next step. The "async" and "exit" modes offer different performance and crash-recovery trade-offs.

Consult the checkpointer reference and asynchronous PostgreSQL store reference when configuring production connections.

Which should I use?

Choose the execution model based on application requirements rather than assuming asynchronous code is always superior.

Application Recommended approach
Learning scripts invoke()
Simple command-line tools invoke()
Asynchronous REST API ainvoke()
Multi-user AI assistant ainvoke()
Concurrent document processing abatch() or bounded concurrency
Independent retrieval branches Concurrent graph nodes
CPU-intensive processing Separate processes or workers
Real-time asynchronous interface astream()

Production engineering considerations

Compile graphs during application initialization and reuse them. Keep request-specific data in state or runtime context rather than mutable global variables.

Set concurrency limits according to provider quotas, available database connections, memory capacity, and downstream service behavior. Remember that concurrent graph runs can each generate additional concurrent node executions and tool calls.

Measure throughput, median latency, p95 latency, error rates, and provider throttling under realistic load. Increasing concurrency beyond infrastructure capacity can reduce performance.

Use LangSmith tracing to inspect node timing, tool execution, and model latency.

Terminal
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="your-langsmith-key"
export LANGSMITH_PROJECT="async-langgraph"

For testing, begin with deterministic simulated I/O before introducing live providers. Verify state isolation, cancellation behavior, concurrent writes, and persistence recovery.

The examples in this lesson use illustrative concurrency limits and simulated timing values rather than measured production capacity. Their API usage has been checked against the official references; live model and PostgreSQL execution require the corresponding installed dependencies, credentials, and services.

Connecting to the next lesson

Asynchronous invocation allows an application to handle other work while a graph progresses. However, ainvoke() still provides the final output only when the invocation returns.

A real-time assistant must also deliver intermediate progress, generated tokens, retrieval results, and custom application events.

That is the purpose of streaming.

In the next lesson, Streaming — updates, values, tokens and custom events, you will extend these asynchronous execution patterns using stream() and astream().

Together, concurrency and streaming will provide the execution foundation for this chapter’s hands-on project: a real-time streaming AI assistant. The later Functional API lesson will demonstrate how the same asynchronous programming principles apply to workflows expressed using @entrypoint and @task.

Exercise

Build a concurrent order processing workflow

Build an asynchronous LangGraph workflow that retrieves an order's details and shipping status concurrently. Process multiple orders using asyncio.gather while limiting the number of simultaneously executing workflows to two. Add independent checkpoint threads for each order and verify that every workflow produces the correct result.

Python
import asyncio
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver

class OrderState(TypedDict, total=False):
    order_id: str
    details: str
    shipping: str
    summary: str

async def fetch_details(state: OrderState):
    # TODO: Simulate a 0.5-second database operation.
    raise NotImplementedError

async def fetch_shipping(state: OrderState):
    # TODO: Simulate a 0.7-second API operation.
    raise NotImplementedError

def summarize(state: OrderState):
    # TODO: Combine order details and shipping information.
    raise NotImplementedError

builder = StateGraph(OrderState)

# TODO: Register the three nodes.
# TODO: Execute both retrieval nodes in parallel.
# TODO: Join both branches before summarizing.

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

async def main():
    order_ids = ["ORD-101", "ORD-102", "ORD-103", "ORD-104"]

    # TODO: Create a semaphore with a capacity of two.
    # TODO: Invoke the graph asynchronously for each order.
    # TODO: Give each order a unique checkpoint thread.
    # TODO: Gather and verify all results.

if __name__ == "__main__":
    asyncio.run(main())

Summary

  • The invoke method blocks its caller until a graph finishes, whereas ainvoke cooperatively awaits graph execution.
  • Asynchronous nodes use async def and await to perform non-blocking I/O operations.
  • LangGraph can execute independent nodes concurrently in the same superstep.
  • Asynchronous tools integrate with ToolNode and create_agent to support concurrent external operations.
  • Blocking operations inside asynchronous functions can stall the entire event loop.
  • Semaphores, concurrency limits, timeouts, and independent checkpoint threads make concurrent workflows safer.
  • Asynchronous production applications should use compatible asynchronous checkpointers and persistent stores.