🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Model Serving: Batching, Latency, and Fallbacks

MLOpsModel Deployment⭐ Premium

Model Serving: Batching, Latency, and Fallbacks

Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe

Prerequisites

  • !Exposing an HTTP endpoint in Python
  • !How p50 and p99 latency differ
  • !Container basics from the deployment lessons

What You'll Learn

  • 1Match a serving mode to the product's latency and cost budget
  • 2Write an inference endpoint with health, ready, and predict routes
  • 3Implement dynamic batching to raise GPU utilization safely
  • 4Design fallback behaviour for model timeouts and bad inputs

Latency, throughput, and cost are a triangle

Every serving decision is a negotiation between three numbers that refuse to improve together. Per-request latency improves when you add replicas and shrink batches. Throughput improves when you pack more requests into one forward pass. Cost improves when hardware runs near saturation. Push any one and the others move against you, which is why "make it faster" is never a complete requirement — you must say which of the three is the binding constraint and which is allowed to suffer. A fraud check that must answer in 20 milliseconds has a different architecture from a nightly document enrichment job that may take four seconds but must process three million rows for a dollar.

Start from the product's tolerance rather than the model's convenience. Interactive predictions bound p99, not the average, because the tail is what users feel. Batch jobs bound cost per thousand rows. Streaming workloads bound end-to-end freshness. Once the binding constraint is named, most architecture choices resolve quickly: if p99 under 50 milliseconds is mandatory, cross-network model calls and unbounded batching are off the table before you benchmark anything.

Three serving modes

The modes differ in when work happens relative to the request, and each carries an operational signature you inherit permanently. Batch inference runs on a schedule over stored data, is trivial to retry and audit, and cannot serve an interactive product. Real-time inference computes on demand and is the only mode that fits user-facing latency, at the cost of autoscaling, tail latency, and on-call ownership. Streaming inference sits between: events arrive continuously, predictions are emitted with bounded delay, and the system needs exactly-once semantics that batch and request/response both avoid.

ModeLatencyCost profileFailure handlingTypical use
BatchMinutes to hoursLowest per rowRerun the partitionScoring, embeddings, reports
StreamingSecondsMedium, always-onReplay from offsetFraud, anomaly, live ranking
Real timeMillisecondsHighest, sized to peakRetry, timeout, fallbackSearch, recommendations, chat

A common mistake is choosing real time because it seems most capable. Real time inherits peak-provisioned capacity, dependency on upstream availability, and a pager. If the product can accept a five-minute delay, batch will be an order of magnitude cheaper and far easier to reason about during an incident.

An endpoint that survives real load

The difference between a demo endpoint and a production one shows up in five places: the model is loaded once at startup rather than per request, input is validated before it touches the model, latency is measured inside the handler, concurrency is bounded so the process cannot be overwhelmed, and failures return structured errors instead of stack traces. The server below implements those, plus a readiness probe that reports whether the model is actually loaded — a distinction that matters because a process that answers 200 while warming up will receive traffic it cannot serve.

python
# inference_server.py
import asyncio
import time
from collections import deque
from contextlib import asynccontextmanager
from typing import Deque, List, Optional

import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field, validator


class PredictRequest(BaseModel):
    features: List[float] = Field(..., min_items=1, max_items=512)
    request_id: Optional[str] = None

    @validator("features")
    def finite_only(cls, values):
        if not all(np.isfinite(values)):
            raise ValueError("features must be finite numbers")
        return values


class PredictResponse(BaseModel):
    prediction: float
    score: Optional[float]
    model_version: str
    latency_ms: float


class Model:
    version = "2026.02.11"

    def __init__(self, weights: List[float]):
        self.weights = np.asarray(weights, dtype=np.float64)

    def score(self, row: List[float]) -> float:
        return float(np.dot(self.weights, np.asarray(row)))


state: dict = {"model": None, "inflight": 0, "latencies": deque(maxlen=1024)}


@asynccontextmanager
async def lifespan(app: FastAPI):
    state["model"] = Model(weights=[0.4, -0.25, 0.15, 0.05])
    yield
    state["model"] = None


app = FastAPI(title="scoring-service", lifespan=lifespan)
semaphore = asyncio.Semaphore(32)


@app.get("/health")
async def health() -> dict:
    return {"status": "ok"}


@app.get("/ready")
async def ready() -> dict:
    if state["model"] is None:
        raise HTTPException(status_code=503, detail="model not loaded")
    return {"version": state["model"].version, "inflight": state["inflight"]}


@app.post("/predict", response_model=PredictResponse)
async def predict(req: PredictRequest) -> PredictResponse:
    if state["model"] is None:
        raise HTTPException(status_code=503, detail="model not loaded")
    if state["inflight"] >= 32:
        raise HTTPException(status_code=429, detail="server at capacity")

    async with semaphore:
        state["inflight"] += 1
        started = time.perf_counter()
        try:
            loop = asyncio.get_running_loop()
            score = await loop.run_in_executor(None, state["model"].score, req.features)
        except ValueError as exc:
            raise HTTPException(status_code=422, detail=str(exc))
        finally:
            state["inflight"] -= 1

    latency_ms = (time.perf_counter() - started) * 1000
    state["latencies"].append(latency_ms)
    return PredictResponse(
        prediction=1.0 if score > 0 else 0.0,
        score=score,
        model_version=state["model"].version,
        latency_ms=round(latency_ms, 3),
    )


@app.get("/metrics")
async def metrics() -> dict:
    values = sorted(state["latencies"])
    if not values:
        return {"count": 0}
    return {
        "count": len(values),
        "p50_ms": round(values[len(values) // 2], 2),
        "p95_ms": round(values[int(len(values) * 0.95) - 1], 2),
        "p99_ms": round(values[int(len(values) * 0.99) - 1], 2),
    }

The 429 path deserves attention. Rejecting load at the edge is healthier than accepting requests the process cannot finish, because a saturated queue converts a latency problem into a timeout problem for every caller. Load shed early, shed predictably, and let the caller's retry policy absorb it.

Dynamic batching for expensive models

Batching is where GPU economics are won. A transformer that answers one sequence at a time may use a fraction of the hardware; packing 16 sequences into one forward pass often cuts per-request cost by an order of magnitude while adding only a few milliseconds of queueing delay. The design is a queue plus a trigger: start a batch when either the maximum size is reached or the oldest waiter has exceeded a short deadline, whichever comes first.

python
# dynamic_batcher.py
import asyncio
import time
from dataclasses import dataclass, field
from typing import Any, Callable, List


@dataclass
class BatcherConfig:
    max_batch: int = 16
    max_delay_ms: float = 6.0
    max_queue: int = 1024


@dataclass
class _Entry:
    item: Any
    future: asyncio.Future
    enqueued_at: float = field(default_factory=time.perf_counter)


class DynamicBatcher:
    def __init__(self, infer_fn: Callable[[List[Any]], List[Any]],
                 config: BatcherConfig = BatcherConfig()):
        self.infer = infer_fn
        self.cfg = config
        self.queue: asyncio.Queue = asyncio.Queue(maxsize=config.max_queue)
        self.stats = {"batches": 0, "items": 0, "dropped": 0, "max_batch_seen": 0}

    async def submit(self, item: Any) -> Any:
        loop = asyncio.get_running_loop()
        future: asyncio.Future = loop.create_future()
        try:
            self.queue.put_nowait(_Entry(item, future))
        except asyncio.QueueFull:
            self.stats["dropped"] += 1
            raise RuntimeError("batch queue full")
        return await future

    async def run(self) -> None:
        while True:
            first = await self.queue.get()
            batch = [first]
            deadline = first.enqueued_at + self.cfg.max_delay_ms / 1000

            while len(batch) < self.cfg.max_batch:
                remaining = deadline - time.perf_counter()
                if remaining <= 0:
                    break
                try:
                    batch.append(await asyncio.wait_for(self.queue.get(), remaining))
                except asyncio.TimeoutError:
                    break

            results = await asyncio.get_running_loop().run_in_executor(
                None, lambda: self.infer([e.item for e in batch])
            )
            for entry, value in zip(batch, results):
                if not entry.future.done():
                    entry.future.set_result(value)

            self.stats["batches"] += 1
            self.stats["items"] += len(batch)
            self.stats["max_batch_seen"] = max(self.stats["max_batch_seen"], len(batch))


def fake_infer(batch: List[float]) -> List[float]:
    time.sleep(0.004)
    return [x * 2 for x in batch]


async def main() -> None:
    batcher = DynamicBatcher(fake_infer)
    worker = asyncio.create_task(batcher.run())
    results = await asyncio.gather(*(batcher.submit(i) for i in range(64)))
    await asyncio.sleep(0.05)
    worker.cancel()
    print("first results:", results[:5])
    print("stats:", batcher.stats)


if __name__ == "__main__":
    asyncio.run(main())

Tune max_batch against measured p99 rather than throughput alone. The curve is friendly at first — cost per row falls quickly — then flattens while queueing delay grows linearly, and the knee of that curve is your operating point. Measure it under realistic input lengths, because a batch sized for short sequences will blow the deadline on the long tail.

Spreading traffic and swapping versions

Once a single replica behaves, the interesting questions become how traffic is distributed and how a new version takes over. Round-robin balancing looks correct and behaves badly when requests have wildly different costs: a replica that draws a burst of long sequences falls behind while its neighbours idle, and tail latency degrades for everyone. Least-connections or latency-aware routing fixes most of that, and connection draining during a rollout keeps in-flight requests from being killed mid-prediction.

Version swaps deserve the same discipline. A rolling update with maxUnavailable: 0 keeps capacity while new pods warm; each new pod passes readiness before joining, so the model load time never becomes a user-visible gap. For models where even a brief quality dip is expensive, run the new version as a canary at a small percentage of traffic, watch the fallback and error counters, and promote only if they stay flat. The rule that makes this safe is architectural rather than procedural: traffic targeting must be controlled by the deployment layer, not by a hard-coded version inside application code, otherwise every rollout becomes a rebuild.

Health, readiness, and graceful degradation

Liveness answers "is this process wedged", readiness answers "should this process receive traffic", and conflating them causes restart loops during model loads. Keep them separate: liveness touches nothing but a counter, readiness verifies the model artifact is loaded and the weights checksum matches. A pod that fails readiness stays in the service rotation's exclusion set while it warms, and rolling updates become genuinely safe.

Degradation is the other half. When the model times out or returns garbage, callers need a documented answer — a cached prediction, a conservative default, or a fast rules-based fallback — rather than a 500. Pick the fallback per use case: a recommender can serve popularity, a fraud scorer should default to manual review, a search ranker can fall back to recency. Whatever you choose, emit a distinct metric for fallback usage, because that counter is often the earliest signal that the model is unhealthy in a way aggregate latency will never reveal.

💡Benchmark with production-shaped inputs

Synthetic uniform vectors hide the tail. Replay a day of captured requests, including the pathological ones, and plot p99 against batch size before choosing a configuration.

Common Mistakes

Loading the model inside the request handler

Fix: Load once at startup, gate readiness on success, and keep the handle in module state.

Averaging latency instead of tracking p95 and p99

Fix: Report percentiles from a bounded window; the tail is what users and SLAs actually experience.

Returning 500s when the model cannot answer

Fix: Return a documented fallback with a dedicated metric so degradation is visible and survivable.

Sizing capacity from average load

Fix: Provision for peak with autoscaling headroom, and shed load explicitly at the edge rather than queueing forever.

Best Practices

  • Separate liveness from readiness and gate traffic on readiness
  • Validate and bound inputs before they reach the model
  • Measure queue time and compute time separately when tuning batching
  • Return the model version in every response for fast incident triage
  • Replay captured traffic in CI so latency regressions fail the build

Interview Questions

Q1: How do you decide between batch and real-time inference?

Whether the product tolerates delay. If a five-minute lag is acceptable, batch is dramatically cheaper and simpler; only user-facing latency forces real time.

Q2: What is dynamic batching and what does it trade away?

Accumulating requests into one forward pass to raise hardware utilization, trading a few milliseconds of queueing delay for much lower cost per row.

Q3: Why separate health from readiness?

A process can be alive but not yet able to serve — during model load. Conflating them either routes traffic too early or restarts pods during warm-up.

Q4: How do you handle overload?

Shed load at the edge with a bounded queue and explicit 429s, so callers can retry with backoff instead of every request timing out.

Key Takeaways

  • Name the binding constraint — p99, cost, or freshness — before designing
  • Real time inherits a pager; batch inherits a schedule; pick deliberately
  • Startup loading, input validation, in-handler timing, and bounded concurrency are the four pillars
  • Batch size must be tuned on the p99 knee, measured with production-shaped traffic
  • Fallbacks plus a fallback metric turn model failure into a degraded response instead of an outage
🔒

Premium Content

Model Serving: Batching, Latency, and Fallbacks

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement