Sub topic 14
Authentication and abuse protection
This chapter assumes you have the FastAPI service from the earlier chapters, with /predict and /predict/batch endpoints, and that you know basic HTTP headers and status codes. It uses Pydantic v2.
Why an open prediction endpoint is a problem
Every prediction costs CPU time. An endpoint anyone can reach lets strangers use your compute, scrape your model's behavior by sending many inputs, or slow the service for real users. You need to answer two questions: who is calling, and how much may they call?
Layers of protection
Each layer rejects bad traffic before it reaches the model.
Authenticating with an API key
An API key is a secret string the client sends in a header. The service compares it to the expected value and returns 401 if it is missing or wrong. Read the key from an environment variable so it never appears in source code.
import os
import secrets
from fastapi import Depends, HTTPException, Security
from fastapi.security import APIKeyHeader
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def require_api_key(key: str | None = Security(api_key_header)) -> None:
expected = os.environ.get("API_KEY", "")
if not expected or key is None:
raise HTTPException(status_code=401, detail="Missing or invalid API key")
if not secrets.compare_digest(key.encode(), expected.encode()):
raise HTTPException(status_code=401, detail="Missing or invalid API key")Apply it to the endpoint with dependencies. The function runs before the handler, so unauthenticated requests never reach the model.
@app.post(
"/predict",
response_model=Prediction,
dependencies=[Depends(require_api_key)],
)
def predict(features: IrisFeatures):
...Leave /health unprotected so orchestrators can probe it without a secret.
Two details matter here:
secrets.compare_digesttakes the same time whether the strings differ at the first character or the last. A plain==can leak information through timing.- If
API_KEYis unset, the code rejects every request. Failing closed is safer than accidentally running open.
Start the service with API_KEY=change-me uvicorn main:app, and send the header with curl -H "X-API-Key: change-me".
Limiting what one request can cost
Authentication does not stop a legitimate client from sending a huge request. Bound the work per request in the schema:
from pydantic import BaseModel, Field
class BatchRequest(BaseModel):
instances: list[IrisFeatures] = Field(min_length=1, max_length=100)A batch of 101 rows now fails validation with status 422 before any prediction runs. Pick the maximum from your latency budget, not from a guess.
Rate limiting and transport security
A rate limit caps requests per client per time window and returns 429 when exceeded. Do this at a reverse proxy or API gateway such as nginx, Envoy, or a cloud gateway. A per-process counter inside the app is wrong once you run several replicas, because each replica counts separately. The gateway can also set a maximum request body size and request timeouts.
API keys travel in plain text headers, so serve the API over HTTPS. Terminate TLS at the gateway or load balancer.
Common errors
- Hard-coding the key in the source or the Docker image. Pass it at run time with
docker run -e API_KEY=...or a secrets manager. - Logging request headers, which writes keys into your logs.
- Using one shared key for every client. You cannot revoke one client without breaking the rest, so issue one key per client.
- Treating a key as full security. For user-level permissions, use OAuth2 or JWT tokens instead.
Exercise
A client sends a valid API key but posts a batch of 5,000 rows. Which layer should reject it, which status code does the client see, and why is the API key check not enough?
Show answer
The input validation layer rejects it, because the max_length=100 limit on instances fails, and the client sees status 422. The API key check only proves who the caller is. It does not limit how much work one request can cause.