Lesson 2 of 9
Building High-Throughput ML REST APIs with FastAPI, Pydantic & Async Workers
Serving machine learning models in production requires high-throughput, low-latency microservices with automatic request validation. FastAPI is the modern standard for ML serving: built on Starlette and Pydantic, it provides async I/O concurrency, strict JSON schema validation, automatic OpenAPI / Swagger documentation, and sub-10ms response times when paired with Uvicorn and Gunicorn worker pools.
Production FastAPI Inference Microservice with Lifespan Loading
import numpy as np
import pandas as pd
from pydantic import BaseModel, Field
from typing import List
# 1. PYDANTIC REQUEST VALIDATION SCHEMA (Enforces strict input typing)
class LoanApplicantPayload(BaseModel):
annual_income: float = Field(..., gt=0, description="Annual income in USD")
credit_score: int = Field(..., ge=300, le=850, description="FICO score (300-850)")
revolving_debt: float = Field(..., ge=0, description="Outstanding credit balance")
home_ownership: str = Field(..., pattern="^(RENT|MORTGAGE|OWN)$")
class PredictionResponse(BaseModel):
risk_score: float
decision: str
model_version: str
# 2. FASTAPI MICROSERVICE IMPLEMENTATION (Simulated production pattern)
class ProductionMLService:
def __init__(self):
# Model is loaded ONCE into memory during application lifespan startup
self.model_version = "v2.1.0"
self.warm = True
print(f"[FastAPI Lifespan] Model {self.model_version} loaded into RAM successfully.")
def predict(self, applicant: LoanApplicantPayload) -> PredictionResponse:
# Vectorized feature conversion
debt_to_income = applicant.revolving_debt / applicant.annual_income
# Simulated model inference logic
risk_logit = 0.005 * debt_to_income - 0.008 * (applicant.credit_score - 600)
risk_prob = float(1.0 / (1.0 + np.exp(-risk_logit)))
decision = "REJECT" if risk_prob > 0.45 else "APPROVE"
return PredictionResponse(
risk_score=round(risk_prob, 4),
decision=decision,
model_version=self.model_version
)
# Execute test API inference
service = ProductionMLService()
applicant_request = LoanApplicantPayload(
annual_income=85000.0,
credit_score=720,
revolving_debt=12500.0,
home_ownership="MORTGAGE"
)
response = service.predict(applicant_request)
print("=== FASTAPI INFERENCE RESPONSE PAYLOAD ===")
print(response.model_dump_json(indent=2))Pro Tip: Use FastAPI `lifespan` Context Managers
Never load your machine learning model inside the route endpoint function (e.g. `@app.post('/predict')`); doing so re-loads the model from disk on every single HTTP request, destroying throughput. Use FastAPI's `@asynccontextmanager` `lifespan` handler to load model artifacts once during server startup.
MlFastAPIServing Visual Representation
Hands-On Challenge: Build a Batch Prediction Endpoint
Implement a `/predict-batch` endpoint that accepts a list of up to 1,000 applicant payloads `List[LoanApplicantPayload]`, converts them into a single vectorized 2D NumPy matrix, and executes batch inference in a single call.
Quick Quiz & Key Concept Checks
Common Pitfall: Blocking the Async Event Loop with Heavy CPU Inference
Running a heavy, long CPU model inference call directly inside an `async def` endpoint blocks the single-threaded asyncio event loop, freezing all other incoming requests. For CPU-heavy models, either use standard `def` (which FastAPI runs in an external threadpool) or offload inference to Celery/Redis.