Serving graphs with FastAPI, Streamlit or React

Topic 3 of 5 in Deployment & LLMOps20 min readAdvancedFree course

Overview

A LangGraph application running inside a Python script is not yet an application that customers or employees can use. External clients need a stable interface through which they can submit messages, receive responses, continue conversations, and observe long-running operations.

In the previous lesson, you learned how the LangGraph CLI and LangSmith Agent Server provide standardized infrastructure for serving graphs. An alternative is to self-host a compiled graph behind a custom FastAPI application.

FastAPI is particularly useful when integrating agents into existing products that already have authentication, business APIs, databases, and application-specific requirements.

The architecture in this lesson separates graph execution, HTTP communication, persistence, and presentation.

The architecture in this lesson separates graph execution, HTTP communication, persistence, and presentation.

The frontend sends a message and conversation identifier. FastAPI authenticates the request, invokes the graph, and translates its output into a client-friendly response. PostgreSQL preserves graph state, while Redis optionally supports operational concerns.

Choosing a serving approach

Capability Agent Server Custom FastAPI
Standard graph API Built in Implement yourself
Thread and run management Provided Implement yourself
Streaming infrastructure Provided Customize yourself
Authentication integration Supported Application-defined
Custom business endpoints Supported through customization Full control
Operational responsibility Deployment-dependent Primarily your responsibility
Best fit Graph-centric platforms Existing application backends

A custom FastAPI endpoint is not automatically equivalent to Agent Server. Features such as background execution, durable run queues, reconnection, cancellation, and run management require additional engineering.

We will build a support assistant with persistent conversations, a synchronous-response HTTP endpoint, a streaming endpoint, optional Redis rate limiting, and two interchangeable user interfaces.

The FastAPI app

Preparing the environment

Use Python 3.11 or newer and install the application dependencies.

Terminal
pip install "langgraph>=1,<2" "langchain>=1,<2" \
    "langchain-openai>=1,<2" \
    langgraph-checkpoint-postgres "psycopg[binary,pool]" \
    fastapi "uvicorn[standard]" redis requests streamlit

Ensure PostgreSQL is running and create a database named agentdb.

Configure the following environment variables using your own credentials.

Terminal
export OPENAI_API_KEY="your-openai-api-key"
export DATABASE_URL="postgresql://agent:password@localhost:5432/agentdb"
export API_TOKEN="replace-with-a-long-random-secret"
export MODEL_NAME="openai:gpt-5.4-mini"

A minimal project structure is:

Text
agent_service/
├── agent_graph.py
├── app.py
├── test_client.py
├── streamlit_app.py
├── history_app.py
└── frontend/

Keep graph logic independent of FastAPI. This separation allows the same graph to run in tests, command-line applications, or an Agent Server deployment.

Note: These examples use LangGraph 1.x APIs, Python 3.11+, and a single-worker teaching deployment. The APIs are documentation-verified, but the examples have not been executed against a live PostgreSQL instance or model provider here.

Creating the graph

The following complete module defines an asynchronous support assistant with conversation memory.

Save it as agent_graph.py.

Python
import os

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

def build_graph(checkpointer):
    model = init_chat_model(
        os.getenv("MODEL_NAME", "openai:gpt-5.4-mini"),
        timeout=45,
        max_retries=1,
    )

    async def respond(state: MessagesState):
        system_message = SystemMessage(
            content=(
                "You are a professional customer support assistant. "
                "Provide clear, accurate guidance. "
                "Do not invent company policies or account details."
            )
        )

        response = await model.ainvoke(
            [system_message, *state["messages"]]
        )

        return {"messages": [response]}

    builder = StateGraph(MessagesState)

    builder.add_node("respond", respond)
    builder.add_edge(START, "respond")
    builder.add_edge("respond", END)

    return builder.compile(checkpointer=checkpointer)

The graph receives a new human message, combines it with existing conversation state, and returns an assistant message.

MessagesState uses the message reducer to merge incoming messages with existing history. Consequently, clients need to send only the latest message rather than retransmitting the entire conversation.

The supplied checkpointer determines where that history survives between invocations. Keeping it outside the graph factory makes persistence configurable without modifying business logic.

Implementing application lifecycle and endpoints

Opening a database connection and compiling a graph for every HTTP request introduces unnecessary latency and resource consumption.

Instead, initialize shared resources using FastAPI’s lifespan context manager. Resources created before yield remain available while the server runs and are cleaned up during shutdown.

Save the following complete application as app.py.

Python
import asyncio
import hmac
import json
import logging
import os

from contextlib import asynccontextmanager, aclosing
from uuid import UUID

from fastapi import FastAPI, Depends, Header, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field, field_validator

from langchain.messages import HumanMessage
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver

from redis.asyncio import Redis
from redis.exceptions import RedisError

from agent_graph import build_graph

logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.api_token = os.environ["API_TOKEN"]

    if not app.state.api_token:
        raise RuntimeError("API_TOKEN must not be empty")

    redis_url = os.getenv("REDIS_URL")

    redis = Redis.from_url(redis_url) if redis_url else None
    app.state.redis = redis

    try:
        if redis is not None:
            await redis.ping()

        async with AsyncPostgresSaver.from_conn_string(
            os.environ["DATABASE_URL"]
        ) as checkpointer:
            await checkpointer.setup()

            app.state.graph = build_graph(checkpointer)

            # Bounded, process-local lock collection.
            app.state.locks = [
                asyncio.Lock() for _ in range(64)
            ]

            yield
    finally:
        if redis is not None:
            await redis.aclose()

app = FastAPI(
    title="Persistent LangGraph API",
    version="1.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_methods=["GET", "POST"],
    allow_headers=["Authorization", "Content-Type"],
)

class ChatRequest(BaseModel):
    thread_id: UUID
    message: str = Field(min_length=1, max_length=8000)

    @field_validator("message")
    @classmethod
    def validate_message(cls, value):
        value = value.strip()

        if not value:
            raise ValueError("Message must not be blank")

        return value

class ChatResponse(BaseModel):
    thread_id: UUID
    reply: str

async def require_user(
    request: Request,
    authorization: str | None = Header(default=None),
):
    expected = f"Bearer {request.app.state.api_token}"

    if not hmac.compare_digest(
        (authorization or "").encode(),
        expected.encode(),
    ):
        raise HTTPException(
            status_code=401,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # Single authenticated identity for this demonstration.
    return "demo-user"

def thread_config(user: str, thread_id: UUID):
    return {
        "configurable": {
            "thread_id": f"{user}:{thread_id}"
        },
        "recursion_limit": 20,
    }

def lock_for(request: Request, config: dict):
    thread_id = config["configurable"]["thread_id"]
    index = hash(thread_id) % len(request.app.state.locks)

    return request.app.state.locks[index]

RATE_LIMIT_SCRIPT = """
local count = redis.call('INCR', KEYS[1])
if count == 1 then
    redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return count
"""

async def admit(
    request: Request,
    user: str = Depends(require_user),
):
    redis = request.app.state.redis

    if redis is not None:
        try:
            count = await redis.eval(
                RATE_LIMIT_SCRIPT,
                1,
                f"rate-limit:{user}",
                60,
            )
        except RedisError:
            raise HTTPException(
                status_code=503,
                detail="Rate limiter unavailable",
            )

        if count > 20:
            raise HTTPException(
                status_code=429,
                detail="Request limit exceeded",
                headers={"Retry-After": "60"},
            )

    return user

@app.get("/health")
async def health():
    return {"status": "ok"}

@app.post("/chat", response_model=ChatResponse)
async def chat(
    body: ChatRequest,
    request: Request,
    user: str = Depends(admit),
):
    graph = request.app.state.graph
    config = thread_config(user, body.thread_id)

    try:
        async with asyncio.timeout(90):
            async with lock_for(request, config):
                result = await graph.ainvoke(
                    {
                        "messages": [
                            HumanMessage(content=body.message)
                        ]
                    },
                    config=config,
                    durability="sync",
                )
    except TimeoutError:
        raise HTTPException(
            status_code=504,
            detail="Graph execution timed out",
        )

    return ChatResponse(
        thread_id=body.thread_id,
        reply=str(result["messages"][-1].text),
    )

def encode_event(event_type: str, **data):
    return json.dumps({
        "type": event_type,
        **data,
    }) + "\n"

@app.post("/chat/stream")
async def stream_chat(
    body: ChatRequest,
    request: Request,
    user: str = Depends(admit),
):
    graph = request.app.state.graph
    config = thread_config(user, body.thread_id)

    async def generate():
        try:
            async with asyncio.timeout(90):
                async with lock_for(request, config):
                    stream = graph.astream(
                        {
                            "messages": [
                                HumanMessage(content=body.message)
                            ]
                        },
                        config=config,
                        stream_mode=["messages"],
                        version="v2",
                        durability="sync",
                    )

                    async with aclosing(stream) as events:
                        async for chunk in events:
                            if chunk["type"] != "messages":
                                continue

                            message, metadata = chunk["data"]

                            if metadata.get("langgraph_node") != "respond":
                                continue

                            if message.text:
                                yield encode_event(
                                    "token",
                                    text=str(message.text),
                                )

                    snapshot = await graph.aget_state(config)

                    reply = str(
                        snapshot.values["messages"][-1].text
                    )

            yield encode_event(
                "done",
                thread_id=str(body.thread_id),
                reply=reply,
            )

        except TimeoutError:
            yield encode_event(
                "error",
                message="Graph execution timed out",
            )
        except Exception:
            logger.exception("Streaming execution failed")

            yield encode_event(
                "error",
                message="Unable to complete the response",
            )

    return StreamingResponse(
        generate(),
        media_type="application/x-ndjson",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )

Start the application from the project directory.

Terminal
uvicorn app:app --host 127.0.0.1 --port 8000 --workers 1

Open http://localhost:8000/docs to access the automatically generated interactive API documentation.

Understanding request execution

The non-streaming endpoint waits asynchronously until graph execution completes. The streaming endpoint delivers partial output while execution remains active.

The following sequence illustrates a successful streaming request.

The FastAPI app diagram: START to Receive HTTP Request; Receive HTTP Request to Authorized?; Authorized? to Reject Request (No); Authorized? to Acquire Thread Lock (Yes); Acquire Thread Lock to Load Saved State; Load Saved State to Execute Graph; Execute Graph to Stream Tokens; Stream Tokens to Persist Final State; Persist Final State to Send Done Event; Send Done Event to END.

The thread_id identifies persisted graph state, not an HTTP connection. Different requests can continue the same conversation even after the original connection closes.

Authentication is checked before graph execution. The authenticated identity forms part of the internal checkpoint identifier.

Our demonstration deliberately supports one authenticated identity. For a multi-user product, replace require_user() with validated identity-provider tokens and enforce ownership through a server-side conversation registry.

A UUID alone is not an authorization mechanism.

Streaming protocol design

The streaming endpoint uses newline-delimited JSON, commonly called NDJSON. Each complete line represents one application event.

A typical response looks like this:

JSON
{"type":"token","text":"You can"}
{"type":"token","text":" reset your password"}
{"type":"token","text":" from account settings."}
{"type":"done","thread_id":"550e8400-e29b-41d4-a716-446655440000","reply":"You can reset your password from account settings."}

A terminal done event confirms successful completion and contains the authoritative final answer. Individual tokens are provisional display data.

LangGraph’s v2 streaming format supplies typed chunks containing type and data. The messages mode provides message chunks and execution metadata. Other useful modes include updates for state changes and custom for application-defined progress events.

Never forward every internal event directly to customers. Filter reasoning-related content, internal tool arguments, confidential state, and debugging information.

Once streaming response headers have been transmitted, an execution failure cannot normally become a new HTTP error response. The application therefore emits a structured error event.

Testing conversation continuity

Save this Python client as test_client.py.

Python
import os
import uuid
import requests

BASE_URL = "http://127.0.0.1:8000"

headers = {
    "Authorization": f"Bearer {os.environ['API_TOKEN']}"
}

thread_id = os.getenv("THREAD_ID") or str(uuid.uuid4())

print("Thread:", thread_id)

def send(message):
    response = requests.post(
        f"{BASE_URL}/chat",
        headers=headers,
        json={
            "thread_id": thread_id,
            "message": message,
        },
        timeout=110,
    )

    response.raise_for_status()

    print("User:", message)
    print("Assistant:", response.json()["reply"])

send("My support ticket number is TKT-4821.")
send("What is my support ticket number?")

Run it using:

Terminal
python test_client.py

Expected output, with model-dependent wording:

Text
Thread: 550e8400-e29b-41d4-a716-446655440000
User: My support ticket number is TKT-4821.
Assistant: I have noted your support ticket number, TKT-4821.
User: What is my support ticket number?
Assistant: Your support ticket number is TKT-4821.

Restart the server and reuse the printed thread identifier. To verify persistence independently, send only the second message using the send() function and the original identifier.

A new thread should not have access to the previous conversation.

PostgreSQL and Redis

PostgreSQL as durable graph persistence

LangGraph checkpoints capture graph state at execution boundaries. Depending on the graph, this includes messages, intermediate results, scheduling information, and pending operations.

AsyncPostgresSaver implements this persistence interface using PostgreSQL.

Calling await checkpointer.setup() initializes the required checkpoint schema and applies migrations. In production, execute schema setup as a controlled deployment operation rather than allowing every replica to migrate simultaneously.

The example uses one PostgreSQL connection for simplicity. Higher-throughput services should use an appropriately configured asynchronous connection pool, bounded concurrency, and database connection budgets.

The durability="sync" setting prioritizes persistence guarantees by synchronizing checkpoint writes with graph execution. This introduces additional latency compared with less synchronous durability modes.

Checkpoints do not make external side effects transactional. If a tool charges a payment or sends an email, use business-level idempotency and transaction controls.

Redis as operational infrastructure

Redis is optional in this architecture.

Requirement PostgreSQL Redis
Durable graph checkpoints Primary responsibility Optional alternative
Conversation recovery Yes Depends on configuration
Shared rate limiting Possible Well suited
Temporary cache Possible Well suited
Expiring counters Additional logic Native TTL support
Distributed coordination Possible Common use case

The Redis script in app.py implements a 60-second window beginning with the first request. It permits up to 20 requests during that window.

Incrementing the counter and setting its expiration within one atomic script prevents a failure between separate Redis commands from leaving a permanent rate-limit key.

Enable this functionality by setting REDIS_URL and restarting the application.

For customer-facing systems, consider separate quotas by authenticated user, tenant, model, and workload type. Rate limiting counts requests, but it does not necessarily constrain token consumption or simultaneously active executions.

Concurrent requests and thread safety

Two requests targeting the same conversation can read overlapping checkpoint state and produce conflicting updates.

The example uses a bounded collection of asynchronous locks to serialize requests targeting the same thread. Unrelated threads can execute concurrently, although occasional lock collisions also serialize unrelated conversations.

These locks work only within one server process.

With multiple workers or replicas, use a shared execution coordinator, durable per-thread queue, or carefully designed distributed locking. Redis locks require ownership tokens, safe release, expiration management, and protection against expired lock holders continuing execution.

PostgreSQL checkpoint persistence alone does not establish an application-level execution queue.

Tip: Begin with one worker, verify persistence and concurrency behavior, and introduce distributed execution only after defining how simultaneous runs, retries, and abandoned requests should behave.

Streamlit for internal tools

Streamlit lets Python developers create interactive applications without building a separate JavaScript frontend.

It is particularly useful for internal support assistants, research tools, agent evaluation dashboards, document-processing applications, and human-review interfaces.

Streamlit executes Python on its application server. Browser interactions normally trigger script reruns, so session-specific values must be preserved explicitly.

Building the chat interface

Save the following complete application as streamlit_app.py. It communicates with the existing FastAPI service.

Python
import os
import uuid

import requests
import streamlit as st

API_URL = os.getenv(
    "API_URL",
    "http://127.0.0.1:8000",
)

headers = {
    "Authorization": f"Bearer {os.environ['API_TOKEN']}"
}

st.set_page_config(page_title="Support Assistant")
st.title("Internal Support Assistant")

if "thread_id" not in st.session_state:
    st.session_state.thread_id = str(uuid.uuid4())

if "messages" not in st.session_state:
    st.session_state.messages = []

if st.sidebar.button("New conversation"):
    st.session_state.thread_id = str(uuid.uuid4())
    st.session_state.messages = []
    st.rerun()

st.sidebar.caption(
    f"Thread: {st.session_state.thread_id}"
)

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

prompt = st.chat_input(
    "Ask a support question",
    max_chars=8000,
)

if prompt and prompt.strip():
    st.session_state.messages.append({
        "role": "user",
        "content": prompt,
    })

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

    with st.chat_message("assistant"):
        with st.spinner("Generating response..."):
            try:
                response = requests.post(
                    f"{API_URL}/chat",
                    headers=headers,
                    json={
                        "thread_id": st.session_state.thread_id,
                        "message": prompt,
                    },
                    timeout=110,
                )

                response.raise_for_status()
                reply = response.json()["reply"]

            except requests.RequestException:
                st.error(
                    "The request failed. Check conversation "
                    "state before retrying."
                )
            else:
                st.write(reply)

                st.session_state.messages.append({
                    "role": "assistant",
                    "content": reply,
                })

Start Streamlit in a separate terminal with the same API token configured.

Terminal
streamlit run streamlit_app.py

Open http://localhost:8501.

The interface displays the conversation, sends new messages to FastAPI, and supports starting a new conversation.

Two independent forms of state exist:

  • st.session_state preserves frontend information across script reruns.
  • PostgreSQL preserves the actual LangGraph conversation state across backend restarts.

A new browser session may lose Streamlit’s local transcript and thread identifier. Production applications should restore saved conversations through an authenticated history endpoint.

Streamlit can also consume the NDJSON endpoint using requests.post(..., stream=True), iter_lines(), and st.write_stream(). This allows progressive rendering without changing the graph.

Keep provider credentials on the backend. Even internal tools need individual authentication, appropriate permissions, and protection against unauthorized conversation access.

React for customer-facing apps

React is more appropriate when agents are embedded into polished products requiring customized layouts, responsive interfaces, accessibility, conversation navigation, and complex interaction states.

Unlike Streamlit, React code generally runs in the customer’s browser.

The browser must communicate with FastAPI rather than directly accessing the language model, PostgreSQL, or Redis.

Creating the frontend

Install a current Node.js LTS release and scaffold a React application using Vite.

Terminal
npm create vite@latest frontend -- --template react
cd frontend
npm install

Replace src/App.jsx with the following complete streaming chat component.

JSX
import { useState } from "react";

const API_URL = "http://127.0.0.1:8000";

export default function App() {
  const [threadId, setThreadId] = useState(
    () => crypto.randomUUID()
  );

  const [token, setToken] = useState("");
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  async function sendMessage(event) {
    event.preventDefault();

    const prompt = input.trim();

    if (!prompt || busy || !token) return;

    setBusy(true);
    setError("");
    setInput("");

    setMessages(previous => [
      ...previous,
      { role: "user", content: prompt },
      { role: "assistant", content: "" }
    ]);

    function updateReply(text) {
      setMessages(previous => [
        ...previous.slice(0, -1),
        { role: "assistant", content: text }
      ]);
    }

    let answer = "";
    let completed = false;
    let buffer = "";

    function processLine(line) {
      if (!line.trim()) return;

      const data = JSON.parse(line);

      if (data.type === "token") {
        answer += data.text;
        updateReply(answer);
      } else if (data.type === "done") {
        answer = data.reply;
        updateReply(answer);
        completed = true;
      } else if (data.type === "error") {
        throw new Error(data.message);
      }
    }

    try {
      const response = await fetch(`${API_URL}/chat/stream`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${token}`
        },
        body: JSON.stringify({
          thread_id: threadId,
          message: prompt
        })
      });

      if (!response.ok || !response.body) {
        throw new Error(`Request failed: ${response.status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      try {
        while (true) {
          const { value, done } = await reader.read();

          if (done) break;

          buffer += decoder.decode(value, { stream: true });

          const lines = buffer.split("\n");
          buffer = lines.pop() ?? "";

          for (const line of lines) {
            processLine(line);
          }
        }

        buffer += decoder.decode();

        if (buffer.trim()) {
          processLine(buffer);
        }

        if (!completed) {
          throw new Error("Response ended before completion");
        }
      } finally {
        await reader.cancel().catch(() => {});
        reader.releaseLock();
      }
    } catch (err) {
      setError(err.message);

      updateReply(
        answer
          ? `${answer}\n\n[Incomplete response]`
          : "[Response unavailable]"
      );
    } finally {
      setBusy(false);
    }
  }

  function newConversation() {
    setThreadId(crypto.randomUUID());
    setMessages([]);
    setError("");
  }

  return (
    <main style={{
      maxWidth: 720,
      margin: "40px auto",
      padding: 20
    }}>
      <h1>Customer Support Assistant</h1>

      <label>
        Demo access token
        <input
          type="password"
          value={token}
          disabled={busy}
          onChange={e => setToken(e.target.value)}
        />
      </label>

      <p>
        <button disabled={busy} onClick={newConversation}>
          New conversation
        </button>
      </p>

      <section aria-label="Conversation">
        {messages.map((message, index) => (
          <article key={index}>
            <strong>
              {message.role === "user" ? "You" : "Assistant"}
            </strong>

            <p style={{ whiteSpace: "pre-wrap" }}>
              {message.content}
            </p>
          </article>
        ))}
      </section>

      {busy && <p role="status">Generating response...</p>}
      {error && <p role="alert">{error}</p>}

      <form onSubmit={sendMessage}>
        <input
          value={input}
          onChange={e => setInput(e.target.value)}
          placeholder="Ask a question"
          aria-label="Your message"
          maxLength={8000}
          disabled={busy}
        />

        <button
          disabled={busy || !input.trim() || !token}
        >
          Send
        </button>
      </form>
    </main>
  );
}

Start the frontend.

Terminal
npm run dev -- --host localhost --port 5173 --strictPort

Open http://localhost:5173, enter the demonstration API token, and submit a message.

The answer should appear progressively rather than waiting until model generation finishes.

Understanding network streaming

HTTP chunks do not necessarily correspond to JSON records. One network chunk may contain half a record, several records, or part of a UTF-8 character.

The React implementation therefore uses a TextDecoder and a persistent buffer. It processes complete newline-delimited records and retains incomplete data until more bytes arrive.

The done event replaces accumulated text with the final persisted answer.

CORS middleware allows requests from the specified React development origin. CORS is a browser security mechanism, not an authentication or authorization system.

The demonstration token is manually entered and held in component memory. Never embed shared backend secrets in JavaScript bundles or public frontend environment variables. Production applications should use individual authenticated sessions or short-lived access tokens.

Production integration considerations

Designing a richer agent API

Real agents often need more than a chat endpoint.

Endpoint Responsibility
POST /chat Execute a conversation turn
POST /chat/stream Stream incremental output
GET /threads/{id}/messages Restore conversation history
POST /threads/{id}/resume Resume an interrupted graph
GET /runs/{id} Inspect background execution
POST /runs/{id}/cancel Request cancellation

The last four endpoints are extensions to the base application, not automatically provided routes.

For human-in-the-loop workflows, expose interruption payloads as explicit frontend events. Resume the original thread using Command(resume=value) with the authenticated thread configuration.

For long-running jobs, decouple execution from the HTTP connection through a durable run queue and persistent run identifiers. A disconnected browser should not be the sole determinant of business workflow execution.

When a graph requires authenticated user context, use StateGraph(State, context_schema=Context) and pass validated context through context=Context(...). Reserve the configurable thread identifier for checkpoint selection.

Common mistakes and best practices

  • Compiling graphs per request instead of initializing them during application startup.
  • Calling synchronous graph.invoke() inside asynchronous HTTP handlers.
  • Allowing clients to select arbitrary internal checkpoint identifiers.
  • Assuming a database automatically prevents concurrent executions of one thread.
  • Sending raw graph state or confidential tool results to browsers.
  • Automatically retrying failed requests without checking whether execution already produced side effects.
  • Confusing a successful liveness endpoint with database readiness or provider availability.
  • Allowing conversation history to grow indefinitely without retention and context-management policies.

Add request-size limits, explicit execution deadlines, dependency health checks, idempotency keys, TLS, and structured error reporting before exposing the service publicly.

Useful verification references include the official LangGraph streaming documentation, FastAPI lifespan documentation, Redis rate-limiting documentation, and Streamlit session-state documentation.

Connecting to the deployment project

This architecture provides the application foundation for the chapter’s hands-on project: deploying a complete LangGraph agent as an API with a user interface.

The graph is independently defined, persistent state resides outside the application process, and both frontends communicate through a shared HTTP contract.

The next lesson, Docker, cloud, Kubernetes and CI/CD, builds on this separation by packaging the service into reproducible containers, configuring deployment environments, managing secrets, introducing health probes, and scaling application instances safely.

When moving from a single-worker application to distributed infrastructure, preserving thread-level execution guarantees and database durability becomes a central deployment responsibility.

Exercise

Build a persistent conversation history API

Extend the FastAPI application from this lesson with an authenticated GET endpoint that retrieves conversation history from PostgreSQL-backed graph checkpoints. Return only user-facing human and assistant messages in chronological order, and return HTTP 404 for an unknown conversation. Verify that the history remains available after restarting the API server.

Python
# history_app.py
# Requires app.py and agent_graph.py from the lesson.

from uuid import UUID
from fastapi import Depends, HTTPException, Request
from langchain.messages import HumanMessage, AIMessage

from app import app, require_user, thread_config, lock_for


@app.get("/threads/{thread_id}/messages")
async def get_history(
    thread_id: UUID,
    request: Request,
    user: str = Depends(require_user),
):
    # TODO: Construct the authenticated thread configuration.
    # TODO: Acquire the thread lock.
    # TODO: Retrieve the graph state asynchronously.
    # TODO: Return HTTP 404 for an unknown conversation.
    # TODO: Convert human and assistant messages to JSON.
    raise NotImplementedError

Summary

  • FastAPI exposes compiled LangGraph applications through validated HTTP endpoints without coupling graph execution to a particular frontend.
  • AsyncPostgresSaver provides durable thread-level persistence that survives application restarts.
  • Authentication and thread ownership must be enforced by the API rather than trusted from frontend input.
  • Redis complements PostgreSQL with shared infrastructure such as rate limiting, caching, and distributed coordination.
  • Streamlit provides rapid Python-based interfaces for internal agent applications and operational dashboards.
  • React enables customizable customer-facing experiences with asynchronous requests and incremental response rendering.
  • Streaming, concurrency control, lifecycle management, and failure handling are essential when exposing stateful graphs as network services.