Sub topic 11
Between the two: micro-batch and near-real-time
This chapter assumes you know the basics of batch scoring (a scheduled job over many rows) and online scoring (one request, one prediction, through an API). It also assumes you can read Python and know what a message queue is. The earlier chapters on latency, throughput and freshness are the background for the trade-offs here.
Why a middle ground exists
Batch and real-time prediction sit at two ends of a spectrum. Batch jobs score many records at once, on a schedule, and the results can be hours old. Online services score one record per request and answer in milliseconds, but they need always-on capacity and online access to features.
Many use cases fit neither end well:
- A fraud team wants scores within a minute of a transaction, not tomorrow morning. No customer is waiting on the answer, so there is no hard 100 ms deadline.
- A recommendation feed should reflect the last few clicks. Running a full API call per click is more serving infrastructure than the team wants to maintain.
- A dashboard needs scores refreshed every five minutes for a few million rows.
Two patterns cover this space. They overlap, and people often use the terms loosely, so this chapter defines them.
Definitions
Micro-batch prediction groups incoming records into small batches and scores each batch in one call. The groups are small, from a handful of rows to a few thousand. They form either on a short schedule (every 30 seconds, say) or when a size threshold is reached. Each batch is processed with the same vectorized code a batch job uses.
Near-real-time prediction is defined by its latency target, not its mechanism. It means results arrive within seconds to a few minutes of the triggering event. Micro-batching is one way to get there. A streaming consumer that scores each event as it arrives is another.
So the two terms are not parallel. Micro-batch describes how work is grouped. Near-real-time describes how fresh the output is. A micro-batch system is usually near-real-time, but a near-real-time system need not use micro-batches.
How micro-batching works
A typical micro-batch scorer has four parts:
- An event source, such as a message queue or a stream, that buffers incoming records.
- A collector that closes a batch when it reaches a maximum size or a maximum wait time, whichever comes first.
- A scorer that runs the model on the whole batch at once.
- A sink that writes scores to a store the application reads, or publishes them to another stream.
The two limits on the collector control different things. The size limit controls throughput and memory use. The time limit puts a ceiling on how long any record waits. Without the time limit, a quiet period would leave records stuck in a half-full batch indefinitely.
A runnable micro-batch scorer
The example below trains a small model, fills a queue with seven events, and scores them in batches of up to five. It uses the standard-library queue in place of a real message broker, so you can run it as is.
import queue
import time
import numpy as np
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(0)
X_train = rng.normal(size=(200, 3))
y_train = (X_train[:, 0] + X_train[:, 1] > 0).astype(int)
model = LogisticRegression().fit(X_train, y_train)
def collect_batch(events, max_size, max_wait_s):
"""Return up to max_size events, waiting at most max_wait_s in total."""
batch = []
deadline = time.monotonic() + max_wait_s
while len(batch) < max_size:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
batch.append(events.get(timeout=remaining))
except queue.Empty:
break
return batch
def score_batch(batch):
ids = [event["id"] for event in batch]
features = np.array([event["features"] for event in batch])
scores = model.predict_proba(features)[:, 1]
return dict(zip(ids, scores.tolist()))
events = queue.Queue()
for i in range(7):
events.put({"id": i, "features": rng.normal(size=3).tolist()})
while True:
batch = collect_batch(events, max_size=5, max_wait_s=0.5)
if not batch:
break
results = score_batch(batch)
print(f"scored {len(batch)} events:", results)The first batch closes because it reaches five events. The second holds the remaining two and closes when the 0.5 second timer expires. The third is empty, which ends the loop. In a real service the loop would run forever and write each result dictionary to a sink instead of printing it.
The batch-size trade-off
Batch size and wait time are the main tuning knobs. Both move latency and throughput in opposite directions.
- A larger batch uses the CPU or GPU more efficiently, because vectorized model code has fixed per-call overhead. Throughput and cost per prediction improve.
- A larger batch, or a longer wait, adds delay. A record that arrives right after a batch closes waits for the next one.
The worst-case added delay for a record is roughly the maximum wait time plus the scoring time for its batch. Set the maximum wait from the freshness requirement, not from what feels convenient. If the business can tolerate 60 seconds, a 5 second wait is cheap and a 55 second wait is risky.
Comparing the four patterns
| Aspect | Batch | Micro-batch | Streaming (per event) | Online API |
|---|---|---|---|---|
| Typical latency | Hours | Seconds to minutes | Sub-second to seconds | Milliseconds |
| Who triggers scoring | Scheduler | Timer or size limit | Each event | Each request |
| Caller waits for result | No | No | No | Yes |
| Compute usage | Spiky, then idle | Steady and efficient | Steady, less efficient | Sized for peak traffic |
| Operational complexity | Low | Medium | High | Medium to high |
The "caller waits" row is the key dividing line. In batch, micro-batch and streaming designs, results go to a store and the application reads them later. Only the online API returns a score in the same call that asked for it. If a user-facing request must block on a score, micro-batching will not meet that need.
Features and skew in near-real-time systems
Near-real-time scoring raises feature questions that pure batch avoids. A batch job reads a consistent snapshot of a warehouse table. A streaming system sees data arrive over time, and several things can go wrong:
- Late events. A record arrives after its batch window closed, so features such as "purchases in the last hour" are computed from incomplete data.
- Windowed features. A feature like "clicks in the last 10 minutes" must be computed the same way in training and in the stream. If training used exact windows over a warehouse and serving uses approximate windows over a stream, the two disagree. This is training-serving skew.
- Out-of-order data. Events can arrive in a different order than they happened, so time-based features should use event time, not arrival time.
The safest approach is to compute features with one shared definition, such as a single function or a feature store, and use it in both the training pipeline and the micro-batch scorer.
Common errors
- Using micro-batch where a caller must wait. If a checkout page needs a score before it responds, an asynchronous pipeline cannot supply it. Use an online service.
- No time limit on the collector. A size-only trigger leaves the last records unscored during low traffic.
- Tiny batches at high cost. Running a model on one or two rows per call, thousands of times a minute, gives up the efficiency that justified batching. Check that your batches are actually filling.
- Losing events on failure. If the scorer crashes after reading events but before writing scores, those events vanish. Commit the read position to the queue only after the scores are written. This gives at-least-once delivery, so make the sink idempotent: writing the same customer's score twice should be harmless.
- Ignoring the backlog. If scoring a batch takes longer than the time it takes to collect one, the queue grows without bound. Monitor queue depth and the age of the oldest unscored event.
- Mixing time sources. Computing features from processing time in serving but event time in training introduces skew.
When to choose each
Use micro-batch or near-real-time scoring when all of these hold:
- Freshness of seconds to minutes is good enough.
- No caller needs to block on the score.
- Request volume is high enough that batching reduces cost, or the feature data already lives in a stream.
- The team can run and monitor a queue and a long-running consumer.
Stay with plain batch if hourly or daily freshness is acceptable, because it is simpler. Move to an online service if the score must be returned inside a user request or depends on data that exists only at request time.
Exercises
Exercise
A micro-batch scorer closes a batch at 500 records or after 20 seconds. Traffic is 2 records per second. What is the typical batch size, and which limit closes the batch?
Show answer
At 2 records per second, 20 seconds yields about 40 records, far short of 500. The 20 second timer closes every batch, so batches hold about 40 records and each record waits at most about 20 seconds plus scoring time. The size limit only matters during traffic spikes above 25 records per second.
Exercise
Your scorer reads events from a queue, scores them, and writes results to a database. It crashes between scoring and writing. Describe when to commit the queue position and why the database write should be idempotent.
Show answer
Commit the queue position only after the database write succeeds. After a crash, the unacknowledged events are delivered again, so none are lost. Some events may be scored and written twice, so the write must be idempotent, for example an upsert keyed on customer ID, so that a repeated write leaves the same result.
Exercise
A product manager wants a fraud score returned in the same HTTP response that approves a card payment, within 150 ms. Can micro-batch scoring meet this? Explain.
Show answer
No. Micro-batch results are written to a store and read later, and the batch wait alone can exceed 150 ms. The payment call must block on the score, which needs an online prediction service with features available at request time.