A trained model in a notebook helps nobody else. Put it behind an API, a web address other programs can send text to and get predictions back from, and an app, a website or a colleague’s script can use it. FastAPI makes that a dozen lines of Python. Making it fast when many people use it at once takes three habits, and here you’ll see why from real load tests of one small model served five ways. Load the model once, keep the server free to answer, and measure the slowest requests at the load you expect.
A model behind a web address#
The model here sorts messages to a bank’s support team into eight topics, such as a lost card or a failed top-up: it turns a message into numbers with a small embedding model, all-MiniLM-L6-v2, and a simple classifier picks the topic. The API has two addresses. POST /predict takes {"text": "my card still hasn’t come"} and answers {"intent": "card_arrival", "confidence": 0.44}, its best guess and how sure it is. GET /health just answers that the server is alive. Load balancers and container platforms typically call an address like it every few seconds, and stop sending traffic to, or restart, a server that stops answering.
We served it five ways, on three cores of this site’s build server, and hit it with 1, 4, 16 and 64 users: programs that each send a request, wait for the answer and send the next, for 8 seconds, while a probe calls /health every 200 ms. The five ways:
- Load the model in every request. The mistake that works fine in testing.
- Load once,
async defendpoint. The model is loaded at start-up, and the endpoint is declaredasync, which looks faster. - Load once, plain
defendpoint. FastAPI runs a plain function in a pool of threads, so the server can keep answering other requests while the model works. - Batch requests together. Requests that arrive within 5 ms of each other go through the model together, up to 32 at a time.
- Three worker processes. Three copies of the server, each with its own model, behind one address:
uvicorn main:app --workers 3.
Load once, and don’t block#
Loading inside the request is the easiest mistake to see. Even this small model, read from a disk that had just read it, took about a tenth of a second to load: with one user, half of all requests took 131 ms, against 17 ms when the model was loaded once at start-up. Larger models take seconds. FastAPI’s answer is the lifespan function: code that runs once, before the server takes its first request.
The second mistake is subtler. FastAPI runs an async def endpoint directly on its event loop, the single line of work that receives every request and sends every answer. That’s ideal for code that spends its time waiting on other services. A model doesn’t wait; it computes. While it computes, the event loop does nothing else.
Predict first
The model takes about 15 ms per message. With the async def endpoint and 16 users, how long does the slowest /health check take, a request that does no work at all?
Load once, async def endpoint
The first 8 of 16 users are shown.
Requests a second
116
Half answered within
133 ms
95% answered within
167 ms
Slowest /health check
452 ms
Load once, async def endpoint, 16 users: 948 requests in 8.15 seconds, 116.3 a second. Half were answered within 133 ms, 95% within 167 ms. The slowest health check took 452 ms.
With async def, requests are answered strictly one after another, and the health checks, red, sit in the same line. With a plain def, the work moves to other threads and health checks stay fast: 54 ms at worst with 16 users. FastAPI’s documentation gives the rule of thumb: if you don’t know, use a plain def. Notice the price, though: here the threads got in each other’s way, so def answered fewer requests a second than async def did, 40 against 116 at 16 users. Keeping the server responsive and getting the most out of the processor are different jobs. Never run a model inside async def: the whole server waits while it computes.
Measure under load#
One user tells you how fast the model is. Many users tell you how the server copes, and the number to watch is the slowest answers, not the average: the 95th percentile, the time within which 95% of requests were answered. Once requests arrive faster than the server can answer them, they queue, and every extra user adds to every user’s wait.
Predict first
At 16 users, which of the five ways answers the most requests per second?
| Served as | Users within budget | Requests a second there |
|---|---|---|
| Load the model in every request | 1 | 7 |
| Load once, async def endpoint | 16 | 116 |
| Load once, def endpoint | 16 | 40 |
| Load once, batch requests together | 16 | 182 |
| Load once, def, 3 worker processes | 16 | 154 |
With a budget of 500 ms for 95% of answers: Load per request 1, async def 16, def 16, Batched 16, 3 workers 16 of the users tested (up to 64).
With a budget of 250 ms, batching, three workers and even async def cope with 16 users; plain def only with 4. At 64 users every setup is overloaded and requests mostly wait in line: 95% answered within 0.7 to 1.8 seconds. And the ranking changes. Batching, the best at 16 users, did worse than three workers at 64 in our test, with some requests waiting over 3 seconds. That’s the real lesson of load testing: a setup that wins at one load can lose at another, so test at the load you expect, and watch the slowest requests. Test at your real traffic and watch the 95th percentile: averages hide the users who wait.
In code#
A minimal API with the habits above: the model loaded once in the lifespan, a plain def endpoint, a health check, and input checked by Pydantic before the model sees it. Here with a sentiment model from Hugging Face, free and local (pip install fastapi uvicorn transformers torch):
# main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from pydantic import BaseModel, Field
from transformers import pipeline
models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
# runs once, before the first request: load anything slow here
models["sentiment"] = pipeline("sentiment-analysis", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
yield
models.clear()
app = FastAPI(lifespan=lifespan)
class Review(BaseModel):
text: str = Field(min_length=1, max_length=2000)
@app.get("/health")
def health():
return {"ok": True}
@app.post("/predict")
def predict(review: Review):
# a plain def: FastAPI runs it in a thread pool, so the server can still answer other requests meanwhile
result = models["sentiment"](review.text)[0]
return {"label": result["label"], "score": round(result["score"], 3)}
# try_it.py
from fastapi.testclient import TestClient
from main import app
with TestClient(app) as client: # "with" runs the lifespan, so the model loads
print(client.get("/health").json())
print(client.post("/predict", json={"text": "Arrived quickly and works perfectly."}).json())
print(client.post("/predict", json={"text": ""}).status_code) # fails validation
# {'ok': True}
# {'label': 'POSITIVE', 'score': 1.0}
# 422Run it with uvicorn main:app, add --workers 3 for three processes, and put it in a container when it’s time to deploy. Before you do, load-test it with your own messages at the traffic you expect.
What to remember
- Load the model once, in FastAPI’s lifespan, not in the request: here that was 17 ms a request against 131.
- Never run model code inside async def: it blocks the event loop, and even health checks wait (up to 1.9 s at 64 users here). Use a plain def, worker processes or batching.
- Load-test at the traffic you expect and watch the 95th percentile; the best setup at one load can be the worst at another.