Skip to main content
← Back to Blog
2026-02-22 · 11 min readAI AgentsPythonUpdated Oct 30, 2026

Best Practices for Deploying LangChain Apps to Production

A practical checklist for running LangChain and LangGraph agents in production in 2026: where to host them now that LangServe is deprecated, how to keep conversation state per user with checkpointers, when an LLM cache helps, LangSmith tracing and evaluation, secrets, and the timeouts that break long agent runs.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
49 views
Best Practices for Deploying LangChain Apps to Production

This guide is for developers who have a LangChain or LangGraph agent working in a notebook and now need to put it in front of real users. Deploying a LangChain app to production means running the agent as a service that many users can call at once, with its state, limits, traces and secrets handled outside the notebook. It is a checklist for serving, streaming, state, caching, timeouts, tracing, evaluation and secrets. It is written against LangChain 1.x and the LangChain, LangSmith and AWS documentation as of October 30, 2026. There are no benchmarks here; where something depends on your workload, the advice is to measure it yourself.

Key takeaways

  • LangServe is deprecated. Serve agents with LangSmith Deployment or behind your own API, and use a queue for long runs.
  • Keep conversation state in a database-backed checkpointer, with a thread_id built on the server from the signed-in user.
  • Set timeouts at every layer, cache only stateless steps, and turn on tracing and an evaluation set before the first release.

An agent that works in a notebook has only proved that the prompt and tools can work once, for one person, on a fast connection. Production adds everything a notebook hides: many users at the same time, several server processes, slow or failing model providers, costs that grow with traffic, and bugs you have to diagnose from logs after the fact.

This is the last part of the LLM & LangChain Fundamentals series. The previous part, architecting autonomous agents for complex workflows, covers how to design the agent; this one covers how to run it.

1. Pick how you will serve the agent

The old answer was LangServe: wrap a chain with add_routes on a FastAPI app. The LangServe README now says it has been deprecated since November 18, 2024 and recommends LangGraph Platform for new projects. In the current docs that hosted offering is part of LangSmith Deployment. LangSmith Cloud is its fully managed option: the LangGraph deployment page describes it as managed infrastructure for stateful, long-running agents.

That leaves three realistic options:

Option What it gives you Trade-off Use it when
LangSmith Deployment Managed hosting with persistence and background runs; hybrid, standalone and self-hosted variants Another platform to pay for and learn The agent is the product and you don't already run a Python backend
Your own API (FastAPI or similar) Full control; shares your app's auth, logging and deploy pipeline You build streaming, state and scaling yourself The agent is one feature inside an existing application
A queue and workers Runs that take minutes without an open HTTP request The client polls or waits for a webhook Long agent runs that would hit gateway timeouts

For LangSmith Deployment, a langgraph.json file describes the project: your dependencies, the graphs to expose and the environment file. The application structure page shows this shape:

{
  "dependencies": ["langchain_openai", "./your_package"],
  "graphs": {
    "my_agent": "./your_package/your_file.py:agent"
  },
  "env": "./.env"
}

Checked against langchain@1.4.7, langchain-openai@1.7.3, langgraph@1.2.18, langgraph-checkpoint-postgres@3.2.0 and langchain-redis@0.2.6, 2026-10-30.

The agent it points to can be the object returned by create_agent. Do not commit the .env file itself; see the secrets section below. On Python 3.13, the Postgres example below ran end to end against local services. The Redis cache example ran only up to the first cache lookup. The langgraph.json file was not deployed.

2. Stream the response

Agent runs are slow compared with normal API calls: a model call, a tool call, another model call. Users wait more patiently when they see progress. LangChain agents support stream and astream. With stream_mode="messages" you receive tokens as the model produces them, along with metadata about which step produced them. The client can then show text as it arrives and a status line while a tool runs.

On your own API, send these chunks as Server-Sent Events or over a WebSocket. Two practical points: make sure every proxy in the path (load balancer, CDN, API gateway) passes streaming responses through instead of buffering them, and decide what the client should see when a run fails halfway through a stream.

3. Keep conversation state outside the process

The most dangerous notebook habit is keeping memory in a module-level variable. In a web server every request in the process can share that variable, so one user's conversation can bleed into another's. It also disappears on every restart or scale-down.

In LangChain 1.x, short-term memory is LangGraph state saved by a checkpointer and keyed by a thread_id you pass in the config. InMemorySaver is fine for development. For production, the short-term memory guide uses Postgres:

pip install -U langgraph-checkpoint-postgres "psycopg[binary]"
import os

from langchain.agents import create_agent
from langgraph.checkpoint.postgres import PostgresSaver

MODEL = os.getenv("AGENT_MODEL", "openai:gpt-6-luna")

if __name__ == "__main__":
    db_uri = os.environ["CHECKPOINT_DB_URI"]
    with PostgresSaver.from_conn_string(db_uri) as checkpointer:
        checkpointer.setup()  # creates the checkpoint tables on first run
        agent = create_agent(MODEL, tools=[], checkpointer=checkpointer)
        config = {"configurable": {"thread_id": "user-123:conversation-7"}}
        result = agent.invoke({"messages": [{"role": "user", "content": "Hello"}]}, config)
        print(result["messages"][-1].text)

This block was run twice against a local PostgreSQL server and a local stand-in for the OpenAI API, with a placeholder OPENAI_API_KEY (the key must be set before create_agent builds the client). The second run sent the first turn back to the model, so the history came from the database. On October 30, 2026, OpenAI's models page called gpt-6-luna its most efficient model for focused, high-volume tasks. Check that page for current ids and set AGENT_MODEL rather than editing code.

For an async server, the persistence docs also list AsyncPostgresSaver. A few rules:

  • Build the thread_id on the server from the authenticated user and conversation, and never trust one sent by the client. The persistence docs also say to keep it under 255 characters with the Postgres savers.
  • Long threads grow. Add SummarizationMiddleware or trimming so old turns are condensed before they fill the context window.
  • If you deploy on LangSmith's Agent Server, the persistence docs say you do not need to configure checkpointers yourself; the server handles it.

Implementing memory in LangChain conversational AI goes deeper on what to keep, what to summarise and what to forget.

4. Add caching where requests really repeat

An LLM cache stores the response for a given prompt and model settings and returns it next time instead of calling the provider. The langchain-redis package provides RedisCache (exact match) and RedisSemanticCache (similar prompts, using embeddings):

pip install -U langchain-core langchain-redis redis
import os

from langchain_core.globals import set_llm_cache
from langchain_redis import RedisCache

set_llm_cache(RedisCache(redis_url=os.environ["REDIS_URL"], ttl=3600))

Check your Python and Redis versions

langchain-redis 0.2.6 requires Python 3.10 to 3.13 on PyPI, so it does not install on Python 3.14. The RedisCache reference says it stores entries with Redis JSON. In this check, a Redis 8.0 server built without modules rejected the first lookup with unknown command 'JSON.GET'. The integration page starts Redis with the redis:latest Docker image; test against the same kind of server you run in production. No cache hit was verified for this update.

Be realistic about what this catches. An exact-match cache only hits when the whole prompt is identical. In a multi-turn agent the prompt includes the conversation so far, so hits are rare. Caching pays off on stateless steps: classifying a ticket, summarising the same document, answering a fixed FAQ.

A semantic cache can return an answer to a question that is similar but not the same. Keep it away from anything personal or account-specific, and set a TTL so stale answers expire. Measure your hit rate before deciding the cache is worth the extra moving part.

5. Set timeouts, retries and rate limits deliberately

Every layer has its own timeout, and the shortest one wins.

  • The model call. init_chat_model accepts timeout (seconds) and max_retries (default 6). Retries on a long agent run multiply the worst-case time, so set both on purpose. LangChain also has an optional InMemoryRateLimiter you can pass to the model to stay under a provider's request limits.
  • The agent loop. Cap the number of model and tool steps so a confused agent cannot loop indefinitely, and put a timeout on every tool that calls an external system.
  • The platform. On AWS, the API Gateway REST API integration timeout can be set from 50 milliseconds to 29 seconds. The quota table says you can raise it above 29 seconds for Regional and private APIs (not edge-optimized ones), and that this might require a reduction in your account's Region-level throttle quota.

Lambda can stream responses through function URLs, the InvokeWithResponseStream API or an API Gateway proxy integration. The Lambda docs say streaming is supported on Node.js managed runtimes, while Python needs a custom runtime or the Lambda Web Adapter.

As a rule of thumb, agents that can run longer than a typical HTTP request are simpler on a container service with streaming, or on the queue-and-worker pattern, than behind gateway limits.

6. Trace everything from the first deploy

Normal application logs tell you that a request failed. They rarely tell you what the rendered prompt was, which tool the model chose, what arguments it passed or what came back. Tracing does. For LangSmith, the setup is environment variables:

export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="<your-langsmith-api-key>"
export LANGSMITH_PROJECT="support-agent-prod"

The tracing docs describe LANGSMITH_PROJECT for project-based workspaces and self-hosted LangSmith. Agent-based workspaces set LANGSMITH_AGENT_ID and LANGSMITH_AGENT_ENVIRONMENT instead.

Two more settings from the same page are easy to miss. If your LangSmith account is in a region other than the US, also set LANGSMITH_ENDPOINT to your region's API URL, or the key will not authenticate. In serverless environments, set LANGCHAIN_CALLBACKS_BACKGROUND=false so traces finish sending before the function ends.

If you cannot send prompts to a third-party service, keep the same habit with your own tooling. Log the inputs and outputs of every model and tool call with a run ID you can search on.

7. Evaluate before every change

Changing a prompt, a model or a tool description can quietly break behaviour that used to work. LangSmith splits evaluation into offline evaluation (run a curated dataset before you ship) and online evaluation (run evaluators on real production traffic). Evaluators can be code rules, an LLM acting as a judge, pairwise comparisons or human review.

A workable starting point:

  1. Collect real inputs that cover your main use cases and the failures you have already fixed. Give each one a reference answer or a rule for what "correct" means.
  2. Write checks in code wherever you can (the right tool was called, the JSON parses, a required field is present). Use an LLM judge only for things code cannot check.
  3. Run the set on every prompt, model or tool change, and compare the results with the previous version before deploying.
  4. Add production traces that went wrong to the dataset, so the same mistake cannot ship twice.

8. Handle secrets and data properly

  • Keep provider keys, database URLs and the LangSmith key in your platform's secret store or a secrets manager, injected as environment variables at runtime. Never commit them, and never put them in prompts or tool outputs.
  • Give tools the narrowest credentials that work. A tool that reads orders should not hold a key that can also issue refunds.
  • Decide what may leave your system. Traces contain full prompts and outputs, so check what personal data they include and what your tracing provider's retention settings are.
  • Validate tool arguments in code. The model choosing a tool is not authorisation to run it with any input.

A minimal production checklist

  • Agent served through LangSmith Deployment or your own API, not LangServe.
  • Streaming works end to end, through every proxy.
  • Checkpointer backed by a real database; thread_id built on the server.
  • Timeouts and retry limits on the model, the tools and the agent loop.
  • Cache only on stateless, repeatable steps, with a TTL.
  • Tracing on from day one, with the right region and serverless settings.
  • An evaluation set that runs before every change.
  • Secrets in a secret store; least-privilege credentials for tools.

If you are still deciding whether you need LangChain at all, go back to part 1: What is LangChain? When to use it and when to write your own code.

Frequently asked questions

Is LangServe still a good way to deploy LangChain apps?

Not for new projects. Its README says it has been deprecated since November 18, 2024 and recommends LangGraph Platform, now documented as LangSmith Deployment. For an existing LangServe app, plan a move to LangSmith Deployment or to your own FastAPI service.

Can I deploy a LangChain agent on AWS Lambda?

Yes, with care. API Gateway REST APIs default to a 29-second integration timeout, which can be raised for Regional and private APIs. Lambda response streaming is supported on Node.js managed runtimes; Python needs a custom runtime or the Lambda Web Adapter. For long agent runs, a container service or a queue with workers is usually simpler.

How do I store conversation history in production?

Use a LangGraph checkpointer backed by a database, such as PostgresSaver from langgraph-checkpoint-postgres, and pass a thread_id per conversation in the config. On LangSmith's Agent Server, persistence is handled for you.

Does an LLM cache work for chat agents?

Mostly not for the conversational turns, because the prompt includes the conversation history and rarely repeats exactly. It works well for stateless steps such as classification or summarising the same document. langchain-redis provides both exact-match and semantic caches.

Do I need LangSmith to run LangChain in production?

No. LangChain runs without it. You do need some form of tracing and evaluation, and LangSmith is the most direct option for LangChain apps. If data rules prevent it, log model and tool calls yourself and run your evaluation set in CI.

Sources

Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.

  1. LangServe README (deprecation notice)
  2. LangGraph: Deployment
  3. LangSmith: Application structure (langgraph.json)
  4. LangGraph: Persistence
  5. LangChain: Short-term memory
  6. LangChain: Models (timeouts, retries, rate limiting)
  7. LangChain: Streaming
  8. Redis cache integration for LangChain
  9. LangChain reference: RedisCache
  10. langchain-redis on PyPI
  11. langgraph-checkpoint-postgres on PyPI
  12. LangSmith: Trace with LangChain
  13. LangSmith: Evaluation
  14. OpenAI API: Models
  15. Amazon API Gateway: REST API quotas
  16. AWS Lambda: Response streaming
All 14 parts in this series
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.