Serving Models with FastAPI and BentoML

Expose models as reliable prediction APIs or batch jobs, with input validation, batching, health checks and sensible latency budgets.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Docker for ML, Experiment Tracking with MLflow and Weights and Biases

A model creates value only when something can call it. The main serving patterns are:

  • Online (real-time): an HTTP or gRPC API answers each request in milliseconds.
  • Batch: score millions of rows on a schedule and write results to a table.
  • Streaming: consume events from a queue such as Kafka and emit predictions.
  • Edge: run on a phone or browser (TFLite, ONNX Runtime, Core ML).

Many teams start with batch, since it is simpler and cheaper; move to online only when freshness requires it.

A FastAPI service

  • Load the model once at startup, not per request.
  • Define request and response schemas with Pydantic so bad inputs fail with clear errors.
  • Reuse the exact preprocessing pipeline from training (a saved scikit-learn pipeline or tokenizer).
  • Add /health and /ready endpoints, structured logging and a model version in every response.

Dedicated serving frameworks

  • BentoML packages models with their code into deployable services with adaptive batching.
  • NVIDIA Triton, TorchServe, Ray Serve and vLLM (for LLMs) handle GPU batching and concurrency at scale.
  • Gradio and Streamlit are for demos, not production traffic.

Performance and safety

Measure p50 and p99 latency and throughput with a load test. Batch requests on GPUs, cache repeated inputs, and set timeouts. Roll out new versions with shadow, canary or A/B deployments and keep a fast rollback path.

Good enough to move on when you can serve a model behind a validated API, load test it, and deploy a new version without downtime.

Key concepts

  • Online, batch, streaming and edge
  • FastAPI prediction endpoints
  • Pydantic input validation
  • Health checks and versioning
  • BentoML services
  • Triton, TorchServe and vLLM
  • Load testing and latency
  • Canary and shadow deployments

Mini project

Serve your registered model with FastAPI in Docker, add Pydantic schemas, health checks and a version header, load test it with Locust to find p99 latency, then repackage it with BentoML and compare throughput.

Check yourself

Why should the model load at application startup rather than inside the request handler, and when is batch scoring a better choice than a real-time API?

Free resources