LangChain in Production: Patterns That Work and Anti-Patterns That Don't
Running LangChain 1.x in production: the anti-patterns that cause failures, the patterns that hold up, with create_agent middleware, caching and cost-control code.
The Production Gap#
Moving LangChain applications from prototype to production reveals a gap between documentation examples and real-world requirements. What works perfectly in development can become costly, slow, or unreliable under production load.
Prototype workloads hide failure modes that only surface at scale: agents that loop on ambiguous inputs, token spend that climbs with every conversation turn, and silent failures that reach you as user complaints. The framework’s abstractions accelerate prototyping but obscure the cost, latency, and reliability levers you need under production load.
The default that holds up: bound every resource explicitly (memory tokens, agent iterations, execution time, output length), wire tracing in before the first chain runs, and drop to the provider SDK wherever the abstraction buys you nothing.
The code targets LangChain 1.1 or later on Python 3.10+. LangChain 1.0 shipped in October 2025. It moved AgentExecutor, the legacy chains and the old memory classes into the separate langchain-classic package, and it made create_agent with middleware the way to build agents. Version 1.1 added the summarization triggers and model-retry middleware. Code that still imports AgentExecutor or calls .run() is running on deprecated APIs.
Understanding the Framework Trade-off#
LangChain solved early LLM integration complexity by providing standard abstractions for prompts, chains, agents, and memory management. This made prototyping significantly faster. What might take weeks with direct API calls could be done in days.
However, these abstractions introduce their own challenges:
The velocity-control trade-off: Rapid prototyping comes at the cost of transparency. When something goes wrong in production, debugging through multiple abstraction layers becomes significantly harder than debugging a direct API call.
Hidden behaviors: Framework internals make decisions that aren’t always visible: memory trimming strategies, automatic retries, callback execution order. These work fine until they don’t, and diagnosing why requires deep-diving into source code.
Performance overhead: Every abstraction layer runs on every request: callback dispatch, message conversion, middleware hooks. Whether that is visible next to the model call is an empirical question. Profile before assuming either way, because a guess in either direction leads to optimizing the wrong thing.
The framework inflection point occurs when your team spends more time debugging framework behavior than building features. Some teams hit this quickly, others never do.
The 7 Deadly Anti-Patterns#
1. Unbounded Memory Accumulation#
An agent with a checkpointer keeps every turn of the thread, and nothing trims it by default:
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
# Anti-pattern: every turn is appended to the thread and resent to the model
agent = create_agent(
model="openai:gpt-4.1-mini",
tools=tools,
checkpointer=InMemorySaver(),
)
# After 50 exchanges: massive context, slow responses, high costs
Every request resends the full history, so cost and latency both grow with conversation length. Eventually the context window overflows and requests start failing outright. Track token usage trends over time and flag conversations whose response times keep growing.
The fix is a summarization step with explicit limits. SummarizationMiddleware replaces the deprecated ConversationSummaryBufferMemory:
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware
from langgraph.checkpoint.memory import InMemorySaver
agent = create_agent(
model="openai:gpt-4.1-mini",
tools=tools,
middleware=[
SummarizationMiddleware(
model="openai:gpt-4.1-mini",
trigger=("tokens", 4000), # summarize once history passes 4,000 tokens
keep=("messages", 20), # keep the 20 most recent messages verbatim
),
],
checkpointer=InMemorySaver(),
)
# Older turns collapse into a summary, so tokens per request stay bounded
The cost is one extra model call each time the trigger fires, and the summary loses detail. The middleware also keeps an AI message and its tool results on the same side of the cut, which a hand-rolled trim easily gets wrong.
2. Agent Without Guardrails#
Creating agents without execution controls:
from langchain.agents import create_agent
# Anti-pattern: no cap on model calls, tool calls or wall-clock time
agent = create_agent(model="openai:gpt-4.1-mini", tools=tools)
# Nothing here stops the agent bouncing between search and summarize
# until the graph's recursion limit raises an error
A ReAct loop that never satisfies its stop condition keeps calling tools until something external kills it. Every iteration is a paid LLM call, and the user is staring at a spinner the whole time. Cost alerts and execution time monitoring need to exist before this reaches production.
Explicit controls in configuration put a hard stop on it. The max_iterations and max_execution_time pair from AgentExecutor maps onto a call-limit middleware and a timeout around the run:
import asyncio
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddleware
from langchain_openai import ChatOpenAI
agent = create_agent(
model=ChatOpenAI(model="gpt-4.1-mini", timeout=30, max_retries=2),
tools=tools,
middleware=[
ModelCallLimitMiddleware(run_limit=5), # was max_iterations=5
ToolCallLimitMiddleware(run_limit=10), # cap tool calls per run
],
)
async def answer(query: str) -> dict:
# was max_execution_time=30: one wall-clock cap for the whole run
return await asyncio.wait_for(
agent.ainvoke({"messages": [{"role": "user", "content": query}]}),
timeout=30,
)
When the model-call limit is reached, the middleware ends the run gracefully, so the caller still gets a response. The timeout raises asyncio.TimeoutError, which the caller has to turn into a fallback answer.
3. Over-Abstraction for Simple Tasks#
Using full LangChain abstractions for straightforward operations:
// Anti-pattern: three abstractions around one fixed prompt
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
const chatModel = new ChatOpenAI({ model: "gpt-4.1-mini" });
const outputParser = new StringOutputParser();
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a helpful translator."],
["user", "Translate {text} to {language}"]
]);
const chain = prompt.pipe(chatModel).pipe(outputParser);
// Direct API: Same result, no framework overhead
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.chat.completions.create({
model: "gpt-4.1-mini",
messages: [
{ role: "system", content: "You are a helpful translator." },
{ role: "user", content: `Translate ${text} to ${language}` }
]
});
Unnecessary complexity, harder debugging, and team cognitive load pile up for tasks that don’t benefit from the abstraction. Count the layers during code review: a prompt template, a model wrapper and an output parser around a single fixed prompt is the signal to reach for the direct API instead.
4. Optimizing Latency on a Guess#
The opposite mistake is a hand-rolled “fast path” built on a guess:
# Anti-pattern: count-based trimming, chosen without a measurement
history = history[-10:]
# The window can open on a ToolMessage whose AIMessage tool call was cut off,
# and nobody measured whether the framework path was slow in the first place
A chat history is only valid when every ToolMessage follows the AIMessage that requested it. Cutting by message count ignores that rule, and it ignores token size too: ten short messages and ten pasted documents count the same.
Measure first. Time the same prompt through the chain and through a direct SDK call over a few hundred requests, and compare p50 and p95. If the gap matters, fix the step that causes it. For history, trim by tokens with trim_messages:
from langchain_core.messages import trim_messages
from langchain_core.messages.utils import count_tokens_approximately
window = trim_messages(
history,
strategy="last", # keep the most recent messages
token_counter=count_tokens_approximately,
max_tokens=2000,
start_on="human", # never open on an orphaned ToolMessage
include_system=True, # keep the system prompt
)
Inside create_agent, the same call belongs in a before_model middleware, or SummarizationMiddleware handles it for you. The approximate counter is fast and needs no tokenizer; pass the chat model as token_counter when the budget has to be precise.
5. Shipping Development Defaults#
Production deployments with development defaults:
# Anti-pattern: Development defaults in production
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4.1-mini")
# No caching, no output limits, no timeout, no cost controls
High operational costs, slow responses, and verbose logging filling disk space stay invisible until you baseline cost and latency metrics before the production launch.
Explicit production configuration puts a floor under all three:
import os
from langchain_core.globals import set_llm_cache
from langchain_openai import ChatOpenAI
from langchain_redis import RedisCache
# Exact-match cache: the key is the serialized prompt plus the model's parameters
set_llm_cache(RedisCache(
redis_url=os.environ["REDIS_URL"],
ttl=86_400, # one day; without ttl, entries never expire
))
llm = ChatOpenAI(
model="gpt-4.1-mini",
temperature=0, # extraction and classification: low-variance output is safe to cache
max_tokens=512, # Limit output length
timeout=30, # Timeout for API calls
max_retries=2, # Controlled retry behavior
)
# Prompts that carry personal data skip the shared cache
pii_llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0, cache=False)
Three details matter here. First, an exact-match cache and a high temperature work against each other: the first sampled answer is stored and returned to everyone who sends the same prompt, so the variety the temperature was meant to add disappears. Use temperature=0 for the tasks you cache. Second, set_llm_cache is process-wide, and every chat model in the process reads and writes it. Third, the cache stores full prompts and answers in Redis. Two tenants share an entry only when their prompts are byte-identical, but anything with personal data still lands in a store every service with Redis access can read. Disable caching for those models with cache=False, as pii_llm does above.
6. Black-Box Agent Behavior#
Deploying agents without observability:
# Anti-pattern: no tracing configured, no run metadata
agent = create_agent(model="openai:gpt-4.1-mini", tools=tools)
result = agent.invoke({"messages": [{"role": "user", "content": query}]})
# When this fails silently, you have no idea why
Silent failures, impossible debugging, and discovering issues only through user complaints follow. There is nothing to detect until traces exist, which is precisely the problem.
LangSmith tracing from day one changes that:
# LANGSMITH_TRACING=true, LANGSMITH_API_KEY and LANGSMITH_PROJECT come from the
# deployment environment and the secret store; the key never appears in code
agent = create_agent(model="openai:gpt-4.1-mini", tools=tools)
result = agent.invoke(
{"messages": [{"role": "user", "content": query}]},
config={"tags": ["prod"], "metadata": {"tenant_id": tenant_id}},
)
# Model calls, tool calls, latency and token usage now show up in LangSmith,
# filterable by tag and tenant
7. Underestimating Data Ingestion#
Underestimating RAG pipeline complexity:
# Anti-pattern: Assuming document loading "just works"
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("document.pdf")
documents = loader.load()
# Parser choice, encoding and chunking are where RAG projects actually stall
Wrong PDF parser for your document types, encoding issues with international text, and chunking problems that degrade retrieval quality show up as high failure rates in document processing and poor retrieval results.
Pick the parser and the splitter from the shape of the documents, then verify with real samples:
| Input | Start with | What it costs |
|---|---|---|
| Born-digital PDFs with a text layer, mostly prose | PyPDFLoader (pypdf) | Reads the text layer only; tables come out as loosely positioned text |
| Scanned or image-only PDFs | UnstructuredLoader with strategy="ocr_only" | Model inference is much slower than text extraction, and OCR errors carry into retrieval |
| Tables and multi-column layouts that must survive | UnstructuredLoader with strategy="hi_res" | Slower than text extraction; needs the layout-model dependencies |
| Plain prose after extraction | RecursiveCharacterTextSplitter | chunk_size counts characters by default (length_function=len) |
| Markdown or HTML with real headings | A header-based splitter such as MarkdownHeaderTextSplitter | Uneven chunk sizes; very long sections still need a second pass |
| A hard token limit on the embedding model | RecursiveCharacterTextSplitter.from_tiktoken_encoder | Needs tiktoken, and the encoding should match the model |
PyPDFLoader still lives in langchain-community, which LangChain sunset in May 2026; pin that package or call pypdf directly. UnstructuredLoader comes from the separate langchain-unstructured package. In code, the table becomes a cheap first attempt with a validated fallback:
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_unstructured import UnstructuredLoader
def load_pdf(path: str):
docs = PyPDFLoader(path).load()
# pypdf reads only the text layer: near-empty pages usually mean a scan
if not validate_extraction(docs):
docs = UnstructuredLoader(path, strategy="ocr_only").load()
if not validate_extraction(docs):
raise ValueError(f"No usable text extracted from {path}")
return docs
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000, # measured in characters
chunk_overlap=200, # Maintain context across chunks
)
chunks = splitter.split_documents(load_pdf("document.pdf"))
Production-Ready Patterns#
Each pattern below has a price. The table summarizes when it fits and when to leave it out:
| Pattern | Use it when | Skip it when | What it costs |
|---|---|---|---|
| LCEL-first architecture | Several steps (prompt, model, parser, retriever) need streaming or batching | One fixed prompt and one model call | One more layer to debug |
| Explicit resource controls | Any agent or tool loop | No exception; only the values change | A run can stop before it finds the answer; limits need tuning against traces |
| Multi-tier caching | Identical prompts repeat at temperature=0 | Personalized prompts, sampled or creative output, streaming calls | Stale answers until the TTL expires; another store to run |
| Observability-first | Anything that reaches users | Throwaway experiments | Prompts and outputs land in the tracing backend, so data-handling rules apply there too |
| Smart model routing | A large share of traffic is easy | Uniformly hard traffic, or low volume | A classifier call per request, plus worse answers on every misroute |
| Structured outputs | Code consumes the answer | Free-form text for humans | A schema to maintain; a call fails when the output does not validate |
LCEL-First Architecture#
Modern LangChain applications use LCEL (LangChain Expression Language) for better composability:
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
# LCEL: Readable pipe syntax with built-in streaming
chain = (
ChatPromptTemplate.from_template("Analyze: {input}")
| ChatOpenAI(model="gpt-4.1-mini", streaming=True)
| StrOutputParser()
)
# Supports streaming, batching, async out of the box
for chunk in chain.stream({"input": query}):
print(chunk, end="", flush=True)
LCEL gives clear composition, built-in async support, and easier debugging than legacy chains, and it pays off most in complex workflows that chain multiple LLM calls, transformations, or conditional logic.
Explicit Resource Controls#
Production configuration should make limits explicit. Keep two mechanisms apart: a limit stops spend inside the run, and an alert reports after the run. An alert alone never prevents an overrun.
from typing import Any
from langchain.agents import AgentState, create_agent
from langchain.agents.middleware import (
ModelCallLimitMiddleware,
ToolCallLimitMiddleware,
before_model,
)
from langchain.messages import AIMessage
from langchain_core.callbacks import get_usage_metadata_callback
from langgraph.runtime import Runtime
RUN_TOKEN_BUDGET = 20_000 # limit: enforced before every model call
ALERT_TOKENS = 10_000 # alert: reported once the run finishes
@before_model(can_jump_to=["end"])
def token_budget(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
# usage_metadata is provider-neutral: the same field for every integration that reports usage
spent = sum(
(m.usage_metadata or {}).get("total_tokens", 0)
for m in state["messages"]
if isinstance(m, AIMessage)
)
if spent >= RUN_TOKEN_BUDGET:
return {
"messages": [AIMessage("Token budget reached for this request.")],
"jump_to": "end",
}
return None
agent = create_agent(
model=llm,
tools=tools,
middleware=[
ModelCallLimitMiddleware(run_limit=5), # Stop after 5 model calls
ToolCallLimitMiddleware(run_limit=10), # Stop after 10 tool calls
token_budget,
],
)
with get_usage_metadata_callback() as usage:
result = agent.invoke({"messages": [{"role": "user", "content": query}]})
# usage.usage_metadata maps each model name to its summed token counts
total = sum(u["total_tokens"] for u in usage.usage_metadata.values())
if total > ALERT_TOKENS:
send_alert(f"High-token request: {total} tokens")
The budget check runs before each model call, so one call can still overshoot it by its own input and max_tokens. With a checkpointer, state["messages"] holds the whole thread, and the same check becomes a per-conversation budget. For a per-request budget, count only the messages after the latest human message. Convert tokens to money with your own price table; the callback reports token counts only.
Implementation checklist:
- Token limits on memory and outputs
- Agent iteration caps and timeouts
- Token budgets as limits, cost reports as alerts
- Retry limits and exponential backoff
Multi-Tier Caching Strategy#
Caching dramatically reduces costs and latency:
from langchain_core.caches import InMemoryCache
from langchain_core.globals import set_llm_cache
from langchain_redis import RedisCache
# Development: In-memory cache, empty again after every restart
# set_llm_cache(InMemoryCache())
# Production: Distributed Redis cache shared by every replica
set_llm_cache(RedisCache(
redis_url="redis://redis.production.internal:6379/0",
ttl=86_400, # one TTL per cache instance
))
# Content with a different shelf life needs its own cache instance,
# passed to that model with ChatOpenAI(..., cache=other_cache)
# Invalidation: Manual or event-driven for updated content
A cache hit skips the API call entirely, so the payoff tracks how repetitive your traffic actually is. Measure the hit rate before you count the savings. The model cache does not apply to streaming calls, so a chain that only ever calls .stream() gets no benefit from it.
Observability-First Development#
Set up tracing before writing your first chain, and make the service refuse to start without it:
import os
# Values come from the deployment environment and the secret store
if os.environ.get("LANGSMITH_TRACING", "").lower() != "true":
raise RuntimeError("LANGSMITH_TRACING must be 'true'; refusing to start without tracing")
for name in ("LANGSMITH_API_KEY", "LANGSMITH_PROJECT"):
if not os.environ.get(name):
raise RuntimeError(f"{name} is not set; refusing to start without tracing")
# Tags and metadata make traces filterable; ProductionMetrics is defined
# under Essential Production Metrics below
result = chain.invoke(
{"input": query},
config={
"tags": ["prod"],
"metadata": {"tenant_id": tenant_id},
"callbacks": [ProductionMetrics()],
},
)
Metrics worth tracking:
- Performance: QPS, latency percentiles (p50, p95, p99), time-to-first-token
- Cost: Total tokens, cost per request, daily burn rate
- Quality: Error rates, retry counts, user feedback
- Agent behavior: Tool selections, iteration counts, decision paths
Smart Model Routing#
Route requests to appropriate models based on complexity. A keyword filter makes a poor router: a rule that sends every query containing “performance” to the premium model misroutes in both directions. A cheap model with structured output makes a better first classifier:
from typing import Literal
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
# Define models with cost/capability trade-offs (prices in the table below)
cheap_model = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
premium_model = ChatOpenAI(model="gpt-4.1", temperature=0)
class Route(BaseModel):
tier: Literal["simple", "complex"]
ROUTER_PROMPT = (
"Label the request 'complex' if it needs multi-step reasoning, "
"comparison across several sources, or code changes. "
"Otherwise label it 'simple'."
)
router = cheap_model.with_structured_output(Route)
def route_to_model(query: str) -> ChatOpenAI:
"""Route on the classifier's label"""
route = router.invoke([("system", ROUTER_PROMPT), ("user", query)])
return premium_model if route.tier == "complex" else cheap_model
# Dynamic routing in chain
def create_chain(query: str):
model = route_to_model(query)
prompt = ChatPromptTemplate.from_template("{input}")
return prompt | model
The classifier adds one cheap call to every request, so routing only pays off when the premium model is several times more expensive than the router. Once you have labelled traffic, a small trained classifier can replace the LLM call.
| Model | Input, per 1M tokens | Output, per 1M tokens |
|---|---|---|
| gpt-4o-mini | $0.15 | $0.60 |
| gpt-4.1-mini | $0.40 | $1.60 |
| gpt-4.1 | $2.00 | $8.00 |
These are OpenAI’s standard-tier list prices as shown on the OpenAI pricing page (opens in new tab) in November 2026. Prices change, so take current numbers from that page before you model savings. gpt-4o-mini is cheaper still as a low tier if it passes your labelled sample.
Savings scale with the share of traffic the cheap model can absorb, and every misroute buys that saving with a worse answer. Score the router against a labelled sample before trusting it.
Structured Outputs with Pydantic#
Type-safe outputs reduce post-processing bugs. with_structured_output binds the schema to the model call, so the prompt needs no hand-written format instructions:
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
# Define output schema
class ProductAnalysis(BaseModel):
sentiment: str = Field(description="positive, negative, or neutral")
key_features: list[str] = Field(description="list of mentioned features")
price_mentioned: bool = Field(description="whether price was discussed")
confidence_score: float = Field(description="confidence from 0 to 1")
structured_llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0).with_structured_output(
ProductAnalysis
)
# Type-safe output
result = structured_llm.invoke(f"Analyze this product review:\n{review_text}")
print(f"Sentiment: {result.sentiment}, Confidence: {result.confidence_score}")
Inside an agent, create_agent(..., response_format=ToolStrategy(ProductAnalysis)) (with ToolStrategy from langchain.agents.structured_output) gives the same contract for the final answer. Type safety, automatic validation, and clear contracts between the LLM and downstream code are the payoff.
The Migration Decision Matrix#
Choosing the right approach depends on your specific requirements:
When to Use LangChain#
- Complex multi-agent systems requiring orchestration
- RAG with multiple retrievers and re-ranking
- Teams needing standard abstractions for collaboration
- Rapid prototyping phase with plans for production hardening
- Heavy reliance on LangSmith observability ecosystem
Example: LinkedIn describes its internal SQL Bot (opens in new tab) as a multi-agent system built on top of LangChain and LangGraph.
The LlamaIndex Alternative#
- Primary focus on search and retrieval
- Large dataset indexing requirements
- Need for efficient semantic similarity search
- Simpler, more focused use case than general orchestration
Skipping the Framework Entirely#
- Simple chatbot or completion tasks
- Clear, unchanging requirements
- Performance-critical applications where latency matters
- Small team wanting full control
- Minimal external dependencies desired
Example implementation:
from openai import OpenAI
client = OpenAI()
# Clear, explicit, fast
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
],
max_tokens=512,
temperature=0.7
)
answer = response.choices[0].message.content
Signs It’s Time to Migrate#
Consider migration when:
- Team spends more time debugging framework behavior than building features
- Performance profiling puts framework overhead ahead of the LLM call on the critical path
- Requirements don’t fit LangChain’s patterns and you’re fighting the framework
- Dependency management becomes a maintenance burden
Migration approach: Incremental replacement, starting with highest-impact components. Keep what works, replace what doesn’t.
LangGraph: Production Evolution#
LangGraph emerged in 2024 as a production-focused evolution, designed from lessons learned deploying LangChain agents. Since 1.0, create_agent itself runs on LangGraph; dropping to the graph API directly is for control flow that a single agent loop cannot express.
Key differences:
- Low-level, controllable framework without hidden behaviors
- No hidden prompts or automatic cognitive architecture
- Durable execution for complex agentic systems
- State management across long-running workflows
Hybrid pattern:
from typing import Annotated, TypedDict
from langchain_core.messages import AnyMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
# Define state: the add_messages reducer merges updates into the list
class AgentState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
current_step: str
# Use LangChain for LLM interactions
analysis_chain = (
ChatPromptTemplate.from_messages([
("system", "Analyze the user's request."),
MessagesPlaceholder("messages"),
])
| ChatOpenAI(model="gpt-4.1-mini", temperature=0)
)
# Nodes return only the keys they change; LangGraph applies the reducer
def analyze_node(state: AgentState) -> dict:
result = analysis_chain.invoke({"messages": state["messages"]})
return {"messages": [result], "current_step": "analyzed"}
# Wrap in LangGraph nodes for orchestration
workflow = StateGraph(AgentState)
workflow.add_node("analyze", analyze_node)
workflow.add_edge(START, "analyze")
workflow.add_edge("analyze", END)
# InMemorySaver keeps checkpoints in RAM; use PostgresSaver in production
app = workflow.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "user-42"}}
app.invoke({"messages": [("user", "Compare these two designs")]}, config)
Two details make this graph behave. The add_messages reducer appends the node’s new message to the existing list, so the node never mutates state in place. The checkpointer saves state per thread_id, which is what durable execution and multi-turn memory build on. InMemorySaver loses everything when the process restarts; production uses a persistent saver such as PostgresSaver from langgraph-checkpoint-postgres.
When to upgrade: Control flow beyond one agent loop (branches, several cooperating agents), state that is more than a message list, long-running workflows that must resume after a restart.
LangChain’s own write-up Is LangGraph Used In Production? (opens in new tab) names Uber (code migration agents), LinkedIn (a recruiting agent), Replit (a coding agent with human-in-the-loop) and Elastic (threat detection) as LangGraph users.
Cost Optimization Strategies#
Token Management#
Track and control token usage aggressively:
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware
from langchain_core.callbacks import get_usage_metadata_callback
from langchain_openai import ChatOpenAI
# 1. Track everything: usage_metadata works across providers and agent types
with get_usage_metadata_callback() as cb:
result = chain.invoke({"input": query})
print(cb.usage_metadata) # token counts per model name
# 2. Trim context to a token budget: trim_messages, shown in anti-pattern 4
# 3. Smart summarization for older context
agent = create_agent(
model="openai:gpt-4.1-mini",
tools=tools,
middleware=[
SummarizationMiddleware(
model="openai:gpt-4.1-mini",
trigger=("tokens", 4000),
keep=("messages", 20),
),
],
)
# 4. Explicit output limits
llm = ChatOpenAI(
model="gpt-4.1-mini",
max_tokens=512 # Concise responses
)
Where the Savings Come From#
The four levers compound, and they compound in a specific order. Routing changes the price per token, so apply it first; it has the largest effect and the largest quality risk. Memory trimming and output limits change the token count per request, which multiplies against whatever price the router picked. Caching removes requests entirely, so it sits on top of all three.
Model your own numbers before promising anything: take the published per-token prices for the models you route between, multiply by your measured tokens per request, and only then apply your observed cache hit rate.
Monitoring and Observability#
Essential Production Metrics#
import time
from typing import Any
from uuid import UUID
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.messages import AIMessage
from langchain_core.outputs import LLMResult
class ProductionMetrics(BaseCallbackHandler):
"""Comprehensive production monitoring, safe for concurrent runs"""
def __init__(self) -> None:
# Start times keyed by run_id, so parallel calls never share a clock
self._started: dict[UUID, float] = {}
def on_chain_start(self, serialized, inputs, *, run_id: UUID, **kwargs: Any) -> None:
self._started[run_id] = time.perf_counter()
def on_chain_end(self, outputs, *, run_id: UUID, **kwargs: Any) -> None:
self._observe("chain.duration", run_id)
def on_chain_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
self._started.pop(run_id, None)
def on_chat_model_start(self, serialized, messages, *, run_id: UUID, **kwargs: Any) -> None:
self._started[run_id] = time.perf_counter()
metrics.increment("llm.requests")
def on_llm_end(self, response: LLMResult, *, run_id: UUID, **kwargs: Any) -> None:
# Performance metrics
self._observe("llm.latency", run_id)
# Token metrics from usage_metadata, the provider-neutral field
for generation in response.generations[0]:
message = getattr(generation, "message", None)
if isinstance(message, AIMessage) and message.usage_metadata:
metrics.gauge("llm.input_tokens", message.usage_metadata["input_tokens"])
metrics.gauge("llm.output_tokens", message.usage_metadata["output_tokens"])
def on_llm_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
self._started.pop(run_id, None)
metrics.increment("llm.errors")
logger.error("LLM error: %s", error)
def on_tool_start(self, serialized, input_str, **kwargs: Any) -> None:
tool_name = (serialized or {}).get("name", "unknown")
metrics.increment(f"tool.{tool_name}.calls")
def _observe(self, name: str, run_id: UUID) -> None:
started = self._started.pop(run_id, None)
if started is not None:
metrics.gauge(name, time.perf_counter() - started)
LangSmith Integration#
With LANGSMITH_TRACING and LANGSMITH_API_KEY set in the environment, LangSmith traces chain and agent runs without code changes. Tags and metadata make those traces filterable:
# Tags and metadata set on a runnable are inherited by all of its children,
# so every trace from this chain carries the release and service names
tagged_chain = chain.with_config(
{"tags": ["prod", "version-2.1"], "metadata": {"service": "review-analyzer"}}
)
result = tagged_chain.invoke({"input": query})
What LangSmith tracks:
- Execution traces with timing for each step
- Token usage and costs per request
- Agent decision paths and tool selections
- Error rates and failure patterns
- A/B test comparisons with metadata tags
Migration Patterns#
From LangChain to Custom Code#
Incremental approach minimizes risk:
# Week 1: Profile to find the component with the worst cost/latency ratio
# Week 2: Create custom replacement
# (plain-text history only: there are no tool messages to keep paired)
class EfficientMemory:
def __init__(self, max_messages=10):
self.messages = []
self.max_messages = max_messages
def add(self, message):
self.messages.append(message)
if len(self.messages) > self.max_messages:
self.messages = self.messages[-self.max_messages:]
def get_context(self):
return "\n".join(self.messages)
# Week 3: A/B test implementations
# Group A: LangChain memory (baseline)
# Group B: Custom memory (test)
# Week 4: Compare on p95 latency, tokens per request, answer quality
# Week 5+: Gradual rollout
# 10% → 50% → 100% over 2 weeks
From Legacy Agents to create_agent#
The langchain-cli migrate command rewrote import paths for the 0.2 and 0.3 package split; it never converted chains or agents. For 1.0, the v1 migration guide (opens in new tab) is the map, and most agent code moves in a few lines.
Manual migration example:
# Legacy: initialize_agent, now in langchain-classic and deprecated
from langchain_classic.agents import AgentType, initialize_agent
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION
)
# LangChain 1.x: create_agent replaces langgraph.prebuilt.create_react_agent too
from langchain.agents import create_agent
agent = create_agent(
model=llm,
tools=tools,
)
result = agent.invoke({"messages": [{"role": "user", "content": query}]})
Middleware for limits and summarization, built-in streaming, clearer debugging, and full control over agent behavior round out the case for making the switch.
Failure Modes in Practice#
The Prototype-to-Production Trap#
A prototype running on defaults looks fine in development, then production reveals high costs, slow responses, and silent failures. Design for production from day one: set resource limits, add caching, and wire in observability before the first deployment.
Framework Lock-In#
Starting with LangChain for rapid prototyping is the easy call. Six months into a deeply coupled architecture, migrating away becomes months of work, unless framework usage stayed at the boundaries with core business logic kept framework-agnostic.
Observability Left for Later#
Launching without tracing or monitoring means production issues surface as user complaints, with no way to debug what actually happened, until LangSmith or an equivalent gets wired in from the start.
Agent Autonomy Without Guardrails#
Trusting an agent to “figure it out” without controls lets the tool-calling loop run until the budget or the user’s patience gives out. Max iterations, timeouts, and cost budgets belong in required configuration, not optional tuning.
Where This Default Holds#
This covers most LangChain deployments: RAG services, internal assistants, and agent workflows with a handful of tools. The price of the discipline is a few dozen lines of configuration and one observability dependency, paid once.
Override it in two directions. Below the line, a single-prompt service with stable requirements does not need the framework at all; the provider SDK plus a cache is less code to write and less code to debug. Above the line, multi-agent systems with long-running state outgrow a single create_agent loop well before they outgrow LangChain itself, and that is the moment to move orchestration into a LangGraph graph while keeping LCEL chains for the LLM calls.
References#
- LangChain v1 Migration Guide (opens in new tab) - What moved to
langchain-classic, the switch tocreate_agent, middleware hooks, and the Python 3.10 requirement - LangChain and LangGraph 1.0 (opens in new tab) - Release announcement (October 2025) introducing
create_agent, middleware, and thelangchain-classicpackage - LangChain Changelog (opens in new tab) - Release notes, including the 1.1 summarization triggers and model-retry middleware
- Built-in Middleware (opens in new tab) - Parameters for
ModelCallLimitMiddleware,ToolCallLimitMiddleware,SummarizationMiddleware, and fallback and retry middleware - Custom Middleware (opens in new tab) -
before_modelhooks,can_jump_to, and early exits from the agent loop - Short-Term Memory (opens in new tab) - Checkpointers,
thread_id,PostgresSaver, and trimming or summarizing agent history - trim_messages API Reference (opens in new tab) - Token-based trimming parameters and the
start_on="human"rule for a valid chat history - LangChain Models (opens in new tab) - Model initialization, timeouts, retries, token usage callbacks, and
with_structured_output - Redis LLM Caching (opens in new tab) - The
langchain-redisRedisCache, including itsttlparameter - langchain-core chat model source (opens in new tab) - How a chat model builds the cache key from the serialized messages and its parameters
- langchain-core language model base (opens in new tab) - The per-model
cachefield (True,False, or a cache instance) and the note that streaming calls skip the cache - LangGraph Graph API (opens in new tab) - State schemas, the
add_messagesreducer, and nodes that return partial updates - LangGraph Persistence (opens in new tab) - Checkpointers, thread IDs, and why in-memory savers lose state on restart
- Trace with LangChain (opens in new tab) -
LANGSMITH_*environment variables and tagging runs with tags and metadata - LangSmith Observability (opens in new tab) - Official guide to tracing, monitoring, and evaluating LangChain applications in production
- OpenAI API Pricing (opens in new tab) - Current per-token list prices for the models in the routing table
- Is LangGraph Used In Production? (opens in new tab) - LangChain’s write-up of LangGraph use at Uber, LinkedIn, Replit, and Elastic
- Practical Text-to-SQL for Data Analytics (opens in new tab) - LinkedIn Engineering on SQL Bot, a multi-agent system built on LangChain and LangGraph
- pypdf: Extract Text from a PDF (opens in new tab) - Why pypdf reads only the text layer and how tables appear as positioned text
- Sunsetting langchain-community (opens in new tab) - The May 2026 announcement that
langchain-communityis sunset in favor of standalone integration packages - Unstructured Document Loader (opens in new tab) - Installing
langchain-unstructuredand loading files withUnstructuredLoader - Unstructured Partitioning Strategies (opens in new tab) - The
fast,hi_res, andocr_onlystrategies and their speed trade-offs - LangChain Text Splitters (opens in new tab) - Recursive, structure-based, and token-based splitting options
Related posts
A technical guide to production-grade prompt engineering: systematic design, security, observability, and cost optimization for enterprise LLM apps.
prompt-engineering · llm · ai-tools +6
When a coding agent underperforms, the reflex is a stronger model. On bounded tasks the harness moves the score about as much; a rule for which lever to pull.
ai-agents · ai-tools · llm +3
An implementation-focused glossary for developers navigating the AI/LLM landscape - from tokens to agents, RAG to fine-tuning, with code examples.
llm · ai-agents · rag +6
Prompt caching, model routing, token budgets, and semantic caching: how to keep production LLM spend predictable without giving up answer quality.
aws · cost-optimization · llm +3
Systematic profiling for PostgreSQL and MongoDB: how to find the queries driving latency and infrastructure cost, and which fixes actually move them.
data-storage-orm · postgresql · performance +4