FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
Turn a help-centre RAG pipeline into a FastAPI service: a schema that answers bad input with a 422 before the model runs, a lifespan that loads the index once, Depends for shared objects, and the def vs async def mistake that makes five users wait 3.02 s instead of 0.61 s.
What you will learn
- Reject bad input with a 422 before any model call, using a Pydantic request schema
- Load the search index and the model once in the lifespan and share them on app.state
- Hand shared objects to routes with Depends, so tests can swap them
- Choose plain def or async def for a route that calls a blocking model client
Before you start
- FastAPI Request and Response Models with Pydantic
- The RAG Pipeline Explained
A notebook can answer a question from your documents. But another app can't call a notebook, nothing says what a caller is allowed to send, and if five people ask at once, they wait in a queue. In this article we turn a small RAG pipeline into a proper web service with FastAPI, and we measure the one mistake almost everybody makes once.
The project is docs-answer, a service that answers questions from a shop's help centre. It runs with a stand-in test model, so you need no key. Put a key in .env and the same code calls a real model.
A restaurant counter
Think about a restaurant. At the counter there's an order form, so a bad order is turned away before it reaches the kitchen. The kitchen is set up before the doors open, not once per order. The knives and pans hang on the wall, and each cook takes the ones they need. And the cooks work side by side, so one slow dish doesn't stop the others.
Those are the four FastAPI features in this article:
- The order form is the request schema.
- Setting up the kitchen is the lifespan.
- Tools on the wall are dependencies with
Depends. - Cooks side by side is a plain
defrunning in the thread pool.
One request, end to end
A client posts a question to /api/ask. Before any of our code runs, FastAPI checks the body against AskRequest. If it doesn't fit, the client gets a 422 and the model is never called. If it fits, FastAPI calls ask, which hands the work to rag.answer. The retriever finds the three best chunks of the help centre, the model writes the answer from them, and an AskResponse comes back.
For "How long does a refund take?" the run returned in 0.61 s with model stand-in. The first source was returns-and-refunds.md - When you get your refund with a score of 3.591, which is the right page. (The answer text is a test model reply.)
The order form: schemas.py
"""The shapes that go in and out of the API. FastAPI checks every request against them."""
from pydantic import BaseModel, Field
class AskRequest(BaseModel):
question: str = Field(min_length=3, max_length=500, examples=["How long does a refund take?"])
top_k: int = Field(default=3, ge=1, le=8)
class Source(BaseModel):
source: str # file name, the citation
heading: str
score: float
class AskResponse(BaseModel):
answer: str
sources: list[Source]
model: str # "stand-in" or the real model name
The question must be 3 to 500 characters. A long essay pasted in here would cost tokens, so we stop it at the door. top_k, the number of chunks to retrieve, must be between 1 and 8. AskResponse is what every client gets back: the answer, the sources and which model answered. There isn't a single if statement for any of this; FastAPI does the checking. If you want the full tour of request and response models, see FastAPI Request and Response Models with Pydantic.
Here are three bad requests:
python demo.py validate
=== validate: Bad requests get a 422 ===
[stand-in test model, help-centre docs]
{"question": "hi"} -> 422 ['question: String should have at least 3 characters']
{"question": "Where do you ship?", "top_k": 50} -> 422 ['top_k: Input should be less than or equal to 8']
{} -> 422 ['question: Field required']
Each error names the field that's wrong, and none of these requests reached the model, so none of them cost anything.
Set up the kitchen once: the lifespan
"""docs-answer: a small RAG service over a shop's help centre. Create the app, load the docs once, add the routers."""
from contextlib import asynccontextmanager
from fastapi import FastAPI
from .config import settings
from .routers import ask, blocking, health
from .services.docs import load_folder
from .services.llm import get_model
from .services.retriever import KeywordRetriever
@asynccontextmanager
async def lifespan(app: FastAPI):
# Runs once at start-up, not on every request: read the docs, build the index, pick the model.
app.state.retriever = KeywordRetriever(load_folder(settings.docs_dir))
app.state.model = get_model()
yield
app = FastAPI(title="docs-answer", version="0.1.0", lifespan=lifespan)
app.include_router(health.router)
app.include_router(ask.router)
app.include_router(blocking.router)
The lifespan runs once, when the server starts. It reads the help-centre files, cuts them into chunks and builds the search index, then picks the model (with no key, that's the stand-in). Both sit on app.state, and every request shares them, so nothing is loaded twice. The same idea for a classic ML model is in A Production FastAPI for an ML Model.
Tools on the wall: Depends
# routers/deps.py
from fastapi import Request
from ..services.llm import Model
from ..services.retriever import KeywordRetriever
def get_retriever(request: Request) -> KeywordRetriever:
return request.app.state.retriever
def get_model(request: Request) -> Model:
return request.app.state.model
# routers/ask.py
from typing import Annotated
from fastapi import APIRouter, Depends
from ..schemas import AskRequest, AskResponse
from ..services import rag
from ..services.llm import Model
from ..services.retriever import KeywordRetriever
from .deps import get_model, get_retriever
router = APIRouter(prefix="/api", tags=["ask"])
Retriever = Annotated[KeywordRetriever, Depends(get_retriever)]
LLM = Annotated[Model, Depends(get_model)]
@router.post("/ask", response_model=AskResponse)
def ask(body: AskRequest, retriever: Retriever, model: LLM) -> AskResponse:
"""A plain def: FastAPI runs it in a worker thread, so a slow model call does not block other requests."""
return rag.answer(body.question, retriever, model, body.top_k)
Retriever means "whatever get_retriever returns", and get_retriever just returns the one the lifespan built. The model works the same way. The route itself is one line. In a test you can swap these dependencies for fakes without touching the router.
Notice the route is a plain def, not async def. That's on purpose, and the next sections show why.
The RAG part knows nothing about HTTP
"""Retrieve, build the prompt, ask the model. The routers call answer(); nothing here knows about HTTP."""
from ..schemas import AskResponse, Source
from .llm import Model
from .retriever import Hit, KeywordRetriever
PROMPT = """Answer the question using only the context. If the context does not cover it, say so.
Keep it to two sentences.
CONTEXT:
{context}
QUESTION: {question}"""
def build_prompt(question: str, hits: list[Hit]) -> str:
context = "\n".join(f"[{h.chunk.source} - {h.chunk.heading}] {h.chunk.text}" for h in hits)
return PROMPT.format(context=context, question=question)
def answer(question: str, retriever: KeywordRetriever, model: Model, k: int = 3) -> AskResponse:
hits = retriever.search(question, k)
reply = model.complete(build_prompt(question, hits))
sources = [Source(source=h.chunk.source, heading=h.chunk.heading, score=h.score) for h in hits]
return AskResponse(answer=reply, sources=sources, model=model.name)
Each chunk goes into the prompt in square brackets with its file name and heading, so the answer can point back to its source. This file doesn't care whether a web request, a test or a script calls it. If the stages are new to you, read The RAG Pipeline Explained.
Which model answers is decided in one place, services/llm.py. Model is a Protocol: anything with a name and a complete method counts. The real one uses the OpenAI client with a 30 second timeout and two retries. With no key you get the stand-in, which answers from the best chunk and sleeps 600 ms first, like a real model that takes time to answer. That delay is what makes the next part visible.
The first attempt: async def
"""The first attempt, kept on purpose so you can see the problem (python demo.py load).
async def + a blocking model call = the whole server waits. While one request sits in model.complete(),
the event loop cannot start any other request, so five users are served one after another."""
from fastapi import APIRouter
from ..schemas import AskRequest, AskResponse
from ..services import rag
from .ask import LLM, Retriever
router = APIRouter(prefix="/api", tags=["first attempt"])
@router.post("/ask-blocking", response_model=AskResponse)
async def ask_blocking(body: AskRequest, retriever: Retriever, model: LLM) -> AskResponse:
return rag.answer(body.question, retriever, model, body.top_k)
Same work, but declared async def. It looks faster. The problem is inside: rag.answer calls the model, and that call blocks. It doesn't await anything. FastAPI runs every async def route on one event loop, so while this request sits in the model call, the loop is stuck and no other request can even start.
Five users at once
demo.py load sends five questions at the same moment to each endpoint:
python demo.py load
python demo.py tests
=== load: 5 users at once: blocking vs thread pool ===
[stand-in test model, help-centre docs]
each answer takes 600 ms; 5 users ask at the same moment
async def + blocking call /api/ask-blocking all 5 answered in 3.02s
plain def (thread pool) /api/ask all 5 answered in 0.61s
...... [100%]
6 passed in 1.58s
With async def and the blocking call, five answers take 3.02 s: five answers, one after another. With the plain def, all five are done in 0.61 s, the time of one answer, because FastAPI ran each one in its thread pool. The six offline tests pass, including one that checks exactly this.
The rule: if your model client blocks, use a plain def. If you use an async client and await it, async def is fine. Never mix the two: a blocking call inside async def.
Common mistakes
- Checking input by hand inside the route. Put the limits on the schema, and a bad request is a 422 before it costs anything.
- Loading the index or model inside the route. Every request pays the start-up cost again. Load once in the lifespan.
- Importing a global model straight into routes. You can't swap it in a test. Hand it over with
Depends. - Writing
async defbecause it sounds faster. With a blocking SDK call it's the slowest choice you have.
Quick recap
| Problem | FastAPI feature | In docs-answer |
|---|---|---|
| Bad input reaches the model | Pydantic schema | AskRequest: 422 for "hi" or top_k 50 |
| Loading things on every request | Lifespan | Index and model on app.state |
| Shared objects hard to test | Depends | get_retriever, get_model |
| One slow call blocks everyone | Plain def in the thread pool | 5 users: 0.61 s instead of 3.02 s |
Try it yourself
- Start the service with
python demo.py weband send a question from the/docspage. - Send a
top_kof 9 and read the error. - Make the stand-in slower with
STANDIN_DELAY_MSand run the load test again. Watch the gap grow.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.