Skip to main content
LearnMLAcademy
Advanced10 min read

Batch, Online & Streaming Inference Architectures

Design batch, real-time online, and event streaming inference architectures, with pipeline maps, deployment choices, and production reliability checks.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Choose when and how predictions must arrive

Training creates a model artifact; inference uses that artifact to produce predictions. The correct inference architecture depends first on when predictions are needed: in bulk by a deadline, during one waiting request, or continuously as events arrive.

Serving mode is separate from learning mode. A model may retrain weekly yet serve online every millisecond, or retrain daily and write one batch of scores nightly.

What You Will Be Able to Explain

  • Compare batch, online, and streaming inference
  • Separate training and inference pipelines
  • Distinguish synchronous and asynchronous prediction
  • Calculate throughput and completion time
  • Allocate an end-to-end latency budget

Latency, throughput and serving modes

These terms name different responsibilities. Read the meaning before following them through the diagrams and worked example.

Core vocabulary

Core vocabulary
TermMeaning in this lesson
LatencyElapsed time from a request or event becoming ready to its prediction becoming available.
ThroughputPredictions completed per unit of time.
SynchronousThe caller waits for the prediction before continuing.
AsynchronousThe caller submits work and receives or reads the result later.
QueueA durable buffer that separates incoming work rate from worker processing rate.
SLAA service commitment; in this lesson, 100 ms is a chosen example target, not a universal number.

Serving architecture follows the timing contract

Batch inference reads a bounded input, partitions it across workers, writes versioned outputs, and records which partitions succeeded. It suits overnight churn scoring because the business needs all scores by morning, not one response per waiting user.

Online inference usually sits behind an API. It validates one request, obtains fresh features, runs the model, applies decision logic, and responds within a stated latency target. Every synchronous dependency consumes the same end-to-end budget.

Streaming inference consumes an unbounded event stream. It may maintain state such as counts over a time window, track offsets, checkpoint progress, and write predictions continuously. Streaming is not simply a very frequent batch job; recovery and event ordering are explicit concerns.

Batch, online, and streaming inference solve different timing problems

When is a prediction needed, and how does that shape the architecture?

Batch10M customers overnight
↓
files/table → workers → scored tableminutes or hours; restart by partition
Onlineone transaction request
↓
API → live features → model → responsesynchronous; milliseconds
Streamingcontinuous event stream
↓
broker → stateful processors → sinkfresh events; offsets/checkpoints
How to read it: Batch maximizes efficient bulk work, online answers one synchronous request within a latency target, and streaming continuously processes events with checkpointed recovery.

Choose an inference mode from the operating need

Choose an inference mode from the operating need
DimensionBatchOnlineStreaming
ExampleScore all customers overnightScore one transaction during API requestScore each event from a continuous topic
LatencyMinutes/hours by deadlineMilliseconds/seconds per requestLow event-to-result delay
ThroughputHigh bulk efficiencyHandles concurrent requestsSustained event rate
FreshnessSnapshot at run timeLatest available request/featuresContinuous event/state updates
ScalingMore partitions/workersReplicas, load balancing, autoscalingPartitions and stateful consumers
RecoveryRetry failed partitionsTimeout, retry policy, fallbackOffsets, checkpoint, replay, deduplication
Consistency riskSnapshot/version mismatchFeature and model mismatchOrdering, late, or duplicate events
Complexity/costOften simplest per predictionPays for ready capacityHighest state/operations complexity

Package the model with the code it depends on

A deployable inference unit combines the trained model artifact, its preprocessing or feature contract, compatible runtime dependencies, and the serving code and configuration. Packaging these pieces together makes dependency versions repeatable, prevents model/runtime incompatibility, and lets a release or rollback restore one known bundle. A container is one common packaging mechanism for keeping that environment consistent, but containers are not mandatory for every architecture and containerization is not the definition of MLOps.

Training and inference pipelines have different outputs

Training and inference pipelines have different outputs
PipelineConsumesProducesSuccess means
TrainingHistorical features + labelsEvaluated candidate artifactReproducible evidence and eligible model
InferenceApproved current inputs + production artifactPrediction + metadataCorrect contract within freshness/latency/reliability target

Account for waiting time as well as model compute

Queues allow asynchronous callers and absorb short bursts, but they do not create capacity. When arrival rate remains above processing rate, queue depth and waiting time keep growing. Backpressure slows or rejects producers before overload becomes uncontrolled.

An online response spends one shared latency budget

Which sequential stages consume a 100 ms service target?

10 ms
network
10 ms
validate
25 ms
features
35 ms
model
10 ms
rules
10 ms
return

Illustrative total = 10 + 10 + 25 + 35 + 10 + 10 = 100 ms SLA budget

How to read it: Network, validation, feature lookup, model inference, rules, and serialization all spend the same end-to-end budget. A fast model alone does not guarantee a fast endpoint.

Worked Example: Estimate a 10-million-row batch

Given: There are 10,000,000 predictions. Average model compute is 4 ms = 0.004 seconds per prediction. Assume 20 workers are identical, perfectly utilized, and work divides evenly. Ignore data loading, network, startup, writing, failures, and coordination.

  1. Sequential compute = 10,000,000 × 0.004 seconds = 40,000 seconds.
  2. With 20 perfectly utilized parallel workers, ideal wall time = 40,000 ÷ 20 = 2,000 seconds.
  3. Convert seconds: 2,000 ÷ 60 = 33.333... minutes, or approximately 33 minutes 20 seconds.
  4. This is an optimistic compute-only lower bound. Real elapsed time adds input/output, startup, skewed partitions, retries, and spare capacity.
  5. An online 100 ms SLA asks a different question: one request's complete dependency chain must finish within 0.100 seconds. A high-throughput batch worker that waits to fill large batches may violate that per-request target.

Result and interpretation: The toy batch can finish model compute in about 33 minutes 20 seconds under ideal assumptions. The same design is not automatically appropriate for an online endpoint because bulk throughput and individual latency optimize different goals.

Calculate serving capacity and describe the inference contract

The label above each block states what it is. Runnable Python can be executed as shown with the standard library; pseudocode and configuration communicate architecture and require adaptation to a real platform.

Score batch partitions with restartable outputs

Each partition records input, model, feature, and output versions so a failed partition can be retried without rescoring successful work.

Score batch partitions with restartable outputsCONCEPTUAL PSEUDOCODE
for partition in uncompleted_partitions(run_id):
    rows = read_snapshot(input_version, partition)
    features = transform(rows, feature_version)
    scores = model.predict(features)
    write_atomic(run_id, partition, scores, model_version)
    mark_complete(run_id, partition)

Make the online contract explicit

The total is an application target allocated across dependencies. Teams measure actual percentiles and revise these budgets.

Make the online contract explicitILLUSTRATIVE CONFIGURATION
endpoint: POST /v1/churn-score
total_sla_ms: 100
timeouts_ms:
  feature_lookup: 30
  model_inference: 40
  total_internal: 90
fallback: manual_review
log_versions: [request_schema, features, model, policy]

Choose a serving mode from the response deadline

  • Use the least complex mode that satisfies prediction freshness and response timing.
  • Keep work asynchronous when no user or transaction must wait for it.
  • Measure p50, p95, and p99 latency; an average can hide slow requests that violate the experience.
  • Plan overload behaviour—queue, shed, degrade, or scale—before traffic exceeds capacity.

Failure Analysis and Recovery

Observed failure → likely cause → controlled response

Observed failure → likely cause → controlled response
Observed failureLikely causeResponse
Batch misses deadlineI/O, skew, retries, or insufficient workers ignoredMeasure stage times; repartition; add bounded capacity
Online p95 exceeds targetSlow feature dependency or cold modelBreak down the latency budget by span
Streaming duplicates decisionsReplay without idempotencyUse event IDs and deterministic output keys
Queue grows continuouslyArrival rate exceeds service rateApply backpressure, increase safe capacity, or reduce work

Connect to Earlier Lessons

Summary / Key Takeaways

  • Training produces an evaluated artifact; inference applies an approved artifact to current inputs.
  • Batch inference optimizes bulk completion by a deadline, online inference optimizes waiting-request latency, and streaming inference continuously handles events and state.
  • Synchronous callers wait for a result; asynchronous work can be queued and completed later.
  • Latency measures elapsed response time, while throughput measures completed predictions per unit time.
  • Twenty ideal workers reduce 40,000 seconds of compute to 2,000 seconds—about 33 minutes 20 seconds—under deliberately simplified assumptions.
  • A 100 ms online SLA covers validation, feature lookup, inference, policy, network, and serialization, not only model compute.
  • Queues absorb temporary bursts but sustained overload requires backpressure, scaling, reduced work, or controlled rejection.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Batch, Online & Streaming Inference Architectures"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5practical selection
Which workload most naturally fits batch inference?
Question 2 of 5numerical/formula
What is the ideal compute-only time for 10,000,000 predictions at 4 ms each across 20 perfectly utilized workers?
Question 3 of 5interpretation
Why can that batch estimate not prove a 100 ms online SLA?
Question 4 of 5debugging/diagnostic
A streaming consumer replays events after recovery and produces duplicate decisions. What control is missing?
Question 5 of 5application/scenario
A queue grows for hours while traffic is steady. What is the most accurate diagnosis?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which workload most naturally fits batch inference?▼

Correct Answer: Score all customers before the morning retention shift

The scores are needed in bulk by a deadline rather than as one low-latency response, so batch inference is the simpler fit.

2What is the ideal compute-only time for 10,000,000 predictions at 4 ms each across 20 perfectly utilized workers?▼

Correct Answer: 2,000 seconds

Sequential compute is 10,000,000 × 0.004 = 40,000 seconds; dividing evenly across 20 workers gives 2,000 seconds.

3Why can that batch estimate not prove a 100 ms online SLA?▼

Correct Answer: Batch completion throughput and one request's end-to-end latency are different constraints

Online latency includes the sequential request chain and queueing. High aggregate throughput does not guarantee each request completes within 100 ms.

4A streaming consumer replays events after recovery and produces duplicate decisions. What control is missing?▼

Correct Answer: Checkpoint-aware idempotency or deduplication

Replay is normal recovery behaviour. Stable event IDs and idempotent outputs prevent a repeated event from creating a second logical action.

5A queue grows for hours while traffic is steady. What is the most accurate diagnosis?▼

Correct Answer: Sustained arrival rate exceeds effective processing rate

A queue absorbs temporary bursts but cannot add processing capacity. Persistent growth means work enters faster than it leaves.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next