TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Batch, Real-Time and Streaming Inference

Batch, Real-Time and Streaming Inference

A trained model can deliver its predictions in very different ways. A bank can score every customer once a night and store the results in a table; a checkout page can ask a fraud model about each payment while the customer waits; a recommendation system can update a user's scores a few seconds after each click; a phone keyboard can run its model on the device without any server at all. The model may be identical in all four cases. What differs is when the prediction is computed, how fresh its inputs are, how long someone waits for it, and what it costs. Choosing the serving mode is one of the first architecture decisions of an ML system, and it is usually decided by those four quantities rather than by the model.

Four ways to serve a model

batchhours at 02:00 score all rows prediction table, look-up onlinemilliseconds client waits model service request -> response, one row streamingseconds events queue + consumer fresh scores, features edgeno network device: app + small model private, offline, size-limited
Mode Prediction computed Typical latency or staleness Good for Watch out for
Batch on a schedule, for all rows hours (staleness) churn scores, credit limits, demand forecasts, email campaigns stale inputs; scoring rows nobody will look at
Online (real-time) on request, one row or a few milliseconds to ~1 s fraud checks, search ranking, pricing, chat tail latency, availability, peak capacity
Streaming per event, seconds after it happens seconds session-based recommendations, anomaly alerts, live features backlog and lag, exactly-once processing, ordering
Edge on the user's device milliseconds, no network keyboards, cameras, offline apps, privacy-sensitive data model size, many versions in the field, slow updates

Many systems mix them: a nightly batch job precomputes most of a score, and an online model adjusts it with the last few minutes of activity. The edge lesson treats on-device deployment in depth; this lesson compares the first three with numbers.

Definitions: latency, staleness, throughput, Little's law

Latency is the time from a request to its response; for online serving it is what the user feels, and its tail (the slowest 1 % of requests) matters more than its mean (next lessons). Staleness is the age of the information a prediction is based on, at the moment it is used. A batch prediction can be looked up in 1 ms, but if it was computed last night it is hours stale. Throughput is the number of predictions per second the system can sustain.

For a job that runs every PP hours and takes DD hours, an event that happens at a uniformly random time waits on average half a period for the next run, plus the run itself:

mean staleness=P2+D,worst case=P+D\text{mean staleness} = \frac{P}{2} + D, \qquad \text{worst case} = P + D

The job duration itself is the number of rows divided by the throughput: D=N/(r⋅k)D = N / (r \cdot k) for NN rows, rr rows per second per worker and kk workers.

For online and streaming systems, the central identity is Little's law. In any stable system where requests arrive at an average rate λ\lambda and spend an average time WW inside, the average number of requests inside the system is

L=λWL = \lambda W

It holds regardless of the arrival pattern or the service-time distribution, which makes it the most useful formula in capacity planning. A service receiving λ=400\lambda = 400 requests per second with W=0.05W = 0.05 s has on average L=20L = 20 requests in flight, so it needs at least 20 concurrent workers (threads, processes, batch slots) just to keep up, and more to absorb bursts. The system-design lesson on latency and throughput covers it from the infrastructure side.

From scratch: checking Little's law in a simulation

Simulate one model server that handles requests one at a time in arrival order (a single-server queue). Requests arrive at random (Poisson, 40 per second), and each takes an exponentially distributed time with mean 20 ms. Measure WW from the request times, measure LL by looking at the system at 20,000 random moments and counting requests inside, and compare with λW\lambda W.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
lam, mean_service, n = 40.0, 0.020, 50_000
arrivals = np.cumsum(rng.exponential(1 / lam, n))
service = rng.exponential(mean_service, n)
start = np.empty(n); finish = np.empty(n)
free_at = 0.0
for i in range(n):                                 # one server, first come first served
    start[i] = max(arrivals[i], free_at)
    finish[i] = free_at = start[i] + service[i]
W = (finish - arrivals).mean()                     # mean time in the system (wait + service)

t = rng.uniform(arrivals[0], arrivals[-1], 20_000)  # look at the system at random moments
inside = np.searchsorted(arrivals, t, side="right") - np.searchsorted(np.sort(finish), t, side="right")
lam_hat = n / (arrivals[-1] - arrivals[0])
print(f"utilisation rho = lambda * service = {lam * mean_service:.2f}")
print(f"measured: lambda = {lam_hat:.1f}/s, W = {W * 1000:.1f} ms")
print(f"L observed at random moments = {inside.mean():.2f}, lambda * W = {lam_hat * W:.2f}")
utilisation rho = lambda * service = 0.80
measured: lambda = 40.0/s, W = 95.0 ms
L observed at random moments = 3.79, lambda * W = 3.80

The two numbers agree (3.79 against 3.80): Little's law needs no assumption about the distributions. Notice also how large WW is. Each request needs only 20 ms of work, yet it spends 95 ms in the system on average, because at 80 % utilisation it usually finds others in front of it. Queueing theory predicts W=1/(μ−λ)=1/(50−40)=0.1W = 1/(\mu - \lambda) = 1/(50 - 40) = 0.1 s for this single-server queue (with μ=50\mu = 50 requests per second), close to the measured value; the latency lesson builds on this.

Batch, micro-batch or online: a day of predictions

Now the decision itself, with a simplified credit-risk scenario: customer events (a new loan application, a missed payment) arrive over a day with a daytime peak, 50 million per day in total. Three designs:

  • nightly batch: score all 5 million customers at 02:00; the job runs on 8 workers at 2,000 rows per second each;
  • micro-batch: every 5 minutes, score the customers with new events, on 2 workers at the same 2,000 rows per second each;
  • online: score each event when it arrives; one replica handles 100 requests per second, and replicas are kept at most 60 % busy so that latency stays low (why 60 %).

The simulation measures staleness (time from an event to a prediction that includes it) and the compute cost in worker-hours per day.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
events_per_day, customers = 50_000_000, 5_000_000
hours = np.arange(24)
profile = 1 + 0.8 * np.sin((hours - 8) / 24 * 2 * np.pi)       # daytime peak around 14:00
rate = events_per_day * profile / profile.sum() / 3600           # events per second, per hour of the day

# Sample 100,000 event times (in hours) that follow the daily profile
h = rng.choice(24, 100_000, p=profile / profile.sum()) + rng.uniform(0, 1, 100_000)

# Nightly batch at 02:00 on 8 workers x 2000 rows/s
D = customers / (8 * 2000) / 3600                                # job duration in hours
ready = np.where(h < 2, 2, 26) + D                               # the next 02:00 run, plus its duration
batch = ready - h
# Micro-batch every 5 minutes on 2 workers: a run scores the events of the last window
P = 5 / 60
run_h = rate * 300 / (2 * 2000) / 3600                           # run duration (hours) at each hour of the day
micro = (np.floor(h / P) + 1) * P + run_h[h.astype(int)] - h
# Online: latency only (log-normal, median 30 ms)
online_s = rng.lognormal(np.log(0.030), 0.4, 100_000)

def q(x):
    return np.percentile(x, [50, 95]).round(2)
print(f"batch job duration D = {D * 60:.0f} min")
print(f"staleness, nightly batch: p50 {q(batch)[0]} h, p95 {q(batch)[1]} h, mean {batch.mean():.2f} h")
print(f"staleness, micro-batch:   p50 {q(micro * 60)[0]} min, p95 {q(micro * 60)[1]} min")
print(f"latency, online:          p50 {q(online_s * 1000)[0]} ms, p95 {q(online_s * 1000)[1]} ms")

replicas = np.ceil(rate / (100 * 0.6))                           # per hour, autoscaled
print(f"peak rate {rate.max():.0f}/s -> up to {int(replicas.max())} replicas")
print(f"longest micro-batch run {run_h.max() * 3600:.0f} s")
print(f"worker-hours per day: batch {8 * D:.1f}, micro-batch {(2 * run_h * 12).sum():.1f}, "
      f"online autoscaled {replicas.sum():.0f}, online fixed at peak {replicas.max() * 24:.0f}")
batch job duration D = 5 min
staleness, nightly batch: p50 11.64 h, p95 20.0 h, mean 11.68 h
staleness, micro-batch:   p50 3.46 min, p95 5.8 min
latency, online:          p50 29.99 ms, p95 57.63 ms
peak rate 1042/s -> up to 18 replicas
longest micro-batch run 78 s
worker-hours per day: batch 0.7, micro-batch 6.9, online autoscaled 244, online fixed at peak 432

The three designs differ by orders of magnitude on both axes:

  • The nightly batch is by far the cheapest: 5 minutes on 8 workers, 0.7 worker-hours a day, for all 5 million customers. But a prediction that includes a given event is on average 11.68 hours old (p95 20.0 h), because the event waits for the next 02:00 run.
  • The micro-batch brings staleness down to minutes (p50 3.46 min, p95 5.8 min) for 6.9 worker-hours, about ten times the batch cost. Its longest run, 78 s at the daytime peak, must stay well below the 5-minute period, or runs start to overlap.
  • Online gives the freshest answer (p50 30 ms, p95 58 ms after the event) and costs the most: the peak of 1042 events per second needs 18 replicas, 244 replica-hours a day with hourly autoscaling, 432 without. The service also has to be up all the time, with a fallback when it is not.

Which one is right depends on the value of freshness: a fraud check that runs after the payment went through is worthless, a churn score that is a day old is fine. The numbers here are illustrative (real throughput depends on the model and hardware), but the shape of the trade-off is typical.

Streaming: lag is a queue

A streaming consumer is an online service whose clients do not wait, so nothing pushes back when it falls behind: the events wait in the queue instead. The lag of a consumer is the backlog divided by its processing rate. As long as the processing rate stays above the arrival rate on average, bursts create temporary lag that drains; if the arrival rate exceeds it for long, lag grows without bound. The simulation below sends 800 events per second with a burst of 2,000 per second between seconds 60 and 90, to a consumer that processes 1,200 per second.

python · try it yourself
import numpy as np

rng = np.random.default_rng(2)
seconds = np.arange(240)
arrival_rate = np.where((seconds >= 60) & (seconds < 90), 2000, 800)
arrivals = rng.poisson(arrival_rate)
capacity = 1200
backlog, lag = 0, []
for a in arrivals:
    backlog = max(0, backlog + a - capacity)     # what the consumer could not process this second
    lag.append(backlog / capacity)               # seconds an event now waits before it is scored
lag = np.array(lag)
print(f"max backlog {lag.max() * capacity:.0f} events, max lag {lag.max():.1f} s at second {int(lag.argmax())}")
print(f"lag back below 1 s at second {int(np.argmax((seconds > 90) & (lag < 1)))}")
print(f"burst excess {(2000 - capacity) * 30} events, drain rate {capacity - 800}/s -> "
      f"{(2000 - capacity) * 30 / (capacity - 800):.0f} s to drain")
max backlog 24336 events, max lag 20.3 s at second 89
lag back below 1 s at second 147
burst excess 24000 events, drain rate 400/s -> 60 s to drain

The burst adds 800 events per second above capacity for 30 s, 24,000 events in total (the simulation peaks at 24,336, because arrivals are random), so at second 89 a new event waits 20.3 s before it is scored. Afterwards the consumer drains the backlog with its spare 400 events per second, and lag is below 1 s again at second 147, about 60 s after the burst. Lag is the metric to alert on for a streaming model: it is the staleness of its predictions.

Pitfalls

  • Choosing online because it sounds modern. If the decision is made once a day (a credit limit, a marketing list), batch is simpler, cheaper and easier to monitor.
  • Ignoring staleness. A batch score that is cheap to look up can still be 26 hours old for an event that happened just after the run.
  • Training/serving skew between modes. Features computed in SQL for the batch job and in Python for the online service drift apart; share one feature definition (a feature store or one library).
  • Sizing for the mean. Online capacity must cover the peak, plus headroom; streaming capacity must cover the mean with enough spare to drain bursts.
  • Forgetting the fallback. Online models need a plan when they are slow or down: a cached batch score, a rule, a default (rollback and incidents).

Practice

  1. A nightly job scores 12 million rows with 6 workers at 2,500 rows per second each. How long does it run, and what is the mean staleness of a prediction for an event at a random time of day?
  2. A model service receives 250 requests per second and its mean latency is 80 ms. How many requests are in flight on average? Would a service with 16 worker threads keep up?
  3. A streaming consumer processes 1,000 events per second. Arrivals average 950 per second. What happens during a 60-second burst at 1,500 per second, and how long does it take to recover?
Answers
  1. D=12 000 000/(6⋅2500)=800D = 12\,000\,000 / (6 \cdot 2500) = 800 s, about 13 minutes or 0.22 h. Mean staleness P/2+D=12+0.22≈12.2P/2 + D = 12 + 0.22 \approx 12.2 hours; worst case about 24.2 hours.
  2. L=λW=250⋅0.08=20L = \lambda W = 250 \cdot 0.08 = 20 requests in flight. 16 threads are fewer than 20, so requests queue up, latency grows, and the system does not keep up; it needs more workers or lower latency.
  3. The backlog grows by 500500 events per second for 60 s, to about 30,000 events (30 s of lag). Afterwards it drains at 1000−950=501000 - 950 = 50 per second, which takes about 600 s, ten minutes. A consumer with little spare capacity recovers slowly.

Test yourself

A service has on average λ=200\lambda = 200 requests per second and a mean time in the system of 0.1 s. By Little's law, how many requests are inside on average?

  1. 2
  2. 20
  3. 200
  4. 2000

A batch job runs every 24 hours and takes 1 hour. What is the mean staleness of a prediction for an event at a uniformly random time?

  1. 1 hour
  2. 12 hours
  3. 13 hours
  4. 25 hours

Which use case fits online (request/response) serving best?

  1. A monthly churn list for a marketing campaign
  2. A fraud check on a card payment before it is approved
  3. A yearly demand forecast
  4. Re-scoring all customers after a model update

What happens to a streaming consumer whose processing rate is below the average arrival rate?

  1. It drops events automatically
  2. Its backlog and lag grow without bound
  3. Latency stays constant
  4. It becomes a batch job