Skip to content
Visual explainer 3h to learn 5 steps

Batch or online inference: serving patterns for ML models

Choose batch or online inference for a use case and write the prediction contract, latency budget and staged release plan.

By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.

Topic 28 of 34

In short

There are two main ways to serve a model. Batch inference scores many rows on a schedule and stores the results; online inference answers one request at a time through an API, usually within a strict time limit. The right choice depends on how fresh a prediction must be, and either way you need a written prediction contract and a staged release plan.

Think of it like this: Batch is printing tomorrow's newspaper overnight; online is answering the phone when a customer calls.

Explained simply

Once a model is packaged, someone has to use its predictions. There are two common ways to deliver them. Batch inference runs the model on a big set of rows at a set time, such as every night, and saves the results in a table. Online inference runs the model the moment a request arrives and sends the answer straight back.

Batch is usually the simpler and cheaper choice. A scheduled job reads the data, loads the model, scores everything and writes the output. If it fails, you rerun it. Online serving needs an always-on service, fast feature lookups, health checks and a plan for when the model is slow or down.

Whichever you choose, write a prediction contract. It says exactly what inputs the model expects, what the output means, which model version answered and what happens when something is wrong. It protects both sides: the model team and the people who use the predictions.

New model versions should not reach everyone at once. A staged release first runs the new model in the background, then gives it a small share of real traffic, and only then switches everyone over. This path covers the decisions; the Invicly FastAPI path covers building the API itself.

Press Play on a diagram to walk through it one step at a time.

CompareBatch versus online inference
Batch
  • Runs on a schedule, such as nightly
  • Scores millions of rows at once
  • Results stored in a table or file
  • Minutes or hours of delay are fine
  • Easy to retry and audit
Online
  • Runs per request through an API
  • Scores one or a few rows
  • Answer returned to the caller
  • Needs a latency budget, often under 100 ms
  • Needs scaling, health checks and fallbacks
SequenceAn online prediction with a fallback
Checkout app
Model API
Feature store
Model
  1. 1POST /predict with basket id
    Checkout app to Model API: POST /predict with basket id
  2. 2Fetch customer features
    Model API to Feature store: Fetch customer features
  3. 3Features in 30 ms
    Feature store to Model API: Features in 30 ms
  4. 4Run pipeline
    Model API to Model: Run pipeline
  5. 5Probability 0.82
    Model to Model API: Probability 0.82
  6. 6Score, model_version, or fallback on timeout
    Model API to Checkout app: Score, model_version, or fallback on timeout

In depth

Choosing between batch and online

Ask three questions. When is the input known? If all the inputs exist before anyone needs the answer, such as last month's usage for a churn score, batch works. If the input only exists at the moment of the request, such as the items in a basket at checkout, you need online. How fresh must the answer be? A score that is one day old is fine for a weekly email but not for blocking a fraudulent card payment. How many entities are there? Scoring ten million customers nightly is cheap in batch, but if only a few thousand are ever looked at, online may waste less work.

A middle option is to precompute in batch and serve the stored results through a fast lookup, which gives online-feeling speed with batch simplicity.

MapPicking a serving pattern
When is the input known?
  • Before it is needed
    • Batch scoring on a schedule
    • Store results in a table
  • Before, but read live
    • Batch precompute
    • Serve via key lookup
  • Only at request time
    • Online API
    • Set a latency budget
    • Plan a fallback

Writing the prediction contract

A prediction contract is a short document, plus a schema in code, that both sides agree on. It lists each input field with its type, units and allowed values, and which fields are required. It defines the output: for example churn_probability as a float from 0 to 1, and the threshold that turns it into a yes or no. It includes a model_version field in every response, so you can trace any prediction back to a registered model. It says what happens on bad input, such as a 422 error for a missing field, and what the fallback is when the model fails, such as returning a rule-based score with a flag.

In a FastAPI service, Pydantic v2 models enforce the input and output schema automatically.

  • Inputs: names, types, units, required or optional
  • Output: meaning, range and threshold
  • model_version in every response
  • Errors and fallback behaviour
  • Expected latency and throughput

Setting a latency budget

A latency budget is the total time a caller can wait, split across the steps. Suppose checkout must answer within 150 ms at p95, meaning 95 percent of requests finish in that time. You might allow 20 ms for the network, 40 ms for fetching features from a store, 30 ms for the model and 20 ms for validation and logging, keeping 40 ms spare.

Measure each part, not just the total. Tree ensembles with thousands of trees, large text models or slow database lookups often break the budget. Fixes include a smaller model, precomputing features, batching several requests together or caching frequent answers. Always set a client timeout and a fallback, so a slow model does not block the checkout.

  • State budgets at p95 or p99, not the average
  • Measure network, features, model and overhead separately
  • Set timeouts and a fallback answer

Staged releases

A staged release lowers the risk of a new model. In shadow mode, the new model receives a copy of live requests and its predictions are logged but never used. You compare its outputs, latency and errors with the current model. In a canary, a small share of traffic, such as 5 percent, gets the new model's answers while you watch business and service metrics. If the guardrails hold for an agreed period, you increase the share, then switch fully.

For batch jobs the same idea applies: score with both models, compare distributions and spot-check, then switch the output table. Every stage needs a pre-written rollback: point back to the previous model version and confirm predictions return to normal.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Compare batch and online inference~35m
  2. 2
    Write a prediction contract~35m
  3. 3
    Set a latency budget~35m
  4. 4
    Plan staged releases~35m
  5. 5
    Hand API work to FastAPI~35m

Key points

  • Choose batch when predictions can be computed before they are needed; it is simpler and cheaper.
  • Choose online when the input only exists at request time, such as a basket being checked out.
  • A prediction contract fixes the input schema, output meaning, units, model version field and error behaviour.
  • A latency budget splits the allowed response time between network, feature lookup, model and overhead.
  • Release in stages: shadow, then a small canary share, then everyone, with a tested rollback.

Key terms

Tap a card to flip it. 0/6 known

Examples

A nightly batch scoring job

A subscription company wants a churn score for every customer each morning. Step 1: a scheduler (cron, Airflow or a CI schedule) starts the job at 02:00. Step 2: the job loads the model by its registry alias, so switching versions does not need a code change. Step 3: it scores the snapshot table and writes results with the model version and a run date. Step 4: it checks row counts and the score distribution before publishing. Rollback: point the alias back and rerun.

python
import datetime as dt
import mlflow
import pandas as pd

model = mlflow.pyfunc.load_model("models:/churn@champion")
customers = pd.read_parquet("data/customers_snapshot.parquet")
scores = customers[["customer_id"]].copy()
scores["churn_probability"] = model.predict(customers.drop(columns=["customer_id"]))
scores["model_uri"] = "models:/churn@champion"
scores["scored_on"] = dt.date.today().isoformat()
assert len(scores) == len(customers) and scores["churn_probability"].between(0, 1).all()
scores.to_parquet(f"out/churn_scores_{dt.date.today()}.parquet")

Writing a contract with Pydantic

Before building the API, the team agrees on the schema. Step 1: define the request fields with types and limits. Step 2: define the response with the probability, the decision and the model version. Step 3: share the generated JSON schema with the caller team. Any request that breaks the schema is rejected with a clear error instead of producing a silent bad prediction. The FastAPI path shows how to serve this.

python
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field

class ChurnRequest(BaseModel):
    model_config = ConfigDict(extra="forbid")
    tenure_months: int = Field(ge=0, le=600)
    monthly_spend: float = Field(ge=0)
    plan: Literal["basic", "plus", "pro"]

class ChurnResponse(BaseModel):
    churn_probability: float = Field(ge=0, le=1)
    will_churn: bool
    model_version: str
    fallback_used: bool = False

print(ChurnRequest.model_json_schema())

Quick reference

  • Batch: input known in advance, freshness of hours is fine, cheapest to run
  • Online: input only exists at request time, needs a latency budget and fallback
  • Precompute plus lookup gives fast reads with batch simplicity
  • Contract = inputs, output meaning, model_version, errors, fallback
  • Budget latency at p95 or p99 and measure each step separately
  • Release path: shadow, canary (for example 5 percent), full, with rollback ready
  • Load models by alias, such as models:/churn@champion, so switching needs no code change

Common mistakes

  • Building a real-time API for predictions that nobody needs until tomorrow morning.
  • Leaving the contract implicit, so a renamed column silently turns into missing values.
  • Measuring average latency only; slow tail requests are what users notice.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A card payment must be approved or blocked within 200 ms using details of that transaction. Which pattern fits?

Question 2

2What does p95 latency of 120 ms mean?

Question 3

3In shadow mode, what happens to the new model's predictions?

Question 4

4Why include model_version in every prediction response?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    For each case, choose batch or online and give one reason: weekly product recommendations email, spam filter for incoming email, monthly credit limit review, live delivery time estimate in an app.

  2. Exercise 2medium

    Write a latency budget for a 150 ms p95 product-ranking API with network, feature lookup, model and logging steps. Leave headroom and name one fallback.

  3. Exercise 3hard

    Write a staged release plan for replacing a churn model served online: stages, traffic share, duration, guardrail metrics and rollback steps.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is online inference always better because it is real-time?
No. It costs more to build and run and has more ways to fail. If predictions can be computed in advance, batch is usually the better choice.
Can MLflow serve models?
Yes. The mlflow models serve command starts a local REST server for a logged model, which is useful for testing. Many teams still wrap the model in their own FastAPI service for control over the contract, auth and logging.
What is the difference between a canary and an A/B test?
A canary is a safety check that a new version does no harm before full rollout. An A/B test is an experiment designed to measure which version is better, with planned sample sizes and statistics.

Go deeper

ShareXLinkedInWhatsApp