Sub topic 14
Authentication and abuse protection
This chapter assumes you have the FastAPI service from the earlier chapters: a /predict endpoint, a /predict/batch endpoint, and a /health endpoint. You should also know what an HTTP header and a status code are. Here you will add API-key authentication, rate limiting, and input size limits. You will also see which of these protections belong outside your Python code.
Why a model API needs protection
A prediction endpoint costs compute on every call. An open endpoint lets anyone spend your CPU, fill your logs, or probe the model. Three separate problems need three separate controls:
- Authentication answers "who is calling?" It lets you reject unknown callers.
- Rate limiting answers "how often?" It stops one caller, including a legitimate one with a bug, from using all the capacity.
- Input limits answer "how big?" They stop a single request from being expensive.
Authentication alone does not stop abuse. A valid key in a runaway loop is still a problem.
API keys in FastAPI
An API key is a secret string the client sends in a header, commonly X-API-Key. It is the simplest scheme that works for service-to-service calls. FastAPI's APIKeyHeader reads the header, and a dependency function decides whether to accept it.
Two details matter:
- Constant-time comparison. Comparing with
==can return faster when the first characters differ, which leaks information in theory.secrets.compare_digesttakes the same time regardless. Pass itbytes, because it raisesTypeErroron astrcontaining non-ASCII characters, and a client could use that to cause a 500 error. - Keys come from the environment. Never put keys in source code or in the Docker image. Read them from an environment variable or a secrets manager.
Create security.py:
import os
import secrets
import threading
import time
from collections import defaultdict, deque
from fastapi import Depends, HTTPException, status
from fastapi.security import APIKeyHeader
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def _valid_keys() -> list[bytes]:
raw = os.environ.get("API_KEYS", "")
return [k.strip().encode() for k in raw.split(",") if k.strip()]
def require_api_key(key: str | None = Depends(api_key_header)) -> str:
if key is not None:
candidate = key.encode()
# Check every key so timing does not reveal which one matched.
matches = [secrets.compare_digest(candidate, v) for v in _valid_keys()]
if any(matches):
return key
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or missing API key",
headers={"WWW-Authenticate": "ApiKey"},
)Setting auto_error=False lets you return a consistent 401 yourself. Without it, FastAPI returns 403 for a missing key in some versions, which confuses clients.
If API_KEYS is empty, _valid_keys() returns an empty list and every request is rejected. That is the safe default: a misconfigured deployment fails closed instead of open.
Rate limiting
A rate limiter counts requests per caller in a time window. The version below keeps a sliding window of timestamps for each API key. Limiting by key is fairer than limiting by IP address, because many clients can share one IP behind a proxy.
Add this to security.py:
class RateLimiter:
def __init__(self, limit: int, window_seconds: float):
self.limit = limit
self.window = window_seconds
self.hits: dict[str, deque] = defaultdict(deque)
self.lock = threading.Lock()
def check(self, key: str) -> None:
now = time.monotonic()
with self.lock:
q = self.hits[key]
while q and now - q[0] >= self.window:
q.popleft()
if len(q) >= self.limit:
retry_after = int(self.window - (now - q[0])) + 1
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Rate limit exceeded",
headers={"Retry-After": str(retry_after)},
)
q.append(now)
limiter = RateLimiter(limit=60, window_seconds=60)
def rate_limited(key: str = Depends(require_api_key)) -> str:
limiter.check(key)
return keyThe lock is needed because FastAPI runs plain def endpoints and dependencies in a thread pool. Without it, two threads could both pass the length check and exceed the limit. time.monotonic() is used because wall-clock time can jump backwards.
The 429 response includes a Retry-After header. Well-behaved clients use it to back off.
The in-memory limit does not scale out
This limiter lives in one process. With four Uvicorn workers or four container replicas, each keeps its own counts, so the real limit is four times higher. It also resets when the process restarts.
Wiring protection into the endpoints
Attach the dependency to the routes that cost compute. Leave /health open, because orchestrators and load balancers call it without credentials.
Change the decorators in main.py:
from fastapi import Depends, FastAPI
from pydantic import BaseModel, Field
from security import rate_limited
class BatchRequest(BaseModel):
instances: list[IrisFeatures] = Field(min_length=1, max_length=500)
@app.post(
"/predict",
response_model=Prediction,
dependencies=[Depends(rate_limited)],
)
def predict(features: IrisFeatures):
... # body unchanged
@app.post("/predict/batch", dependencies=[Depends(rate_limited)])
def predict_batch(request: BatchRequest):
... # body unchangeddependencies=[...] runs the dependency without passing its value to the function. Dependencies run before the request body is validated, so an unauthenticated caller gets 401 before the server spends time on validation. FastAPI does read the body first in some configurations, so do not rely on this alone for large uploads.
Limiting input size
The max_length=500 on the batch list is an abuse control, not just a validation rule. Without it, one request with a million rows ties up a worker thread and memory. Pick the limit from measurement: time predict with different batch sizes and choose a cap that keeps worst-case latency inside your budget.
Pydantic bounds on single fields help too. The gt=0 constraint from earlier rejects negatives. Add an upper bound such as lt=1000 to reject absurd values such as 1e308, which can produce unstable output in some models.
Byte-level limits sit below FastAPI. Uvicorn does not cap request body size, so a client can send a very large JSON document before validation begins. Set a limit in the reverse proxy, for example client_max_body_size 64k; in nginx. A body for 500 iris rows is well under that size.
Testing the protections
Test the failure paths, not just the success path. Use monkeypatch to set the environment, so no real key appears in the test file.
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
from main import app
from security import RateLimiter
PAYLOAD = {
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
}
def test_missing_key_is_rejected(monkeypatch):
monkeypatch.setenv("API_KEYS", "test-key")
with TestClient(app) as client:
response = client.post("/predict", json=PAYLOAD)
assert response.status_code == 401
def test_valid_key_is_accepted(monkeypatch):
monkeypatch.setenv("API_KEYS", "test-key")
with TestClient(app) as client:
response = client.post(
"/predict", json=PAYLOAD, headers={"X-API-Key": "test-key"}
)
assert response.status_code == 200
def test_health_needs_no_key():
with TestClient(app) as client:
assert client.get("/health").status_code == 200
def test_limiter_blocks_after_limit():
limiter = RateLimiter(limit=2, window_seconds=60)
limiter.check("k")
limiter.check("k")
with pytest.raises(HTTPException) as exc:
limiter.check("k")
assert exc.value.status_code == 429
assert "Retry-After" in exc.value.headersTesting the limiter directly avoids sending hundreds of requests and keeps the test independent of the global limiter instance's state.
What belongs outside your code
| Concern | In the app | Better placed in |
|---|---|---|
| Transport encryption | Not possible to do safely by hand | TLS terminated at a proxy or load balancer |
| Key storage and rotation | Reads keys from the environment | Secrets manager, with a rotation process |
| Rate limits across replicas | Single-process fallback only | API gateway or Redis-backed limiter |
| Body size limit | Pydantic field limits | Reverse proxy |
| Per-user identity and scopes | Possible, but grows complex | OAuth 2 or JWT through an identity provider |
API keys identify a client application. If you need to know which human user made a call, or to grant different permissions per user, use OAuth 2 or signed tokens (JWTs) from an identity provider. FastAPI has built-in helpers for both, but the provider is the part you should not write yourself.
Common mistakes
- Sending keys over plain HTTP. Anyone on the network path can read the header. Always use HTTPS in production.
- Logging the key. Request logging that records all headers writes secrets to disk. Log a short key identifier instead, such as a key name or the last four characters.
- One shared key for all clients. You cannot revoke one client without breaking the rest. Issue one key per client.
- Leaving
/docspublic. FastAPI serves interactive docs by default. Disable them withFastAPI(docs_url=None, redoc_url=None)if the API is internal and you do not want the schema exposed. - Detailed error messages. Do not tell the caller whether the key was missing, malformed, or revoked. A single generic 401 gives an attacker less to work with.
Exercise
Your service runs as three container replicas behind a load balancer, each with the in-memory RateLimiter set to 60 requests per minute per key. A single client sends requests as fast as it can. Roughly how many requests per minute can it get through, and what would you change to enforce a true 60 per minute?
Show answer
Up to about 180 per minute, because the load balancer spreads requests across replicas and each replica counts only its own traffic. To enforce 60 in total, move the counting to a shared layer: an API gateway or reverse proxy that sees all traffic, or a limiter backed by a shared store such as Redis that all replicas read and update.
Exercise
Why should the API key comparison use secrets.compare_digest on bytes instead of the == operator on strings?
Show answer
The == operator can stop at the first differing character, so response time can leak how much of a guessed key was correct. comparedigest takes the same time regardless of where the values differ. Using bytes avoids a TypeError that comparedigest raises for str values with non-ASCII characters, which would otherwise let a client trigger a 500 error.