22  Serving over HTTP

Every run in this book has ended on your own terminal. You typed python code/....py, a __main__ block called graph.invoke(...), and the answer printed. That is fine for learning and useless for anything else. A graph only your shell can reach is not a service.

Part II promised the first step out of that box: serving the graph over HTTP so something other than a __main__ block can call it. That something is an HTTP client — a browser, a mobile app, another backend. This chapter is the thin layer that lets it in.

Two words first, because the demo bends them. A thread stores a conversation; a run is one execution on it. To keep this chapter’s API small, it calls the thread’s id runId and exposes only the thread’s latest result — one string doing both jobs. A Gotcha later shows what that costs.

Everything else is plumbing around one idea: the request’s thread_id becomes the graph’s thread_id. The runId you hand back to a client is the checkpointer’s filing label from Chapter 8. The client comes back with that id, and you look the run up in the checkpoint — finished, or stopped partway and still waiting for someone to tell it what to do.

The chapter in four stages.
Stage What runs at the end of it Where
serve an answer, look it up by id POST /ask, GET /run/{id} Section 22.3, Section 22.5
pause at the gate, resume with a decision POST /run/{id}/resume Section 22.4
stream the answer token by token the async server and a client that reads it Section 22.7, Section 22.8
restart and scale a durable, shared checkpointer the Gotcha on the checkpointer choice, and the challenges

22.1 The graph, and the one place it stops

The model connection is the same local block every model-backed chapter has used (Chapter 12):

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="http://localhost:1234/v1",  # your local server, not the OpenAI cloud
    api_key="lm-studio",                   # the local server ignores the key
    model="qwen/qwen3.8-27b",              # a capable open model that follows instructions
    temperature=0,                         # 0 = as reproducible as a real model gets
    reasoning_effort="none",               # Qwen3.8 thinks by default; off for now
)

The graph is Chapter 18’s doc-bot plus one addition, and that addition is why this chapter has three endpoints instead of one. search_docs returns stubbed sources — real retrieval waits for Part III — and generate is a plain llm.invoke, exactly as before.

But the stub can come up empty. When it does, the graph refuses to go out to the web on its own: it stops at approve_web and waits for a person. That is Chapter 9’s gate with an HTTP request in front of it. Serving does not touch a single node body.

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart LR
    START(["START"]) --> search_docs["search_docs"]
    search_docs -->|docs found| generate["<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>generate"]
    search_docs -->|nothing found| approve_web{"approve_web<br/><i>interrupt()</i>"}
    approve_web -->|approved| web_search["web_search"]
    approve_web -->|refused| generate
    web_search --> generate
    generate --> END(["END"])

from typing import NotRequired, TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt


class State(TypedDict):
    question: str                          # input, set by the caller
    docs: NotRequired[list[str]]           # written by search_docs
    approved: NotRequired[bool]            # written by approve_web, from the human
    web_results: NotRequired[list[str]]    # written by web_search, if allowed
    answer: NotRequired[str]               # written by generate


def approve_web_node(state: State) -> dict:
1    decision = interrupt({
        "node": "approve_web",
        "ask": "The local docs do not cover this. Search the web?",
        "question": state["question"],
    })
    return {"approved": bool(decision)}


def route_after_docs(state: State) -> str:
2    return "generate" if state.get("docs") else "approve_web"


def route_after_approval(state: State) -> str:
3    return "web_search" if state.get("approved") else "generate"


# search_docs_node, web_search_node and generate_node are stubbed lookups and a
# plain llm.invoke. Serving leaves every node body untouched.

builder = StateGraph(State)
builder.add_node("search_docs", search_docs_node)
builder.add_node("approve_web", approve_web_node)
builder.add_node("web_search", web_search_node)
builder.add_node("generate", generate_node)

builder.add_edge(START, "search_docs")
builder.add_conditional_edges("search_docs", route_after_docs, ["approve_web", "generate"])
builder.add_conditional_edges("approve_web", route_after_approval, ["web_search", "generate"])
builder.add_edge("web_search", "generate")
builder.add_edge("generate", END)

# Without a checkpointer the answer lives only in the POST response - and a run
# that parks at `approve_web` could never be picked up again at all.
checkpointer = InMemorySaver()
graph = builder.compile(checkpointer=checkpointer)
1
Chapter 9’s gate, unchanged. interrupt() freezes the graph inside this node and surfaces its payload. The run is left in the checkpointer with next == ("approve_web",) and no answer to this question in State. On resume the node runs again from its first line (Chapter 9) — which is why nothing but the interrupt() call belongs in it.
2
Ch3’s conditional edge, deciding whether a person needs to be involved at all.
3
Refusing is an answer too. The run falls through to generate, which answers from the local documents — here, that they say nothing.

In the __main__ world the return value of invoke sat in a variable and you printed it whenever you liked. Over HTTP the request that produced an answer is gone the moment its response flushes, so the only way a later request can find that answer is to read it back from the checkpoint. That is why this compile line takes a checkpointer. For a run parked at the gate it is stronger still: without one there is nothing to come back to.

22.2 The client & server

Three endpoints come out of that one gate, and they are the whole surface of this chapter. We use FastAPI1 to implement them:

The chapter’s HTTP surface. Everything else is FastAPI boilerplate.
Endpoint Body Comes back
POST /ask question, and optionally thread_id to name the run yourself status: "done" with the answer — or status: "paused" with awaiting and no answer at all, when the run stopped at the gate
POST /run/{id}/resume approve: true or false status: "done" with the answer and webSearched. 404 if the id never ran, 409 if the run is finished or was not waiting for anything
GET /run/{id} — status, question, answer, plus awaiting while paused and error / parkedAt if a node raised. 404 if the id never ran. Re-runs nothing

{id} is always the thread_id; there is no other kind of id here. Read the exchange top to bottom: a POST /ask that either answers or parks at the gate, a resume that frees a parked run, and a GET that reads a run back without running anything.

sequenceDiagram
    actor H as Human
    participant C as Client
    participant S as Server (FastAPI)
    participant K as LangGraph
    C->>S: POST /ask {question}
    S->>K: run graph → save checkpoint (runId)
    alt docs found
        S-->>C: done — answer + runId
    else local docs miss — parks at the gate
        S-->>C: paused — awaiting + runId
        C-->>H: show "search the web?"
        H->>C: approve or deny
        C->>S: POST /run/{runId}/resume {approve}
        S->>K: resume from the gate
        S-->>C: done — answer + webSearched
    end
    Note over C,K: later, query with runId
    C->>S: GET /run/{runId}
    S->>K: read checkpoint — no re-run
    S-->>C: status, question, answer

22.3 Ask the question

The simplest web layer maps one HTTP request to one graph execution. FastAPI describes the request body with a Pydantic model: a required question, and an optional thread_id the caller may supply to name — or resume — the run themselves. (Two new packages this chapter, both pinned in the companion requirements.txt: pip install fastapi==0.141.1 uvicorn==0.52.3.)

import uuid
from typing import Optional

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI(title="doc-bot")


class AskRequest(BaseModel):
    question: str
    thread_id: Optional[str] = None

The POST /ask handler does three things, and the middle one is just invoke:

@app.post("/ask")
def ask(req: AskRequest):
    """Start a run. It either finishes, or it parks at the approval gate."""
    # runId IS the graph's thread_id: the caller's if they sent one, else fresh
1    run_id = req.thread_id or str(uuid.uuid4())
    config = {"configurable": {"thread_id": run_id}}

    # A new question is a new run: clear this run's derived fields so a reused
    # thread_id cannot leak an earlier run's web_results/answer into it.
    fresh_run = {"question": req.question, "docs": [], "web_results": [],
                 "approved": None, "answer": None}
    try:
        result = graph.invoke(fresh_run, config=config)
2    except Exception as exc:
        raise HTTPException(
            status_code=500,
            detail={"runId": run_id, "error": str(exc)},
        )

3    if "__interrupt__" in result:
        return {
            "runId": run_id,
            "status": "paused",
            "awaiting": result["__interrupt__"][0].value,
        }

    return {"runId": run_id, "status": "done", "answer": result.get("answer")}
1
The identity this chapter turns on. The runId returned below is the thread_id passed into config, not a row in some table of runs.
2
A node that raises propagates straight out of invoke. Catch it, so the caller gets the runId back instead of a bare 500 and a stack trace. The failure is checkpointed under that id, so GET /run/{id} still reports status: "failed" and where it stopped (Section 22.5).
3
A parked run comes back carrying __interrupt__ instead of an answer (Section 9.4). Two shapes out of one endpoint, and a status the caller can branch on — rather than having to notice that answer is missing.

That is already enough to run. Start the server in one terminal, then ask a question from another:

# 1) start the server
python code/ch20_serving.py

# 2) ask a question; get back a runId and the answer
curl -X POST localhost:8000/ask \
     -H "Content-Type: application/json" \
     -d '{"question":"How do I configure Kafka batch consumers?"}'
{
  "runId": "a8af53ff-1bf3-483a-b719-70f99a705680",
  "status": "done",
  "answer": "To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` to enable batch consumption and tune the `max-poll-records` setting."
}

No thread_id went in, so the server minted one and told you which it chose.

TipTry it: a run that fails is a status, not a stack trace

The third shape is the one you cannot produce on demand against a healthy model. So code/ch20_failed_run.py swaps in a graph whose generate raises and drives the same handlers in-process — no server, no model:

POST /ask -> 500  runId=0bcd3735-a039-462c-8ff5-667fdd55138d  error='model endpoint returned 502'
GET  /run/{runId} -> 200  status=failed  parkedAt=['generate']  error="RuntimeError('model endpoint returned 502')"
POST /run/{runId}/resume -> 409  'run is not waiting for input'
stream_tokens -> data: {"failed": "RuntimeError"} data: [DONE]

The 500 still carries the runId. The run reads back as failed, with the error and the node it stopped at. And resume refuses it with a 409, because there is no gate to answer — only a failure that resuming would run again. The last line is the streaming endpoint’s version of the same run, which Section 22.7 comes to.

Mint a fresh UUID when the caller omits one, and two concurrent requests get two distinct threads that never collide in the checkpoint. Let the caller pass their own, and they can pick a stable id and come back to it.

The second shape is the interesting one. A question the local documents cover is answered in one request, and the runId is a convenience. A question they do not cover comes back with a runId, a status of "paused", and no answer at all. The run is sitting in the checkpointer at approve_web, and that id is now the only way to reach it.

Ask something the stubbed documents do not cover, and that shape comes out of the same endpoint and the same body:

curl -X POST localhost:8000/ask \
     -H "Content-Type: application/json" \
     -d '{"question":"How do I tune Redis connection pools?","thread_id":"redis-1"}'
{
  "runId": "redis-1",
  "status": "paused",
  "awaiting": {
    "node": "approve_web",
    "ask": "The local docs do not cover this. Search the web?",
    "question": "How do I tune Redis connection pools?"
  }
}

No answer. The run is parked at the gate, and it stays parked.

Note the plain def. FastAPI runs a non-async handler in a threadpool and awaits it, so the blocking graph.invoke inside is safe — it ties up a worker thread, not the event loop.

22.4 Resuming

A run parked at the second shape — the human-in-the-loop gate — waits in the checkpointer for a person to decide. The user clicks a button to approve or deny the web search. Only that decision can free it, and over HTTP that decision arrives as a third endpoint. Almost all of it is the check:

class ResumeRequest(BaseModel):
    approve: bool


@app.post("/run/{run_id}/resume")
def resume(run_id: str, req: ResumeRequest):
    config = {"configurable": {"thread_id": run_id}}
    snapshot = graph.get_state(config)
1    if snapshot.created_at is None:
        raise HTTPException(status_code=404, detail="unknown runId")
2    if not snapshot.next:
        raise HTTPException(status_code=409, detail="run is already finished")
3    if not snapshot.interrupts:
        raise HTTPException(status_code=409, detail="run is not waiting for input")

4    result = graph.invoke(Command(resume=req.approve), config=config)
    return {
        "runId": run_id,
        "status": "done",
        "answer": result.get("answer"),
        "webSearched": bool(result.get("web_results")),
    }
1
The same existence check as the lookup endpoint, for the same reason: snapshot.created_at is None means the id never ran. It reads through graph.get_state, so it does not care which saver is behind the graph.
2
next is empty on a thread that ran to END, so a finished run gets a 409 rather than a silent no-op.
3
next catches only one of the two ways to be un-resumable. A run that stopped because a node raised also has work pending and no gate to answer. Without this line it would sail past the check, and Command(resume=…) would simply run the failure again and hand the caller a 500. Ask for the pending interrupt — the thing this endpoint exists to answer.
4
Section 9.4’s Command(resume=…), arriving as an HTTP body. The value becomes the return value of the interrupt() call that stopped the node, and the graph carries on from there.

One more line wraps both of those handlers in the companion, and it closes a hole the checks above cannot. Every handler reads the snapshot, decides, then invokes. Two of those interleaved on the same thread_id both pass the check and both invoke. A double-clicked “approve” runs the approved web search twice; two questions on one thread race each other’s state. The shared saver gives every replica the same state — it does not serialize their access to it.

So a request claims the thread for the duration of its run, and a second request on a claimed thread is refused rather than queued. The caller already holds a runId and can GET it:

_in_flight: set[str] = set()
_in_flight_lock = threading.Lock()


@contextmanager
def claim(run_id: str):
    with _in_flight_lock:
        if run_id in _in_flight:
            raise HTTPException(status_code=409, detail="a run is already in progress on this thread")
        _in_flight.add(run_id)
    try:
        yield
    finally:
        with _in_flight_lock:
            _in_flight.discard(run_id)

ask and resume run inside with claim(run_id):. In resume the claim comes before the snapshot is read, because check-then-resume is the window two approvals slip through. The smoke client fires two approvals of one parked run concurrently and expects [200, 409].

Two things this line does not do. It lives in the process, so with several replicas the claim has to move to where the checkpoints are — the Gold challenge’s Redis is the natural place. And a 409 is a policy: queueing the second request behind the first is the other defensible answer, and either beats running it.

Reading the snapshot and testing created_at is one round-trip to the saver, and it serves both the existence check and the state the endpoint needs anyway. It asks nothing of the InMemorySaver that a durable saver cannot answer.

This is the endpoint that makes the runId worth handing out. GET /run/{id} on a finished run hands back an answer the caller already received; a cache would do as well. This one hands back an answer that did not exist until the request arrived. No cache can do that, because there was nothing to cache — half a run, waiting in the checkpointer for a person to say yes.

Refusing works the same way, and it is not an error. approve: false routes past web_search to generate, which answers from the local documents — here, by saying it cannot. A human declining an external call is a normal outcome, and the graph is built to finish either way.

WarningGotcha: one call is not one conversation

runId = thread_id is the identity this chapter turns on, and it welds together two things that are not the same.

A thread_id names a conversation — a State that later requests add to. A run id names one execution. Because they are the same string here, POST /ask twice with one id is not two questions: the second call runs the graph again on a thread that already reached END.

And “runs again” is not “starts clean”. With no reducers, each channel simply keeps its last value, so only the fields the second run actually writes get overwritten. A field it skips — web_results, when this time the web is refused — still holds the first run’s value, and generate would answer the new question from the old sources. That is why the handler clears the derived fields on every /ask (the fresh_run dict above); with that reset, GET /run/{id} reflects only the current run. Give State a reducer instead, the way a chat bot does with add_messages, and successive runs accumulate on purpose.

For a one-shot /ask that is a footgun, which is why the handler mints a UUID when the caller sends nothing. For a chat endpoint it is the whole feature, and the caller should pass a stable id. A real service separates the two: POST /threads/{tid}/runs returns a run_id, status and resume take that run_id, and the thread outlives all of them. That is the shape LangGraph Platform exposes.

22.5 Looking a run up

A client holding a runId comes back with two questions. What state is this run in — running, paused at the gate, failed, or done? And what did it produce? Both answers are already in the checkpoint, so the lookup endpoint reads that run’s latest snapshot and answers both without re-executing a thing:

@app.get("/run/{run_id}")
def get_run(run_id: str):
    """Take the runId (= thread_id) and pull this run's latest snapshot."""
    config = {"configurable": {"thread_id": run_id}}
    snapshot = graph.get_state(config)
1    if snapshot.created_at is None:
        raise HTTPException(status_code=404, detail="unknown runId")

2    error = next((t.error for t in snapshot.tasks if t.error), None)
    if error:
        status = "failed"
    elif snapshot.interrupts:
        status = "paused"
    elif snapshot.next:
        status = "running"
    else:
        status = "done"

    return {
        "runId": run_id,
        "status": status,
        "question": snapshot.values.get("question"),
        "answer": snapshot.values.get("answer"),
        **({"awaiting": snapshot.interrupts[0].value} if snapshot.interrupts else {}),
        **({"error": str(error), "parkedAt": list(snapshot.next)} if error else {}),
    }
1
Ask the checkpointer whether the id exists. A thread that never ran comes back with snapshot.created_at is None, and every saver answers get_state that way — so this line keeps working when you swap InMemorySaver for a durable SqliteSaver or RedisSaver. Reaching into checkpointer.storage would not: that dict is the InMemorySaver’s alone, and a durable saver has no such attribute to test.
2
Four states, not two. snapshot.next is the set of nodes the graph is about to run, and it is non-empty for three very different reasons: the run is still going, it stopped because a task raised, or it is waiting for a human. A status endpoint that calls all three "running" is lying about the two cases it exists for. Both distinctions are on the snapshot — the exception on snapshot.tasks[…].error, the pending gate in snapshot.interrupts — so the handler names them, and repeats what the run is waiting for. awaiting, error and parkedAt appear only when they mean something: a field that is always present and usually null invites callers to test the wrong thing. Chapter 26 reads the same facts out of the writes table, one level down.

Reach for a runs table beside the checkpointer only when you need what the checkpoint cannot give: liveness, leases, a scheduler’s view. Not for the two questions above, which the checkpoint already answers.

22.6 Running it

The server from Section 22.3 is still up, and it has left two runs behind: the Kafka question under a minted id, and redis-1 parked at the gate. Both are now reachable by id alone.

Hand the finished run’s runId to the lookup endpoint — the one your server minted back in Section 22.3, not the one printed here — and the answer is still there:

curl localhost:8000/run/a8af53ff-1bf3-483a-b719-70f99a705680
{
  "runId": "a8af53ff-1bf3-483a-b719-70f99a705680",
  "status": "done",
  "question": "How do I configure Kafka batch consumers?",
  "answer": "To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` to enable batch consumption and tune the `max-poll-records` setting."
}

The parked run reads back just as plainly, and the lookup endpoint says so rather than pretending the run is still moving:

curl localhost:8000/run/redis-1
{
  "runId": "redis-1",
  "status": "paused",
  "question": "How do I tune Redis connection pools?",
  "answer": null,
  "awaiting": {
    "node": "approve_web",
    "ask": "The local docs do not cover this. Search the web?",
    "question": "How do I tune Redis connection pools?"
  }
}

Answer the gate and the run finishes:

curl -X POST localhost:8000/run/redis-1/resume \
     -H "Content-Type: application/json" -d '{"approve":true}'
{
  "runId": "redis-1",
  "status": "done",
  "answer": "To tune Redis connection pools, raise the pool ceiling and set a wait timeout.",
  "webSearched": true
}

Send {"approve":false} instead and the run still finishes. webSearched comes back false, and the answer is whatever the local documents supported — which for this question is an admission that they supported nothing.

Ask for a runId that never ran and you get the 404, because there is no checkpoint under that thread:

curl -i localhost:8000/run/never-happened
HTTP/1.1 404 Not Found
{"detail":"unknown runId"}

A server starts and waits, so it cannot be a closed loop the way every other chapter’s file is — run it, read what happened. Hence one more file:

python code/ch20_smoke_client.py

It starts ch20_serving.py as a child process, waits for the port, drives all three endpoints over real HTTP, and stops the server again. The last six checks are the ones worth watching: a question the local documents miss comes back paused with no answer, stays paused when you look it up again, and yields an answer only when the run is resumed. The answer: lines are shown by excerpt (first line, trimmed — Chapter 12).

starting ch20_serving.py ...
server is up on http://127.0.0.1:8000

POST /ask -> 200  runId=1a7dc478-d45d-4916-a0ee-2b821c985660
  answer: To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` and tune the `max-poll-records` setting.
POST /ask with thread_id='smoke-client-thread' -> runId=smoke-client-thread
GET  /run/{runId} -> 200  status=done
  question: How do I configure Kafka batch consumers?
GET  /run/never-happened -> 404  'unknown runId'

POST /ask (uncovered) -> status=paused  runId=56b04391-cfc4-410a-ac27-43da92fc1870
  awaiting: The local docs do not cover this. Search the web?
GET  /run/{runId} -> status=paused  answer=None
POST /run/{runId}/resume approve=True -> webSearched=True
  answer: To tune Redis connection pools, raise the pool ceiling and set a wait timeout.
POST /run/{runId}/resume approve=False -> webSearched=False
  answer: The provided sources do not contain the answer.
POST /run/{runId}/resume x2 concurrently -> [200, 409]

  ... 15 checks (runId round-trips, done/404, parks-then-resumes, one run per thread) ...

all 15 checks passed
server stopped.

That is the shape to copy when you put a graph behind HTTP for real. The endpoint tests worth writing are about ids, status codes and what survives in storage — the things your code decides — not about what the model said.

One thing this demo leaves out on purpose: every endpoint here is wide open. This graph is not a standalone service to secure on its own. It is one more resource in your backend, and it belongs behind the same authentication and authorization the rest of that backend already enforces. Authorization is the half that is easy to forget here, because the caller picks the runId: send thread_id: "demo-2" and you are handed run demo-2 no matter who started it. Whatever already decides who may read a given row in your database has to decide who may read a run through these endpoints too.

22.7 Streaming the answer: async + SSE

The synchronous endpoint makes the client wait for the entire answer before a single byte comes back. For a hard-coded Part I node that was instant. For a real model, generate can spend several seconds writing, and the caller stares at a frozen request for all of them. Every chat product does the opposite — words appear as the model thinks them. That is the ChatGPT typewriter from Section 18.4, now carried over the wire.

As in Chapter 18, streaming is a decision made outside the graph. Two things change from the sync server; the rest is the same code. The endpoint becomes async def and returns a StreamingResponse, and it drives the graph with graph.astream(..., stream_mode="messages"), which yields a (message_chunk, metadata) pair for every LLM token as it is produced. An async generator turns those tokens into Server-Sent Events2 — one data: line per token, a final [DONE] to close the stream.

Nothing here accumulates. Each yield hands one data: line to FastAPI, which sends it before asking the generator for the next. That is the whole reason the caller sees words appear instead of waiting for the answer. The async on the for is what lets the function wait on the model between tokens without blocking the event loop.

That loop deserves one sentence of model before the code leans on it. An async server runs every request on a single event loop, which is a scheduler with one rule: a request runs until it reaches an await on something not yet ready (the next token, a socket, a database), and at that point it steps aside and the loop runs whatever other request is ready. When the awaited thing arrives, the request resumes where it stopped. So await is a yield point, and the loop is what makes twenty slow model streams share one process without twenty threads. That is as much as this endpoint needs. What async is for, what it costs, where it stops paying, and the three ways it fails while looking fine are the next chapter’s whole subject (Chapter 23); here it is enough to know that the loop is the reason the generator below can wait cheaply.

import json

from fastapi.responses import StreamingResponse


async def stream_tokens(question: str, run_id: str):
    """Drive the graph and yield Server-Sent Events: tokens, or a pause at the gate."""
    config = {"configurable": {"thread_id": run_id}}
    # Same reset as the sync handler: a reused thread keeps each channel's last
    # value, so clear the derived fields — otherwise a refused web search this
    # time answers the new question from the previous run's sources.
    fresh_run = {"question": question, "docs": [], "web_results": [],
                 "approved": None, "answer": None}
5    try:
        try:
            async for msg_chunk, metadata in graph.astream(
                fresh_run, config=config, stream_mode="messages"
            ):
1                if metadata.get("langgraph_node") == "generate" and msg_chunk.content:
                    # JSON-encode so a token with a newline can't break SSE framing.
2                    yield f"data: {json.dumps({'token': msg_chunk.content})}\n\n"
4        except Exception as exc:
            yield f"data: {json.dumps({'failed': type(exc).__name__})}\n\n"
            yield "data: [DONE]\n\n"
            return

3        snapshot = await graph.aget_state(config)
        if snapshot.interrupts:
            yield f"data: {json.dumps({'paused': snapshot.interrupts[0].value})}\n\n"
        yield "data: [DONE]\n\n"
    finally:
        _in_flight.discard(run_id)
1
The filter from Section 18.4. It matters the moment a graph has a second model call: search_docs emits nothing here, but a summarizer or a critic would, and its tokens would carry a different node name.
2
The one detail SSE adds. A raw newline inside a data: line would split one event into two, so each token travels as a tiny JSON object.
3
messages mode does not surface the interrupt, so read it off the checkpoint once the run stops and emit a paused event carrying the same payload the sync endpoint returned. The client resumes through POST /run/{id}/resume exactly as before — the runId is still in the X-Run-Id header.
4
The third ending. A node that raises after some tokens have gone out cannot take them back, and a stream that simply stops looks, from the other end, exactly like one that finished. So the failure is an event of its own — redacted to the exception’s class, since the message may quote internals — and [DONE] still follows it. The failure itself is checkpointed under the run id, so GET /run/{id} reports it with where it stopped, as the Try-it above showed.
5
The claim ask took before this generator existed, given back. finally and not a line at the end: a client can disconnect mid-stream, which closes the generator here rather than running it to the last yield, and a claim released only on the happy path locks that thread for the life of the process.

A stream, then, has three endings the client must tell apart, and one non-ending. Completed: tokens, then [DONE]. Paused: a paused event, then [DONE]. Failed: a failed event, then [DONE]. And cut off: the socket closes with no [DONE] at all — a server restart, a proxy timeout, a dropped connection. [DONE] is the only thing that means “the server finished what it had to say”. A socket closing is not, and a client that treats the two the same will render half an answer as an answer. The protocol is a small one — one terminal marker, three terminal events — and the client below is written around it.

Put the pieces of this chapter together and they are one contract, the one the rest of Part III leans on without restating: a runId is a thread_id; one run per thread at a time, which is what the claim enforces; and every run ends in exactly one of completed, paused, failed or cut off. An exhausted retry (Chapter 21) arrives here as failed — a status, never a fallback answer — and what lets a paused or failed run be picked up at all is the checkpoint and its pending writes, which Chapter 26 opens up.

The endpoint itself is almost all wrapper. It picks the thread_id as the sync version did, then hands the generator to StreamingResponse, which flushes each yield to the client the instant it is produced. One piece of the claim comes apart first: the taking is its own function here, and it has no lock.

_in_flight: set[str] = set()


def take(run_id: str) -> None:
    """Claim the thread, or refuse. Nothing may `await` between these two lines."""
    if run_id in _in_flight:
        raise HTTPException(status_code=409,
                            detail="a run is already in progress on this thread")
    _in_flight.add(run_id)

The sync twin needed _in_flight_lock because two threads can interleave between the test and the add. One event loop cannot: it switches only at an await, and there is none between those two lines, so the pair is already indivisible. The proviso is the whole design — the claim has to be taken before the first await, not after it. The endpoint keeps take and the release apart for a separate reason, in the comment below.

@app.post("/ask")
async def ask(req: AskRequest):
    """Stream the answer token by token as it is generated."""
    run_id = req.thread_id or str(uuid.uuid4())
    # Taken here and released in the generator, which is the one place the sync
    # twin's `with claim(run_id):` cannot be copied. A StreamingResponse hands
    # back a generator: the endpoint returns BEFORE the work starts, so a `with`
    # around this return would release the claim before the first token. Taking
    # it here is also what makes a duplicate a real 409 instead of an error event
    # inside a 200 stream.
    take(run_id)
    return StreamingResponse(
        stream_tokens(req.question, run_id),
        media_type="text/event-stream",
        headers={"X-Run-Id": run_id},
    )

The three pieces do not call each other in the order you might read them. stream_tokens(...) runs nothing — it builds a generator — and ask is finished the moment it hands that generator to StreamingResponse. Everything after that is StreamingResponse pulling, one token at a time, long after the handler returned:

sequenceDiagram
    participant C as Client
    participant A as ask()
    participant R as StreamingResponse
    participant G as stream_tokens()
    participant K as graph.astream()
    C->>A: POST /ask {question}
    A->>G: stream_tokens(question, runId)
    Note over G: a generator object
    A->>R: StreamingResponse(gen, X-Run-Id)
    A-->>C: 200 + headers, body still open
    loop once per token
        R->>G: next?
        G->>K: async for ...
        K-->>G: (message_chunk, metadata)
        G-->>R: yield "data: {token}"
        R-->>C: flush this line
    end
    G-->>R: yield "data: [DONE]"
    R-->>C: flush, close

One difference is forced by the medium. The response body is the token stream now, so there is no room in it for a runId. The server puts it in an X-Run-Id header instead — which you print with curl -D - (dump headers); -N alone only unbuffers the body, it does not show headers — and which a browser’s EventSource will not expose. EventSource cannot POST either, so a front end drives this with fetch() and a stream reader.

NoteIf the browser and the API are not same-origin

The .mjs clients later in this chapter run under Node, where none of this applies. In a browser served from a different origin than the API, two things bite that curl never sees. The cross-origin POST /ask triggers a CORS preflight the server has to answer. And even once the request succeeds, script cannot read X-Run-Id unless the server lists it: browsers hide every response header from cross-origin JS except a short safelist. Both are one setting:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://your-frontend.example"],  # not "*", once you add auth
    allow_methods=["POST", "GET"],
    expose_headers=["X-Run-Id"],                       # or the id is unreadable
)

The simplest escape is to dodge it entirely: serve the front end from the same origin as the API, and there is no cross-origin request to configure.

Everything else stayed put. generate still returns {"answer": ...} when it finishes — streaming observes the node, it does not replace its return — so the answer still lands in State and is still checkpointed. The lookup endpoint asks the same question of the same checkpoint, in the async voice:

@app.get("/run/{run_id}")
async def get_run(run_id: str):
    """After the stream ends, the finished answer is still in the checkpoint."""
    config = {"configurable": {"thread_id": run_id}}
    snapshot = await graph.aget_state(config)   # async handler, async read
    if snapshot.created_at is None:             # saver-neutral, same as the sync file
        raise HTTPException(status_code=404, detail="unknown runId")

    error = next((t.error for t in snapshot.tasks if t.error), None)
    if error:
        status = "failed"
    elif snapshot.interrupts:                   # parked at the gate, awaiting a human
        status = "paused"
    elif snapshot.next:
        status = "running"
    else:
        status = "done"
    return {
        "runId": run_id,
        "status": status,
        "question": snapshot.values.get("question"),
        "answer": snapshot.values.get("answer"),
        **({"awaiting": snapshot.interrupts[0].value} if snapshot.interrupts else {}),
        **({"error": str(error), "parkedAt": list(snapshot.next)} if error else {}),
    }

await graph.aget_state(...), not graph.get_state(...): in an async def handler the sync read blocks the event loop every other stream is sharing. The four-state status and the awaiting field are the sync endpoint’s, unchanged — the async handler owes the client the same contract, so a paused run reports what it is waiting on here too.

Resuming is the sync endpoint’s /resume in the async voice: ainvoke in place of invoke, the existence and gate checks identical:

@app.post("/run/{run_id}/resume")
async def resume(run_id: str, req: ResumeRequest):
    """Answer the gate and let the parked run finish."""
    config = {"configurable": {"thread_id": run_id}}
    # Before the first `await`, and around all three steps.
    with claim(run_id):
        snapshot = await graph.aget_state(config)
        if snapshot.created_at is None:
            raise HTTPException(status_code=404, detail="unknown runId")
        if not snapshot.next:
            raise HTTPException(status_code=409, detail="run is already finished")
        if not snapshot.interrupts:
            raise HTTPException(status_code=409, detail="run is not waiting for input")

        result = await graph.ainvoke(Command(resume=req.approve), config=config)
    return {"runId": run_id, "status": "done", "answer": result.get("answer"),
            "webSearched": bool(result.get("web_results"))}

The claim is the sync server’s, copied across unchanged — and async needs it more, not less. Under def endpoints the window between deciding the gate is open and resuming through it is a thread-scheduling accident. Under async def it is not an accident: await is the yield point, so the second request is guaranteed its chance to read the same snapshot while the first is suspended. This file ran without the claim for a while, and two concurrent approvals of one parked run both returned 200 and both generated — start times equal to the millisecond, on a gate a human had answered once.

It cost one rule, and the rule is the whole design: take the claim before the first await. One event loop never switches between two statements that do not await, so test, then add is already indivisible — which is why there is no threading.Lock on this side. Claim after the snapshot is read and the window is exactly where it was.

ask cannot use with at all. A StreamingResponse hands back a generator and the work starts after the endpoint has returned, so the claim is taken in the handler and released in the generator’s finally. That split is also what makes a duplicate a real 409 rather than an error event buried inside a 200 stream.

A question the local docs miss streams a paused event and no tokens. The client GETs the run, sees status: "paused" with the gate in awaiting, and POSTs the decision to /resume — the runId from the X-Run-Id header the whole time. The pause survives streaming intact.

InMemorySaver answers both forms, so nothing here complains if you get it wrong. It surfaces when you swap in a durable saver: the sync SqliteSaver raises NotImplementedError on the async path and names its twin. Take the twin — AsyncSqliteSaver, AsyncPostgresSaver.

Drive it with curl -N, supplying our own thread_id so we know the id up front:

python code/ch20_serving_async.py   # on port 8001

curl -N -X POST localhost:8001/ask \
     -H "Content-Type: application/json" \
1     -d '{"question":"How do I configure Kafka batch consumers?","thread_id":"demo-2"}'
1
-N (--no-buffer) tells curl to flush each piece to the terminal the instant it arrives, instead of holding output in its own buffer — so you watch the answer appear token by token. Without it curl still receives the stream the same way, but prints it in one lump, and the streaming is invisible.
data: {"token": "To"}

data: {"token": " configure"}

data: {"token": " Kafka"}

data: {"token": " batch"}

data: {"token": " consumers"}

data: {"token": ","}

data: {"token": " set"}

... 21 more events, one per token ...

data: {"token": " setting"}

data: {"token": "."}

data: [DONE]

On screen those events do not appear at once. They type themselves out, one token per line, because StreamingResponse flushes each yield immediately. When the stream closes, the run is finished and checkpointed under demo-2, so the same lookup endpoint returns the whole answer, reassembled from the tokens you just watched fly by:

curl localhost:8001/run/demo-2
{
  "runId": "demo-2",
  "status": "done",
  "question": "How do I configure Kafka batch consumers?",
  "answer": "To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` to enable batch consumption and tune the `max-poll-records` setting according to your needs."
}

The token text is the model’s, and it will drift on you. An earlier version of the companion file carried a comment promising the first event would be You; the first real run against this server printed To. What you control is the framing: one data: event per token, a closing [DONE], and a checkpoint you can read back by thread_id once the stream is spent.

22.8 Reading the stream on the client

curl -N proved the stream works. A real front end reads it the same way, in JavaScript. The one tool you cannot use is the browser’s built-in EventSource: it only does GET, sends no request body, and sets no headers — and POST /ask needs all three. So the client drives the stream with fetch() and a reader over the response body:

const res = await fetch("http://localhost:8001/ask", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ question, thread_id: "demo-2" }),
});

const runId = res.headers.get("X-Run-Id");   // the id is in the header, not the body
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let runStatus = null;   // "paused" | "failed", as the server reported it
let sawDone = false;    // did [DONE] arrive? that, not EOF, is the protocol's ending

1outer: while (true) {
  const { value, done } = await reader.read();
3  if (done) break;      // the socket closed — not proof the server finished
  buffer += decoder.decode(value, { stream: true });

  let i;
  while ((i = buffer.indexOf("\n\n")) !== -1) {   // one SSE event per blank line
    const event = buffer.slice(0, i);
    buffer = buffer.slice(i + 2);
    for (const line of event.split("\n")) {
2      if (!line.startsWith("data:")) continue;
      const data = line.slice(5).trim();
      if (data === "[DONE]") { sawDone = true; break outer; }   // the server's last word
      const evt = JSON.parse(data);
      if (evt.paused) { showGate(evt.paused); runStatus = "paused"; continue; }
      if (evt.failed) { showFailure(runId); runStatus = "failed"; continue; }
      appendToken(evt.token);                     // render as each token lands
    }
  }
}
if (!sawDone) showIncomplete(runId);             // EOF with no [DONE]: partial text is not an answer
1
curl’s read loop, in JS.
2
The line carrying a data: chunk; skip everything else.
3
done reports the socket; the protocol’s own ending is [DONE]. The loop leaves with sawDone still false when the stream was cut off, and the client’s one rule is that this case is incomplete, whatever text it has rendered and whatever status it saw on the way — GET /run/{id} says what the run actually did. The two are separate on purpose: runStatus records what the run reported, sawDone whether the response finished, and a paused that never reached [DONE] is both. The companion’s stream_handwritten.mjs exits 2 on it, and a fake server that sends one token and closes reproduces it in a second.

reader.read() is the loop curl runs for you. The difference is that there is no output buffer to switch off, so the -N question never arises — you render each token the moment you parse it. And the runId comes off the X-Run-Id header, because the body is now nothing but tokens.

WarningGotcha: don’t make /ask a GET just to use EventSource

The tempting shortcut is to sidestep fetch() entirely: make /ask a GET, put the question in the query string, and let native EventSource do the reading and reconnecting. Don’t.

/ask creates a run. It mints a runId, writes a checkpoint, and spends a model call, so it is a write — and GET is defined to be safe and idempotent. Serve it over GET and every speculative fetch fires a real run: browser prefetch, a link-preview crawler, a caching proxy. The question also lands in access logs, proxy logs, and browser history, and you get nowhere to put an Authorization header.

EventSource’s one real advantage — auto-reconnect — buys little here, because resuming a half-sent token stream is not something the server supports anyway. POST answered with server-sent events is also the shape a streaming API such as OpenAI’s takes on the wire, and in a browser the way to read that is fetch, not EventSource.

The framing loop above is worth writing once, to see what a data: stream is. In production, if you want a more robust implementation, reach for @microsoft/fetch-event-source instead. It keeps the POST, headers and body, parses the events for you, and adds configurable reconnect and error handling you would otherwise hand-roll — reconnecting reopens the request, it does not recover the tokens a half-sent stream already lost.

import { fetchEventSource } from "@microsoft/fetch-event-source";

await fetchEventSource("http://localhost:8001/ask", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ question, thread_id: "demo-2" }),
  onmessage(ev) {
    if (ev.data === "[DONE]") { sawDone = true; return; }
    const evt = JSON.parse(ev.data);
    if (evt.paused) { runStatus = "paused"; return showGate(evt.paused); }
    if (evt.failed) { runStatus = "failed"; return showFailure(runId); }
    appendToken(evt.token);
  },
  onclose() { if (!sawDone) showIncomplete(runId); },   // closed without [DONE]
  onerror(err) { throw err; },   // rethrow to stop: a retry would start a new run
  openWhenHidden: true,
});

The same three endings and the same rule, one hook over. onclose fires when the server closes the connection, and a close that [DONE] did not precede is a cut-off, not a completion. Reconnecting on it would start a new run — /ask is a write — which is why onerror rethrows instead of leaving the library to retry.

WarningGotcha: the checkpointer choice decides whether you can scale out

One server process is a demo. Production means several, with a load balancer spreading requests across replicas so you can survive traffic and a dead node. That is where InMemorySaver betrays you, and nothing in the logs will say so.

InMemorySaver keeps every run in one process’s heap. Put two replicas behind a load balancer and the POST /ask that ran on replica A leaves its checkpoint in A’s memory alone. When the follow-up GET /run/{id} lands on replica B — and the load balancer has no reason to send it anywhere in particular — B has never heard of that thread_id, so it returns 404 for a run that happened. No error is raised; runs go missing depending on which replica you hit. Restarts are the same wound: an in-memory saver dies with its process, taking every stored run with it.

Do not use the in-memory saver in production. Put the checkpoints in a store that lives outside any single process, so a run written by one replica can be read by another — and by the same box after a restart. That means a networked, shared saver every replica can reach: PostgresSaver, or a Redis checkpointer (langgraph-checkpoint-redis), or another backend of the same kind. The Gold challenge at the end of the chapter swaps this chapter’s InMemorySaver for Redis and watches a run survive both a restart and a hop to another replica. Why a shared store can serve a run it never executed — how a checkpoint is laid out and replayed — is the subject of Chapter 26.

22.9 Shutting down gracefully with RunControl

A server does not choose when it stops. A deploy, an autoscaler, a rescheduled node — the platform takes your process down while requests are still in flight, and a doc-bot run can be several seconds of LLM generation deep when it does. Graceful shutdown is the promise that a stop lands on a superstep boundary: the step in progress is allowed to finish and is checkpointed, the next one never starts, and the run resumes from there on the next boot. It buys that with the grace period the platform gives you, and it promises nothing about a node still running when the time is up. Skip the drain and the stop lands wherever the signal happened to arrive.

The everyday version is a deploy, and it ends the same way every time: the orchestrator sends SIGTERM, waits a few seconds, then sends SIGKILL. If a request is mid-run when that happens, the process dies partway through a superstep. The last checkpoint on the thread is the one from the previous step, so whatever node was executing left no trace — and when the thread resumes, that node runs again. If it had already charged a card before the signal arrived, it charges again: Chapter 21’s retry Gotcha, wearing a deploy for a disguise.

LangGraph 1.2 added a cooperative way out. Build a RunControl, hand it to the run, and flip it from your signal handler. The snippet below shows the mechanism in isolation — it is not wired into this chapter’s /ask servers. A real integration threads the same control into whatever handler runs the graph, keeps a registry of active runs so each can be drained, installs the SIGTERM handler at startup, and relies on the ordinary invoke(None, config) resume (Chapter 8) after the next boot. Here is just the drain half:

import signal
from langgraph.runtime import RunControl
from langgraph.errors import GraphDrained

control = RunControl()
signal.signal(signal.SIGTERM, lambda *_: control.request_drain("sigterm"))

try:
    result = graph.invoke(payload, config, control=control)
except GraphDrained as e:
    log.info("drained: %s", e.reason)   # the checkpoint is written; nothing to undo

The flag is read at the top of each superstep, so the step already running is allowed to finish and is checkpointed normally; the next one never starts. On the next boot, the three lines from Chapter 8 — invoke(None, config) under the same thread_id — pick the thread up at the node that never ran.

Three things it does not do, all worth knowing before you rely on it. It cancels nothing: a node blocked in a thirty-second HTTP call keeps blocking, because drain only promises there will be no next step. If you need a hard ceiling, pair it with a timeout. It is worth nothing without a durable checkpointer — drain with an InMemorySaver writes its careful checkpoint into a heap that is seconds from being freed. And a RunControl is one per run: once drained, it stays drained, so mint a fresh one for the next request rather than reusing the module-level one.

NoteDeep Dive: terminationGracePeriodSeconds on Kubernetes

The “waits a few seconds” between SIGTERM and SIGKILL is not a constant. It is a field you set on the Pod, and its default is 30 seconds — a budget an ordinary web request never approaches and a run several seconds of LLM generation deep can. It lives on the Pod spec, not the container:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: doc-bot
spec:
  template:
    spec:
      terminationGracePeriodSeconds: 45   # SIGTERM → SIGKILL window, in seconds
      containers:
        - name: doc-bot
          image: doc-bot:latest

kubelet sends SIGTERM, waits up to this many seconds, then sends the uncatchable SIGKILL. If the process exits on its own first the wait ends early, so a generous value costs nothing on a clean shutdown — it only sets the ceiling for the worst case.

That worst case is why the value must be ≥ your longest single superstep, plus a margin. Drain stops the next step, never the one in flight. So when SIGTERM lands mid-step, that step has to finish and checkpoint inside this window, or SIGKILL cuts it off with no checkpoint written and the run re-executes the node on the next boot — the same double charge from Chapter 21. If one node can spend twenty seconds in an LLM call, the 30-second default leaves ten for everything else — and a preStop hook, if you have one, spends from the same budget, not a separate one.

When the window cannot be stretched far enough — a platform that caps graceful termination, or a step whose tail latency you cannot bound — do not chase it by raising the number without limit; a longer grace period also slows every rollout and every scale-down. Attack the other side instead:

  • Cap the step, not just the pod. Pair RunControl with a per-step timeout so no single superstep can outlive the window. A step guaranteed to finish in fifteen seconds fits a 30-second grace period with room to spare; one with no ceiling never safely fits any.
  • Make steps small and idempotent. If the worst a mid-step SIGKILL can do is re-run a cheap, side-effect-free node, the grace period stops being load-bearing. The danger was never the restart — it was the re-executed side effect; an idempotent node is one you can afford to lose.
  • Keep the checkpointer durable. With a durable saver the failure mode of an overrun is “redo one node,” not “corrupt the thread.” The grace period buys cleanliness; the checkpointer is what makes the fallback survivable.

And one case no setting covers: terminationGracePeriodSeconds only applies when the pod is asked to stop. A node that crashes, loses power, or is force-deleted takes the process down with no SIGTERM at all — the final argument for a durable checkpointer and idempotent steps over any amount of grace-period tuning.

22.10 Before moving on

Four judgments to carry out of this chapter.

The checkpoint is the lookup. GET /run/{id} re-runs nothing; it reads the run’s snapshot by thread_id, and an id that never ran is a 404 for free. Hand back an id and let the client come back for the answer is the asynchronous request-reply pattern, the one HTTP has 202 Accepted for; what it normally needs is a job store, and the checkpointer is that store, already written — with the retention bill attached: a job id is exactly as durable as the saver behind it, and an InMemorySaver invalidates every outstanding runId the moment the process restarts.

A graph that stops is what makes that id load-bearing rather than convenient: only POST /run/{id}/resume will ever produce a parked run’s answer.

Streaming is a layer, not a graph change. Swap invoke for astream(stream_mode="messages") and return a StreamingResponse; the finished answer is still checkpointed, so the lookup endpoint does not change.

The checkpointer, not the web framework, decides whether you can scale out — the internals are Chapter 26. Be precise about what this chapter actually built, though: claim() is an in-process set and lock, so it serializes runs on one thread inside a single worker. Who owns a run across replicas, and how a peer’s crash is noticed, is the job of a lease — and this chapter leaves that unbuilt.

The doc-bot can now be called, by a browser, a client or another service, and it can stream its answer as it thinks. What you cannot yet do is see inside a run after it finishes. When a production request is slow, or returns garbage on the one call that mattered, the HTTP response tells you the what and nothing about the why: which node was slow, how many tokens it burned, where the time actually went. Chapter 24 — Observability builds that missing view by hand — a small tracer that wraps each node to record what it wrote, how long it took and what the model reported, so you can replay a whole run’s trajectory without reaching for a vendor. The service can speak; next we make it show its work.

New pieces in this chapter

Piece Usage
Type
FastAPI The web application; route decorators like @app.post("/ask") hang handlers on it. app = FastAPI(title="doc-bot"); the handler just calls graph.invoke(…) — serving is a layer, not a graph change
HTTPException Raise it in a handler to return an HTTP error status. raise HTTPException(status_code=404, detail="unknown runId"); read the snapshot and treat snapshot.created_at is None as “never ran” — a saver-neutral existence check that survives the swap to a durable saver
StreamingResponse A response that flushes each yield of a generator to the client immediately. StreamingResponse(stream_tokens(…), media_type="text/event-stream"); the body is the stream — the runId rides in a header
RunControl A run-scoped drain switch, from langgraph.runtime. control = RunControl(), then control.request_drain("sigterm") from a signal handler — safe to call from any thread. One per run: once drained it stays drained
GraphDrained Raised (from langgraph.errors) when a run stops at a superstep boundary because a drain was requested. except GraphDrained as e: log.info(e.reason); the checkpoint is already written, so the thread resumes with invoke(None, config)
API
graph.astream() Async twin of stream(), for use in async def handlers. async for chunk, meta in graph.astream(…, stream_mode="messages"); same modes and yields as stream()
invoke(…, control=) Hands a run its RunControl. The flag is read at the top of each superstep, so the step in flight finishes and is checkpointed and the next never starts — it cancels nothing already running, so pair it with a timeout if you need a hard ceiling

Code in this chapter

File What it runs
code/ch20_serving.py The synchronous server: FastAPI takes a question, runs the graph, and the request’s thread_id becomes the graph’s.
code/ch20_failed_run.py A failing run driven in-process with TestClient: the 500, the failed status, the 409 on resume, and the stream’s ending.
code/ch20_serving_async.py The async server: tokens stream out over SSE as they are generated, with the run’s ending as an event of its own.
code/ch20_smoke_client.py The servers’ missing other half: starts one, drives every endpoint, checks what came back, stops it.

Challenge

Both challenges ship a worked, self-checking solution you can run.

🥈 Silver — make a run survive a restart

The Gotcha claimed InMemorySaver dies with its process. Prove it, then fix it.

First, with the in-memory server: POST /ask under thread_id=demo with a Kafka question, so the run finishes rather than stopping at the gate. Confirm GET /run/demo returns the answer, then stop the server, start it again, and GET /run/demo — it is a 404, because the run died with the old process.

Now swap InMemorySaver for a durable checkpointer (SqliteSaver pointed at a file is the smallest step up, per Chapter 8) and repeat the whole ritual. This time the run is still there after the restart, read straight from the file. What you have shown is durability across a restart, on one machine. The Gotcha’s other half — a second replica answering for a run it never executed — needs one property more, a store every replica can reach, which is why the ladder does not stop at a file.

office hours Worked solution: code/answers/ch20_durable_restart.py. It simulates the restart in one process by throwing the saver away and rebuilding the graph over the same file, which is what a new process does anyway — so you can see both halves without two terminals. It needs langgraph-checkpoint-sqlite — pinned in requirements.txt, but only the persistence answers import it, so pip install langgraph-checkpoint-sqlite if you kept your install to the main line.

🥇 Gold — share the checkpointer across replicas

Silver’s run survived a restart, but it lived in a file only one box can open. Production’s other half is scale-out: several replicas behind a load balancer, and a GET /run/{id} that may land on a replica that never handled the POST. Give them a checkpointer they all share.

Install langgraph-checkpoint-redis and point a RedisSaver (or AsyncRedisSaver for the async server) at a Redis instance, in place of InMemorySaver in compile(...). Then stage the Gotcha’s wrong-replica wound and its cure on one machine: start two copies of the server on different ports, both pointed at the same Redis; POST /ask under thread_id=demo to the first; then GET /run/demo from the second. With InMemorySaver the second process returns 404 — it never heard of the run. With the shared Redis saver it returns the answer the first process wrote, because the checkpoint lives in Redis, where both processes read it. Restart both processes and the run is still there.

office hours Worked solution with tests: code/answers/ch20_shared_checkpointer_redis.py. It runs two savers against one Redis in a single process — the second saver standing in for a second replica — so you see the 404-vs-answer difference without two terminals. Needs a Redis reachable at redis://localhost:6379; langgraph-checkpoint-redis needs Redis’s Search and JSON capabilities, which Redis 8 bundles and a plain Redis 7.x lacks — pin the version rather than trust a floating tag: docker run -p 6379:6379 redis:8, or a Redis Stack image if you are on 7.x.


  1. https://fastapi.tiangolo.com; the server underneath is uvicorn, https://uvicorn.dev.↩︎

  2. Server-Sent Events (SSE): a one-way server-to-client stream carried over a single, held-open HTTP response (Content-Type: text/event-stream), with messages framed as data: lines separated by blank lines. Unlike WebSocket it is not bidirectional; the browser’s EventSource reads it, but only over GET — see Section 22.8.↩︎