Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 15 min · revision 2

Batch, Online or Streaming: Picking the Inference Pattern

Compare the three ways to deliver predictions with one churn model: what scoring rows together saves over one call per row, how fresh the score is when a decision is made under batch, streaming and online inference, what the window of a streaming micro-batch trades, and how fixed and per-request costs set the price of 1,000 predictions.

Contentsand lesson path

What you will learn

  • Choose batch, online or streaming inference and a rollout strategy (shadow, canary, A/B test, rollback) from latency, freshness, cost and risk requirements.

Prerequisites: Containerization

01. Why it matters

The same model can reach users in three ways. In batch inference a scheduled job scores many rows at once, for example every customer each night, and writes the results to a table that other systems read. In online inference a service scores one request at the moment someone asks, usually behind an HTTP API, and answers within milliseconds. In streaming inference a consumer reads events from a stream, such as a message queue, and rescores each affected entity soon after something changes.

The choice shapes everything after it: the infrastructure, the cost, how fresh the predictions are and what can go wrong. It should follow from four requirements: latency (how long a caller can wait), freshness (how old the data behind a score may be when a decision uses it), cost and risk. This lesson measures each one with small scripts on the churn model of the artifacts lesson. You need Python 3.12 with scikit-learn and pandas.

Terminal
mkdir -p patterns && cd patterns
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*"
Python · data.py
"""Seeded churn data: three numeric and two categorical columns."""
import numpy as np
import pandas as pd

NUMERIC = ["tenure_months", "monthly_fee", "support_calls"]
CATEGORICAL = ["plan", "channel"]


def make(n=4000, seed=0):
    rng = np.random.default_rng(seed)
    df = pd.DataFrame({
        "tenure_months": rng.integers(0, 72, n),
        "monthly_fee": rng.normal(45, 15, n).clip(5, 120).round(2),
        "support_calls": rng.poisson(1.5, n),
        "plan": rng.choice(["basic", "standard", "premium"], n, p=[0.5, 0.3, 0.2]),
        "channel": rng.choice(["online", "store"], n, p=[0.7, 0.3]),
    })
    logit = (-1.0 - 0.04 * df.tenure_months + 0.03 * (df.monthly_fee - 45)
             + 0.45 * df.support_calls + 0.6 * (df.plan == "basic"))
    df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    return df
Python · model.py
"""Train the churn pipeline used by every script in this lesson."""
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

from data import CATEGORICAL, NUMERIC, make


def trained():
    df = make()
    model = Pipeline([
        ("prep", ColumnTransformer([("num", StandardScaler(), NUMERIC),
                                    ("cat", OneHotEncoder(), CATEGORICAL)])),
        ("clf", LogisticRegression(max_iter=1000)),
    ])
    X = df[NUMERIC + CATEGORICAL]
    return model.fit(X, df["churned"]), X

02. Scoring rows together is much cheaper

Every call to a model has a fixed overhead: checking the input, building a data frame, running each preprocessing step and the model with all their Python bookkeeping. Scoring 1,000 rows in one call pays that overhead once, and the arithmetic runs as a few large vectorised operations. Scoring them one by one pays it 1,000 times. The script measures both on the same rows. The times depend on your machine, so the output is illustrative; the ratio is the point.

Python · per_call_cost.py
"""Score 1,000 rows in one call, then the same rows one call at a time."""
import time

import numpy as np

from model import trained

model, X = trained()
X = X.iloc[:1000]

start = time.perf_counter()
together = model.predict_proba(X)[:, 1]
batch_s = time.perf_counter() - start

start = time.perf_counter()
one_by_one = np.array([model.predict_proba(X.iloc[[i]])[0, 1] for i in range(len(X))])
single_s = time.perf_counter() - start

print("same predictions:", bool(np.allclose(together, one_by_one)))
print(f"one call for {len(X)} rows: {batch_s * 1000:.0f} ms")
print(f"{len(X)} calls of one row: {single_s * 1000:.0f} ms "
      f"({single_s / len(X) * 1e6:.0f} µs per row)")
Terminal
python per_call_cost.py
Illustrative output
same predictions: True
one call for 1000 rows: 6 ms
1000 calls of one row: 3756 ms (3756 µs per row)

The predictions are identical, and on our test machine one call took a few milliseconds while a thousand single calls took several seconds, hundreds of times longer. That is why batch scoring is the cheapest way to produce predictions, and why online services that receive many requests at once often group them, as the load-testing lab of this skill shows. Online inference is still the right choice when the answer is needed during a request and its inputs are not known in advance, such as the details of a payment that is happening now.

03. Freshness: how old is the score when it is used?

A prediction is only as fresh as the data it was computed from. The script follows one customer through a day. Their record changes three times: a support call at 09:10, another at 13:40, and a switch to a cheaper plan at 14:05. Four times a day, another system decides whether to show them a retention offer, and reads a churn score. With batch scoring it reads the score computed at 02:00. With streaming a consumer rescored the customer each time the record changed. With online scoring the score is computed inside the decision request from the current record.

Python · freshness.py
"""One customer's day: which churn score does each pattern use for each decision?"""
import pandas as pd

from model import trained

model, _ = trained()
start = {"tenure_months": 30, "monthly_fee": 60.0, "support_calls": 0,
         "plan": "standard", "channel": "online"}
# Changes to the customer's record during the day (time, column, new value).
events = [("09:10", "support_calls", 1), ("13:40", "support_calls", 2),
          ("14:05", "plan", "basic"), ("14:05", "monthly_fee", 35.0)]
decisions = ["08:00", "11:00", "14:30", "20:00"]   # retention offer shown or not


def features_at(time):
    row = dict(start)
    for when, column, value in events:
        if when <= time:
            row[column] = value
    return pd.DataFrame([row])


def score(time):
    return model.predict_proba(features_at(time))[0, 1]


def last_event_before(time):
    return max([when for when, _, _ in events if when <= time], default="00:00")


print("decision  batch (02:00)  streaming (on change)  online (at request)")
for t in decisions:
    batch = score("02:00")                      # scored overnight
    streaming = score(last_event_before(t))     # rescored when the record changed
    online = score(t)                           # scored inside the request
    print(f"{t:>8}  {batch:13.3f}  {streaming:21.3f}  {online:19.3f}")
Terminal
python freshness.py
Expected output
decision  batch (02:00)  streaming (on change)  online (at request)
   08:00          0.168                  0.168                0.168
   11:00          0.168                  0.238                0.238
   14:30          0.168                  0.297                0.297
   20:00          0.168                  0.297                0.297

All three agree at 08:00. By 14:30 the customer's risk has nearly doubled, but the batch table still shows the overnight value, and it will until the next night. Whether that matters depends on the decision. A weekly email campaign can use last night's scores; an offer shown while the customer is on the cancellation page cannot. Streaming and online give the same numbers here because the record only changed at known events. Online scoring can also use facts that exist only in the request, such as the page the customer is on; streaming cannot, but it keeps expensive scoring out of the request path, so the decision itself is a fast lookup.

04. Streaming: the micro-batch window

Streaming consumers rarely call the model once per event. They collect events into micro-batches: a batch closes when a time window has passed since its first event, or when it reaches a maximum size. The window is a trade-off between the cost per prediction and the delay before each event is scored. The script simulates 2,000 events arriving at about 200 per second and replays them with three windows, measuring the number of model calls, the average batch size and the 95th percentile of the time an event waits in the buffer. Times here are simulated, not measured, so the output repeats exactly.

Python · micro_batches.py
"""A streaming consumer groups events into micro-batches. What does the window cost?"""
import numpy as np

rng = np.random.default_rng(0)
arrivals = np.cumsum(rng.exponential(1 / 200, size=2000))   # about 200 events a second


def consume(window_s, max_batch=64):
    """Close a batch when its window ends or when it holds max_batch events."""
    calls, waits, i = 0, [], 0
    while i < len(arrivals):
        deadline = arrivals[i] + window_s
        j = i
        while j < len(arrivals) and arrivals[j] <= deadline and j - i < max_batch:
            j += 1
        closed = arrivals[j - 1] if j - i == max_batch else deadline
        waits.extend(closed - arrivals[i:j])      # how long each event sat waiting
        calls += 1
        i = j
    return calls, len(arrivals) / calls, np.percentile(waits, 95) * 1000


print(f"{len(arrivals)} simulated events over {arrivals[-1]:.0f} seconds")
print("window (ms)   model calls   events per call   p95 wait in buffer (ms)")
for window in (0.01, 0.05, 0.2):
    calls, per_call, p95 = consume(window)
    print(f"{window * 1000:11.0f} {calls:13d} {per_call:17.1f} {p95:25.0f}")
Terminal
python micro_batches.py
Expected output
2000 simulated events over 10 seconds
window (ms)   model calls   events per call   p95 wait in buffer (ms)
         10           674               3.0                        10
         50           184              10.9                        50
        200            50              40.0                       195

A 10 ms window makes 674 calls of about 3 events each; a 200 ms window makes 50 calls of 40. From the previous section you know that fewer, larger calls are far cheaper. The price is waiting: with the 200 ms window, 5% of events wait 195 ms or more before they are scored. For a fraud score that must arrive before a payment is approved, that may be too long; for updating a recommendation, it is nothing. Real streaming tools expose the same two knobs: a Kafka consumer has a maximum number of records per poll and a maximum wait for a fetch, and Spark Structured Streaming has a trigger interval and a limit on records per trigger.

05. Cost per 1,000 predictions

The costs of the three patterns have different shapes. A batch job pays only while it runs. An online service pays for replicas that stay up all the time, because a request can arrive at any moment, plus a load balancer. A streaming system pays for always-on workers and for the message broker. The script turns example prices into a monthly total and a cost per 1,000 predictions at two volumes. The prices are assumptions; replace them with your provider's.

Python · costs.py
"""Cost per 1,000 predictions for each pattern. All prices are example assumptions."""
VM_PER_HOUR = 0.10            # one small virtual machine, $ per hour
HOURS = 730                   # hours in a month

patterns = {
    # name: (machines, hours each runs per month, extra fixed $ per month)
    "batch, nightly job": (1, 30 * 1, 0),           # one machine for an hour a night
    "online, 2 replicas": (2, HOURS, 18),            # always on, plus a load balancer
    "streaming, 2 workers": (2, HOURS, 60),          # always on, plus a message broker
}
print("pattern                 $ per month   $ per 1,000 predictions")
print("                                       at 1M a month  at 50M a month")
for name, (machines, hours, extra) in patterns.items():
    monthly = machines * hours * VM_PER_HOUR + extra
    per_1k = [monthly / (volume / 1_000) for volume in (1_000_000, 50_000_000)]
    print(f"{name:22} {monthly:12.2f} {per_1k[0]:14.4f} {per_1k[1]:15.4f}")
Terminal
python costs.py
Expected output
pattern                 $ per month   $ per 1,000 predictions
                                       at 1M a month  at 50M a month
batch, nightly job             3.00         0.0030          0.0001
online, 2 replicas           164.00         0.1640          0.0033
streaming, 2 workers         206.00         0.2060          0.0041

Batch is the cheapest by far, as long as its freshness is enough. For the always-on patterns the monthly bill hardly depends on traffic, so the cost per prediction falls as volume grows, until you need more replicas. The script ignores the engineering cost, which often dominates: an online service needs on-call support, autoscaling and a latency budget, and streaming adds a broker to run and events to replay after failures.

In practice you choose per use case, and many systems mix patterns: nightly batch scores for most customers, plus an online model for the few decisions that need the current state. Risk matters as much as cost. A batch job that fails can usually be rerun before anyone reads its table, while an online model that fails affects users at once, which is why online releases go through the safe rollout steps of the rollouts lesson.

06. Check your understanding

Practice check · 3 questions

Choosing the pattern

Use the outputs of this lesson.

Q1. In `freshness.py`, the 14:30 decision reads 0.168 from the batch column while the other two read 0.297. Why does the batch value not change?
Q2. In `micro_batches.py`, moving the window from 10 ms to 200 ms cuts model calls from 674 to 50. What is the price of that saving?
Q3. In `costs.py`, the online service costs about $0.16 per 1,000 predictions at 1M a month and about $0.003 at 50M. Why does it fall so much?
Practice only: not graded, not saved, not evidence.

07. Apply it

For your project, write down for each place where your model's predictions are used: who reads them, how old the input data may be when the decision is made, how long the caller can wait, and how many predictions a month you expect. Choose batch, online or streaming for each, and justify it with those numbers and with costs.py filled in with your own prices. Your project needs both an online endpoint and a batch command, which the next lab builds on shared code.

08. Review prompt

Without looking back, answer in your own words:

  1. Define batch, online and streaming inference, and give one use case for each.
  2. Why is scoring 1,000 rows in one call so much cheaper than 1,000 calls of one row?
  3. What is freshness, and how does it differ between the three patterns?
  4. What does the window of a streaming micro-batch trade?
  5. Why does the cost per prediction of an always-on service fall as traffic grows?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check