Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. AI System Design

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.

Chaand Sheikh

·27 November 2026AI System Design

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 def running in the thread pool.

One request, end to end

One request through docs-answer POST/api/ask AskRequestschema check ask()routers/ask.py rag.answer()services/rag.py retriever3 best chunks modelwrites answer 422, no model call back: AskResponse (answer, sources, model)
The router speaks HTTP. The RAG code doesn't know HTTP exists.

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

async def + blocking call vs plain def async def + blocking call: one after another user 1user 2user 3user 4user 5 all 5 in 3.02 s plain def (thread pool): side by side all 5 in 0.61 s 0 s 3 s
Each answer takes 600 ms. Only the route declaration changed.

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 def because it sounds faster. With a blocking SDK call it's the slowest choice you have.

Quick recap

ProblemFastAPI featureIn docs-answer
Bad input reaches the modelPydantic schemaAskRequest: 422 for "hi" or top_k 50
Loading things on every requestLifespanIndex and model on app.state
Shared objects hard to testDependsget_retriever, get_model
One slow call blocks everyonePlain def in the thread pool5 users: 0.61 s instead of 3.02 s

Try it yourself

  1. Start the service with python demo.py web and send a question from the /docs page.
  2. Send a top_k of 9 and read the error.
  3. Make the stand-in slower with STANDIN_DELAY_MS and run the load test again. Watch the gap grow.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 77 of 89

Previous
A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
Next post
Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket

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.

On this page

  • A restaurant counter
  • One request, end to end
  • The order form: schemas.py
  • Set up the kitchen once: the lifespan
  • Tools on the wall: Depends
  • The RAG part knows nothing about HTTP
  • The first attempt: async def
  • Five users at once
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.