Graph versioning, performance, cost and production monitoring

Topic 5 of 5 in Deployment & LLMOps25 min readAdvancedFree course

Overview

Deploying an AI agent is not the end of its engineering lifecycle. It is the beginning of its operational lifecycle.

An agent running successfully on your laptop may behave very differently when thousands of users interact with it simultaneously. Conversations become longer, external services become unreliable, model usage increases, and checkpoints accumulate in persistent storage.

Meanwhile, business requirements change. You may need to introduce new tools, replace a model, modify approval workflows, or change the structure of graph state without interrupting existing conversations.

This creates four production engineering challenges:

  • Versioning: Changing the application without breaking existing threads.
  • Performance: Reducing response latency and increasing throughput.
  • Cost: Controlling model, infrastructure, and external service expenses.
  • Monitoring: Detecting failures, performance regressions, and declining answer quality.

Together, these responsibilities form an important part of LLMOps, the operational discipline required to maintain reliable LLM-powered applications.

In the previous lesson, you learned how Docker, Kubernetes, cloud infrastructure, and CI/CD pipelines make deployment repeatable. This lesson focuses on what happens inside and around the deployed application.

Install the core dependencies for the examples:

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

Use Python 3.11 or newer. Examples involving live models require an OPENAI_API_KEY. Record the exact tested dependency versions in your deployment lockfile rather than resolving new versions during every production build.

Graph versioning and backward compatibility

Why graph versioning matters

Traditional stateless APIs generally process each request independently. LangGraph applications can maintain execution state across multiple requests, failures, and human approvals.

A checkpoint can contain:

  • Conversation messages and application state.
  • Pending execution tasks and node identifiers.
  • Intermediate results.
  • Interrupt information.
  • Metadata required to continue execution.

When graph code changes, these previously persisted records remain.

LangGraph does not automatically pin every thread to the original version of your Python implementation. A resumed thread can encounter the newly deployed graph.

Consequently, graph upgrades must be designed as compatibility migrations rather than ordinary code replacements.

Consider a refund workflow that pauses at a node named approval. If a deployment removes that node while customers are waiting for approval, the runtime may no longer have a valid continuation point.

Even when the graph can resume technically, changing the refund eligibility rules halfway through a customer’s request can violate business expectations.

Different kinds of versioning

Version What it identifies Example
Application release Deployed code and dependencies 2.4.1
Graph version Workflow behavior and routing 2
State schema version Persisted data structure 3
Prompt version Instructions given to models support-v5
Model version Model identifier or snapshot gpt-5.4-mini
Knowledge revision Retrieval data freshness policy-2026-12

These versions need not change together. A prompt improvement may require no state migration, whereas changing a reducer could alter the meaning of historical state.

An assistant configuration version in Agent Server is also distinct from a graph code revision. Restoring an earlier assistant configuration does not necessarily restore the original Python implementation.

Understanding compatible changes

Change Compatibility consideration
Add an optional state field Usually compatible with older checkpoints
Add a new node Usually compatible if existing behavior remains valid
Change edges May alter the behavior of existing workflows
Rename a pending node Can break resumed execution
Remove an existing state field May discard data required by older workflows
Change a field type Requires compatibility handling or migration
Change reducer semantics Can change how persisted updates are interpreted
Reorder interrupt calls Can invalidate resume-value matching

Use an expand-and-contract migration: introduce new structures while supporting old ones, migrate or drain affected threads, and remove deprecated structures only after verifying that they are no longer required.

Implementing a backward-compatible upgrade

Imagine that version 1 of a refund workflow requires human approval, while version 2 introduces an additional policy check.

Existing version 1 requests must continue under their original business rules. New version 2 requests should execute the additional check.

The following diagram shows both versions sharing a compatible approval node.

Graph versioning and backward compatibility diagram: START to Record version; Record version to Human approval; Human approval to Approved?; Approved? to Reject refund (No); Approved? to Version two? (Yes); Version two? to Policy check (Yes); Version two? to Complete refund (No); Policy check to Complete refund; Complete refund to END; Reject refund to END.

The following complete example simulates a deployment upgrade while a thread is interrupted.

Python
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

class RefundState(TypedDict):
    amount: float
    workflow_version: NotRequired[int]
    approved: NotRequired[bool]
    policy_passed: NotRequired[bool]
    result: NotRequired[str]

checkpointer = InMemorySaver()

def build_graph(release: int):
    def intake(state: RefundState):
        return {
            "workflow_version": state.get(
                "workflow_version", release
            )
        }

    def approval(state: RefundState):
        decision = interrupt({
            "action": "Approve refund",
            "amount": state["amount"],
        })
        return {"approved": decision is True}

    def policy_check(state: RefundState):
        return {"policy_passed": state["amount"] <= 500}

    def complete(state: RefundState):
        allowed = (
            state["approved"]
            and state.get("policy_passed", True)
        )

        return {
            "result": "Refund approved" if allowed
            else "Refund rejected"
        }

    def route(state: RefundState):
        if (
            release >= 2
            and state.get("workflow_version", 1) >= 2
            and state["approved"]
        ):
            return "policy_check"

        return "complete"

    builder = StateGraph(RefundState)
    builder.add_node("intake", intake)
    builder.add_node("approval", approval)
    builder.add_node("complete", complete)

    destinations = ["complete"]

    if release >= 2:
        builder.add_node("policy_check", policy_check)
        builder.add_edge("policy_check", "complete")
        destinations.append("policy_check")

    builder.add_edge(START, "intake")
    builder.add_edge("intake", "approval")
    builder.add_conditional_edges(
        "approval", route, destinations
    )
    builder.add_edge("complete", END)

    return builder.compile(checkpointer=checkpointer)

v1 = build_graph(1)

old_config = {
    "configurable": {"thread_id": "refund-old"}
}

paused = v1.invoke({"amount": 800}, old_config)

assert paused["__interrupt__"]
print("Pending nodes:", v1.get_state(old_config).next)

v2 = build_graph(2)

old_result = v2.invoke(
    Command(resume=True),
    old_config,
)

new_config = {
    "configurable": {"thread_id": "refund-new"}
}

v2.invoke({"amount": 800}, new_config)

new_result = v2.invoke(
    Command(resume=True),
    new_config,
)

print("Old:", old_result["result"])
print("New:", new_result["result"])

assert old_result["workflow_version"] == 1
assert new_result["workflow_version"] == 2
assert old_result["result"] == "Refund approved"
assert new_result["result"] == "Refund rejected"

Expected output:

Text
Pending nodes: ('approval',)
Old: Refund approved
New: Refund rejected

The original thread retains version 1 because its version was persisted before the interruption. The new thread records version 2 during intake.

The node identifier approval remains unchanged, allowing the upgraded graph to resume the original checkpoint.

The example deliberately uses one refund per thread. For reusable conversation threads, define whether behavioral versions apply to the entire conversation or to individual business transactions.

Note: A node containing interrupt() restarts from its beginning when resumed. Preserve interrupt ordering and payload compatibility, and make operations performed before interruptions idempotent.

For additional compatibility rules, consult the official LangGraph backward compatibility guide.

Migrating production threads

Before deploying an incompatible change:

  1. Identify interrupted, running, and recoverable failed threads.
  2. Inspect checkpoints using get_state() and get_state_history().
  3. Test representative historical checkpoints against the candidate release.
  4. Introduce optional fields, compatibility readers, and stable node aliases.
  5. Deploy gradually and monitor resume failures.
  6. Remove compatibility code only when affected threads have completed or migrated.

You can explicitly update checkpointed state using update_state(config, values, as_node=...). However, this creates a new checkpoint, applies applicable reducers, and can influence subsequent execution. It is not equivalent to directly editing a database record.

For fundamentally incompatible workflows, register a separate graph identifier and route new threads to it. Keep the original graph available for existing threads.

Rollback must also be tested: an older application may not understand checkpoints created by the newer release. Backward compatibility alone does not guarantee safe downgrades.

Performance optimisation

Understand the sources of latency

End-to-end agent latency consists of several components:

Text
Total latency =
    Queue waiting time
  + Graph execution time
  + Model inference time
  + External tool latency
  + Checkpoint overhead
  + Network and serialization overhead

Sequential operations contribute their combined durations. Independent operations executed concurrently contribute approximately the duration of the slowest operation, plus coordination overhead.

Model inference frequently dominates latency, but overloaded databases, external APIs, excessive retries, and long queues can become equally important.

Measure at least:

  • p50: Median response time.
  • p95: Response time below which 95% of requests complete.
  • p99: Tail latency experienced by the slowest requests.
  • TTFT: Time to first generated token.
  • Throughput: Completed requests per unit of time.

An average latency of two seconds can conceal a p99 latency of thirty seconds.

Parallel execution

Suppose a support agent retrieves product information and company policies before composing an answer. Neither retrieval operation depends on the other.

Execute these operations concurrently rather than sequentially.

This diagram illustrates parallel retrieval followed by a synchronization point.

This diagram illustrates parallel retrieval followed by a synchronization point.

The following example uses asynchronous nodes to simulate independent network requests.

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

class State(TypedDict):
    question: str
    product: NotRequired[str]
    policy: NotRequired[str]
    answer: NotRequired[str]

async def product_lookup(state: State):
    await asyncio.sleep(1)
    return {"product": "Product warranty: 24 months"}

async def policy_lookup(state: State):
    await asyncio.sleep(1.5)
    return {"policy": "Returns accepted within 30 days"}

def combine(state: State):
    return {
        "answer": f"{state['product']}. {state['policy']}."
    }

builder = StateGraph(State)

builder.add_node("product_lookup", product_lookup)
builder.add_node("policy_lookup", policy_lookup)
builder.add_node("combine", combine)

builder.add_edge(START, "product_lookup")
builder.add_edge(START, "policy_lookup")

builder.add_edge(
    ["product_lookup", "policy_lookup"],
    "combine",
)

builder.add_edge("combine", END)

graph = builder.compile()

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

    result = await graph.ainvoke({
        "question": "What are the product policies?"
    })

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

asyncio.run(main())

Expected output:

Text
Product warranty: 24 months. Returns accepted within 30 days.
Latency: 1.51s

Sequential execution would require approximately 2.5 seconds.

Internally, LangGraph schedules independent nodes in the same super-step. Their updates become available to subsequent steps after synchronization. The list-based incoming edge ensures that combine waits for both retrieval nodes.

When parallel nodes update the same state field, define an appropriate reducer. Otherwise, concurrent updates may conflict.

Limit concurrency using execution configuration such as max_concurrency, and enforce service-wide concurrency limits separately. Excessive parallelism can increase rate-limit errors and database contention.

Node-level caching

Caching avoids repeating computations when equivalent inputs produce reusable results.

Good candidates include document retrieval, public catalog queries, deterministic transformations, and repeated classification tasks where reuse is acceptable.

The following example caches a simulated expensive document lookup.

Python
import time
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.cache.memory import InMemoryCache
from langgraph.types import CachePolicy

class State(TypedDict):
    query: str
    revision: str
    result: NotRequired[str]

def search_documents(state: State):
    print("Executing expensive lookup...")
    time.sleep(1)

    return {
        "result": f"Policy found for {state['query']}"
    }

builder = StateGraph(State)

builder.add_node(
    "search",
    search_documents,
    cache_policy=CachePolicy(ttl=300),
)

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

graph = builder.compile(cache=InMemoryCache())

request = {
    "query": "refund policy",
    "revision": "2026-12",
}

for attempt in range(2):
    started = time.perf_counter()
    graph.invoke(request)
    print(f"Latency: {time.perf_counter() - started:.3f}s")

Expected output:

Text
Executing expensive lookup...
Latency: 1.004s
Latency: 0.002s

The second invocation reuses the cached node result. The TTL specifies how long that result remains eligible for reuse.

LangGraph derives a cache key from node input by default. In larger graphs, unrelated state fields can reduce cache effectiveness. A carefully designed CachePolicy(key_func=...) can restrict the key to relevant inputs.

Include document revisions, model versions, authorization scope, and other result-affecting dependencies where applicable.

Never cache external mutations such as payment execution, email delivery, or account deletion. Avoid sharing cached private results across tenants.

InMemoryCache is suitable for demonstrations and single-process workloads. Distributed deployments require an appropriate shared cache strategy if cross-replica reuse is necessary.

See the Graph API documentation for node caching and execution semantics.

Checkpoint durability

Persistence protects workflows against failures but introduces storage overhead.

LangGraph provides three durability modes when checkpointing is enabled:

Mode Persistence behavior Trade-off
sync Persist changes before the next step Stronger recovery guarantees
async Persist while subsequent execution proceeds Lower blocking overhead
exit Persist when execution exits, including interruption or error Less intermediate crash recovery

Select a mode at invocation time using graph.invoke(inputs, config, durability="sync"), or the equivalent asynchronous invocation.

For critical approval workflows, prefer durability settings consistent with the required recovery guarantees. For short, repeatable computations, lower persistence overhead may be acceptable.

Checkpoint durability does not guarantee exactly-once execution of external side effects. Use transactional operations and idempotency keys where required.

Additional performance techniques

  • Reuse initialized model clients and database connection pools.
  • Avoid blocking synchronous I/O inside asynchronous nodes.
  • Stream partial responses using graph.stream(..., stream_mode=["updates", "messages"], version="v2").
  • Apply provider timeouts and narrowly scoped retry policies.
  • Store references instead of unnecessarily large documents in state.
  • Profile before consolidating nodes or removing persistence boundaries.

Streaming improves perceived responsiveness but does not necessarily reduce total execution time.

Cost optimisation

Understand agent economics

An agent can make multiple model calls during one user request. A seemingly inexpensive model can therefore generate substantial costs through repeated tool selection, reasoning, retrieval, and verification.

Calculate model cost using:

Text
Model cost =
    Uncached input tokens × input rate
  + Cached input tokens × cached input rate
  + Output tokens × output rate

Convert published per-million-token prices into per-token rates before multiplying.

Additional costs include embeddings, paid tools, vector databases, Agent Server infrastructure, trace ingestion, and external APIs.

For example, assume illustrative rates of $1 per million input tokens and $5 per million output tokens.

A run consuming 8,000 input tokens and 2,000 output tokens costs:

Text
Input cost  = $0.008
Output cost = $0.010
Total cost  = $0.018

At 100,000 equivalent runs, model expenditure alone reaches $1,800.

These rates are hypothetical, not provider quotations. Consult the model provider’s pricing and account for discounts, cached input, and billable reasoning tokens.

Measure actual token consumption

The following example measures token usage from an AI response and estimates its cost using illustrative rates.

Python
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage

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

response = model.invoke([
    HumanMessage(
        content="Explain checkpointing in three sentences."
    )
])

usage = response.usage_metadata

if usage is None:
    raise RuntimeError("Token usage unavailable")

input_tokens = usage["input_tokens"]
output_tokens = usage["output_tokens"]

cached_tokens = usage.get(
    "input_token_details", {}
).get("cache_read", 0)

uncached_tokens = input_tokens - cached_tokens

estimated_cost = (
    uncached_tokens * 1.00
    + cached_tokens * 0.10
    + output_tokens * 5.00
) / 1_000_000

print(response.text)
print("Usage:", usage)
print(f"Estimated cost: ${estimated_cost:.6f}")

The model generates an explanation and reports provider-supplied token metadata when available.

For a complete agent, aggregate usage across every model invocation, including billable retries and verification calls. The final AI message alone does not represent total run expenditure.

Reduce unnecessary model calls

Use deterministic Python logic when the decision does not require natural-language reasoning.

Checking a refund amount, validating JSON, applying an authorization rule, or calculating a total should normally be ordinary code.

Route straightforward language tasks to economical models and reserve more capable models for complex reasoning. Validate the routing strategy against an evaluation dataset rather than assuming smaller models are sufficiently accurate.

Control context growth and execution loops

Use bounded retrieval, message trimming, and conversation summarization to prevent prompts from growing indefinitely.

When trimming messages, preserve complete tool-call and tool-response relationships. Incomplete message sequences can cause provider validation errors.

Set explicit graph limits:

Python
config = {
    "configurable": {"thread_id": "support-123"},
    "recursion_limit": 20,
}

The recursion limit bounds graph super-steps, not tokens or individual tool calls. Also enforce model-call limits, tool budgets, output limits, and execution deadlines where appropriate.

Track cost per successful task, not merely cost per invocation. A cheaper model that repeatedly fails or requires additional correction may be more expensive overall.

Production monitoring

Observability and LangSmith tracing

Logs explain individual events. Metrics reveal aggregate behavior. Distributed traces connect the operations involved in one request.

LangSmith records nested model calls, graph execution, tool invocations, timing, and available usage information.

Configure tracing through environment variables:

Terminal
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="your-langsmith-api-key"
export LANGSMITH_PROJECT="support-agent-production"
export OPENAI_API_KEY="your-openai-api-key"

Use a secret manager in production instead of committing these values.

The following complete example attaches release metadata to a trace and records structured execution logs.

Python
import json
import logging
import time

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

logging.basicConfig(level=logging.INFO)

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

def respond(state: MessagesState):
    return {"messages": [model.invoke(state["messages"])]}

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

graph = builder.compile()

started = time.perf_counter()
status = "success"

try:
    result = graph.invoke(
        {"messages": [HumanMessage(content="What is LLMOps?")]},
        config={
            "run_name": "support-request",
            "tags": ["production", "release-2.4.1"],
            "metadata": {
                "graph_version": 2,
                "prompt_version": "support-v5",
            },
            "recursion_limit": 10,
        },
    )

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

except Exception:
    status = "error"
    raise

finally:
    logging.info(json.dumps({
        "event": "agent_completed",
        "release": "2.4.1",
        "status": status,
        "latency_ms": round(
            (time.perf_counter() - started) * 1000, 2
        ),
    }))

The run appears in the configured LangSmith tracing project when tracing is enabled and connectivity is available.

The structured log records latency and execution status without including the user’s message.

Define production indicators

Establish service-level indicators and objectives based on actual workload requirements.

Indicator Illustrative target
Successful execution rate At least 99.5%
p95 response latency Under 5 seconds
Model cost per completed task Under $0.03
Tool failure rate Below 1%
Answer quality pass rate At least 95%
Resume compatibility failures Zero

These are example objectives, not universal production standards.

Monitor infrastructure indicators such as queue depth, worker utilization, PostgreSQL connections, checkpoint growth, and Redis connectivity. Segment application metrics by release, model, and workflow version.

A graph returning HTTP 200 can still produce an incorrect answer. Use offline regression evaluations before deployment and sampled online evaluations afterward.

LangSmith’s observability capabilities support trace inspection, dashboards, alerts, and evaluation workflows.

Tip: Do not assume application log redaction also sanitizes traces. Apply privacy controls to tracing inputs, outputs, tool arguments, checkpoint retention, and access permissions independently.

Project: deploy the complete agent

Bring together the deployment techniques from Chapter 19 by creating a support agent served through Agent Server and accessed through Streamlit.

The project uses a read-only company-policy tool, persistent conversation threads, explicit recursion limits, and release metadata.

Step 1: Create the agent

Save the following as agent.py.

Python
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain.tools import tool

@tool
def lookup_policy(topic: str) -> str:
    """Retrieve a company policy for a supported topic."""
    policies = {
        "refund": "Refunds are available within 30 days.",
        "warranty": "The warranty lasts 24 months.",
        "shipping": "Standard shipping takes 3-5 business days.",
    }

    return policies.get(
        topic.lower().strip(),
        "Policy not found. Contact human support.",
    )

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

graph = create_agent(
    model=model,
    tools=[lookup_policy],
    system_prompt=(
        "You are a customer support assistant. "
        "Use lookup_policy for company policy questions. "
        "Never invent company policies. "
        "Keep responses concise and accurate."
    ),
)

The high-level create_agent API constructs a LangGraph-backed agent with model and tool execution capabilities.

Agent Server manages deployment persistence, so this graph does not embed an InMemorySaver.

Step 2: Configure Agent Server

Create requirements.txt:

Text
langgraph>=1,<2
langchain>=1,<2
langchain-openai
langsmith

Create langgraph.json:

JSON
{
  "dependencies": ["."],
  "graphs": {
    "support": "./agent.py:graph"
  },
  "env": ".env"
}

Create .env containing the required model credentials and LangSmith tracing configuration. Exclude it from version control.

Install dependencies and start the local server:

Terminal
pip install -r requirements.txt
pip install "langgraph-cli[inmem]" langgraph-sdk streamlit
langgraph dev

The development API normally runs at http://127.0.0.1:2024.

Step 3: Verify the API

Save this integration test as test_api.py.

Python
import asyncio
from langgraph_sdk import get_client

async def main():
    client = get_client(url="http://127.0.0.1:2024")

    thread = await client.threads.create()

    result = await client.runs.wait(
        thread["thread_id"],
        "support",
        input={
            "messages": [
                {
                    "role": "user",
                    "content": "What is your refund policy?",
                }
            ]
        },
        config={"recursion_limit": 15},
        metadata={"release": "1.0.0"},
    )

    answer = result["messages"][-1]["content"]
    print(answer)

asyncio.run(main())

Run:

Terminal
python test_api.py

The expected answer should state that refunds are available within 30 days. Exact wording may vary.

Step 4: Connect a user interface

Save the following as ui.py.

Python
import os
import streamlit as st
from langgraph_sdk import get_sync_client

client = get_sync_client(
    url=os.getenv(
        "AGENT_SERVER_URL",
        "http://127.0.0.1:2024",
    )
)

st.title("Customer Support Agent")
st.caption("LangGraph production deployment project")

if "thread_id" not in st.session_state:
    thread = client.threads.create()
    st.session_state.thread_id = thread["thread_id"]
    st.session_state.history = []

for message in st.session_state.history:
    with st.chat_message(message["role"]):
        st.write(message["content"])

if prompt := st.chat_input("Ask about company policies"):
    st.session_state.history.append({
        "role": "user",
        "content": prompt,
    })

    with st.chat_message("user"):
        st.write(prompt)

    with st.chat_message("assistant"):
        with st.spinner("Retrieving information..."):
            result = client.runs.wait(
                st.session_state.thread_id,
                "support",
                input={
                    "messages": [
                        {"role": "user", "content": prompt}
                    ]
                },
                config={"recursion_limit": 15},
                metadata={"release": "1.0.0"},
            )

            answer = result["messages"][-1]["content"]
            st.write(answer)

    st.session_state.history.append({
        "role": "assistant",
        "content": answer,
    })

Start the interface in another terminal:

Terminal
streamlit run ui.py

Ask about refunds, then ask a follow-up question. The frontend reuses its thread identifier, allowing the server to maintain conversation continuity.

This demonstration uses a local server and fictional company policies. Public deployment requires authenticated users, server-side authorization for thread access, request validation, rate limits, protected credentials, and robust error handling.

Step 5: Release and validate

Validate the application using production-like infrastructure:

Terminal
langgraph up

This Docker-based environment includes the relevant Agent Server infrastructure, including PostgreSQL and Redis. Use langgraph deploy or the LangSmith deployment interface for supported hosted deployments.

Consult the official deployment guide for hosting, authentication, and licensing requirements.

Before promoting the release, verify:

  • Historical threads remain resumable after an upgrade.
  • Conversation state survives infrastructure restarts.
  • Concurrent requests remain within latency and cost objectives.
  • Unauthorized users cannot access another user’s threads.
  • Tool failures and model timeouts are handled appropriately.
  • Traces, dashboards, and alerts are operational.
  • Evaluation datasets show acceptable answer quality.
  • Rollback procedures preserve compatible checkpoint data.

Deploy an immutable, tested release to staging before directing production traffic to it. Use gradual traffic promotion or separate versioned deployments when infrastructure permits.

The examples follow the LangGraph 1.x and LangChain 1.x API conventions. Their expected outputs are illustrative; live model calls, cloud deployment, and infrastructure-dependent behavior must be validated in your own environment.

In the next lesson, Capstone: an enterprise multi-agent AI assistant, you will extend this operational foundation to coordinated specialist agents, enterprise integrations, persistent memory, human approvals, security boundaries, and production evaluation.

Exercise

Build a version-aware and cached workflow

Build a document lookup graph that records the workflow version, caches expensive read operations, and measures execution latency. Ensure that identical requests reuse cached results while changes to the document revision invalidate the cache. Verify the behavior using assertions and compare cold and warm execution times.

Python
# pip install "langgraph>=1,<2"

import time
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.cache.memory import InMemoryCache
from langgraph.types import CachePolicy

class State(TypedDict):
    query: str
    document_revision: str
    workflow_version: NotRequired[int]
    answer: NotRequired[str]

lookup_calls = 0

def lookup(state: State):
    global lookup_calls
    lookup_calls += 1
    time.sleep(0.5)
    # TODO: Return the lookup result and workflow version.
    raise NotImplementedError

builder = StateGraph(State)

# TODO: Register the node with a CachePolicy.
# TODO: Connect START and END.
# TODO: Compile with InMemoryCache.
# TODO: Measure two identical requests.
# TODO: Change document_revision and verify a cache miss.

Summary

  • Persisted checkpoints create a compatibility contract between historical thread state and newly deployed graph code.
  • Stable node identifiers and explicit workflow versions help existing threads survive application upgrades.
  • Parallel execution, asynchronous I/O, and carefully scoped caching reduce unnecessary execution latency.
  • Token budgets, intelligent model selection, and bounded agent loops control operational costs.
  • Checkpoint durability should balance recovery requirements against persistence overhead.
  • Production monitoring must cover infrastructure health, execution reliability, model costs, and answer quality.
  • Production releases require compatibility testing, measurable acceptance criteria, gradual rollout, and a tested rollback strategy.