Building Prediction APIs with FastAPI
Expose model predictions behind fast, typed HTTP APIs with FastAPI.
In plain words
A prediction API is a web address that takes some information, runs your model on it and sends back the answer, so any app can ask the model for a prediction.
Think of it like…
A bank teller window for a prediction expert. Customers (apps) hand over a standard form (validated JSON); the teller (the endpoint) consults the expert (the loaded model) who has already read the rulebook, and returns a stamped answer with the rulebook edition; more windows (workers) are opened when the queue grows.
Where you’ve seen it
The churn service defines class CustomerFeatures(BaseModel) (validated fields) and class Prediction(BaseModel) with churn_probability: float, model_version: str and request_id: str. A lifespan handler loads churn-v12.joblib once (about 2 seconds for 480 MB) into app.state.model and marks readiness only afterwards, so Kubernetes doesn't route traffic to a pod that is still loading. The endpoint @app.post("/v1/predict") is declared def (not async def), so FastAPI runs it in a thread pool and the event loop stays free to accept requests. Per request the model needs 8 ms of CPU and framework overhead adds about 4 ms, so p50 latency is about 12 ms. Because inference is CPU-bound and Python threads share a GIL, scaling uses processes: one Uvicorn worker sustains at most 1 / 0.008 = 125 requests a second. To serve 400 requests a second at 70% target utilisation, the service needs 400 × 0.008 = 3.2 busy cores, 3.2 / 0.7 ≈ 4.6, so 5 workers (or 5 pods with 1 worker each, which scales more cleanly under an autoscaler). A POST /v1/predict/batch endpoint accepts up to 100 rows and scores them vectorised in one call: 50 rows scored one at a time would take about 400 ms, while one vectorised call takes roughly 35 ms (illustrative; measure your model). The API includes a request_id, logs the model version, latency and a hash of the input but not raw personal data, returns 422 for invalid inputs through the validation models and 503 while the model is not loaded, and exposes /health (liveness) and /ready (readiness). Tests include a golden-sample prediction, a schema contract test and a load test (for instance with Locust) that confirms p95 stays within the 50 ms budget at 400 requests a second.
Words you’ll hear
- ASGI / Uvicorn
- The async server interface and a common server that runs FastAPI apps.
- Lifespan startup
- Code that runs once when the app starts, used to load the model.
- Readiness probe
- An endpoint that reports whether the service can handle traffic yet.
- Worker process
- A separate server process; more workers use more CPU cores.
Visual diagram
Theory & deep dive
Structure of a good prediction endpoint
Define request and response models with Pydantic so FastAPI validates and documents them: features with types and constraints in, a Prediction object out containing the score, the model version and a request ID. Load the model in a lifespan (startup) handler into app.state, not at module import time in a way that hides failures and not inside the endpoint, and mark the service ready only when loading succeeded. Use versioned routes (/v1/predict) so a changed schema becomes /v2, a batch endpoint for many rows (vectorised scoring is much faster than looping), and separate health (/health: process alive) and readiness (/ready: model loaded) checks.
Return useful errors: 422 for validation failures with field details, 503 when the model isn't ready, 500 with a request ID for unexpected faults. Add logging of request ID, model version, latency and a hash or summary of inputs (not raw sensitive values), and expose metrics (request count, latency histogram, error rate, prediction distribution) so monitoring and drift detection have data. Add authentication (API keys or tokens) and rate limits for anything exposed beyond a trusted network, and keep configuration (model path, thresholds) in environment variables rather than code.
{"churn_probability": 0.372, "model_version": "churn-v12", "request_id": "req_7f3a", "threshold": 0.35, "decision": "contact"}. The version and request ID let support trace any score back to a model and a log line.
Concurrency, latency and capacity
FastAPI is async, but model inference is CPU-bound: if you call it inside an async def endpoint it blocks the event loop and every other request waits. Declare CPU-bound endpoints as plain def so they run in a thread pool, and remember that Python threads share the GIL, so NumPy-heavy code scales with processes, not threads. Capacity arithmetic: with 8 ms of CPU per prediction, one worker sustains 1 / 0.008 = 125 requests a second. To serve 400 requests a second at a 70% utilisation target you need 400 × 0.008 = 3.2 busy cores, so 3.2 / 0.7 ≈ 4.6, rounded up to 5 workers. Running one worker per container and letting an autoscaler add pods is simpler to reason about than many workers per container.
Latency is the model time plus overhead (parsing, validation, serialisation): 8 ms plus about 4 ms gives roughly 12 ms at p50, and queueing adds to the tail when utilisation is high, so test p95 and p99 under load (Locust, k6) rather than relying on single-request timing. Batching helps throughput: scoring 50 rows in one vectorised call (about 35 ms in the illustration) is far cheaper than 50 separate calls (400 ms). For heavy models consider ONNX Runtime, quantisation or a dedicated model server, and for GPU models micro-batching. Set timeouts, bounded request sizes and sensible worker limits, plan for cold starts (2 seconds of model load affects autoscaling) and keep a warm minimum number of replicas.
Target 400 req/s. CPU per request 8 ms → 3.2 cores busy. Utilisation target 70% → 4.6 → 5 single-worker pods. p50 ≈ 12 ms; at 70% utilisation queueing pushes p95 to roughly 25 ms, within a 50 ms budget. Load-test to confirm.
How it works, step by step
Step 1 of 41. Define the contract
Write request and response models with constraints, a versioned route and an error scheme.
- Document
- OpenAPI /docs
When to use it & trade-offs
What it is
A prediction API wraps a trained model behind an HTTP endpoint so applications can request scores without importing your code. FastAPI is a popular Python framework for this: you declare typed request and response models with Pydantic, FastAPI validates inputs, generates interactive OpenAPI docs at /docs and runs on an ASGI server such as Uvicorn. A sound design loads the model once at startup (not per request), exposes POST /v1/predict (and a batch variant), a GET /health endpoint, returns the model version with each prediction and treats CPU-bound inference carefully: because a model call blocks the thread, it belongs in a plain def endpoint (run in a thread pool) or a process pool, not inside an async def that would stall the event loop.
Why it matters: A model that only exists in a notebook creates no value. The API is where data science meets reliability: latency budgets, concurrency, versioning, validation and monitoring decide whether predictions are usable. Common mistakes are reloading a 480 MB model on every call, blocking the event loop with CPU work, skipping input validation and returning bare numbers with no version, which makes production issues hard to debug and models impossible to roll back.
When to reach for it
- Real-time scoring for web and mobile applications
- Internal services that call a model from several systems
- A thin wrapper around an ONNX or scikit-learn artefact
When to avoid or be careful
- Loading the model inside the request handler
- CPU-heavy work inside async def endpoints
- Responses with no model version or request ID
Serving options
Strengths: Flexible; typed; easy to test.
Watch out: You manage scaling and performance.
Strengths: Batching and optimisations built in.
Watch out: More infrastructure to learn.
Strengths: Autoscaling, logging, deployment tooling.
Watch out: Platform lock-in and cost.
Interview signals & numbers to know
When this topic comes up
- “How would you serve this model?”
- Why load the model at startup
- async versus def for CPU-bound inference
- How many workers do you need?
- Health versus readiness
Benchmarks & rules of thumb
- 125 req/s
- one worker with 8 ms CPU per request
- 3.2 → 5 workers
- 400 req/s at 8 ms, planned for 70% utilisation
- 400 ms vs 35 ms
- 50 single-row calls versus one vectorised batch (illustrative)
Common mistakes & follow-ups
Common interview mistakes
- Putting model inference in an async function and freezing the server.
- Ignoring readiness, so traffic hits pods still loading the model.
- Not load-testing tail latency.
Likely interviewer follow-ups
- How would you roll out a new model version behind this API?
- How do you protect the API from abuse?
- How would you reduce latency for a heavy model?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Building Prediction APIs with FastAPI with data science interview Q&A and hands-on practice.