Sub topic 11
Between the two: micro-batch and near-real-time
Prerequisites
This chapter assumes you know the basics from earlier chapters: batch scoring runs on a schedule over many records, and real-time scoring answers one request at a time. It also assumes you can read basic Python and understand the idea of a queue of events.
The gap between the two approaches
Some use cases fit neither pattern well. A nightly batch job is too slow for fraud checks on card swipes. A real-time service is more than you need if the business only needs a fresh score every few minutes. Micro-batch and near-real-time prediction cover this middle ground.
- Micro-batch collects incoming records for a short window, such as 30 seconds or 5 minutes. It then scores the whole window in one call, as a small batch job.
- Near-real-time is a looser term. It means predictions arrive seconds to minutes after the event, without a caller waiting on an open request.
In both cases, the caller does not wait for the answer. Events go into a queue or stream. A worker reads them, scores them, and stores the results. Other systems read the stored results later.
Why a window helps
Scoring many rows in one call is cheaper per row than scoring rows one by one. A model call has fixed overhead, and vectorized libraries such as scikit-learn handle many rows at nearly the same cost as a few. A window lets you keep most of the throughput benefit of batch while cutting staleness from hours to seconds or minutes.
The window size sets the trade-off:
| Window size | Staleness | Per-row cost | Typical fit |
|---|---|---|---|
| Large (minutes to hours) | Higher | Lower | Dashboards, email targeting |
| Small (seconds) | Lower | Higher | Alerts, feed ranking |
| One record | Lowest | Highest | Real-time APIs |
A minimal micro-batch worker
This example uses Python's standard queue module to stand in for a real stream such as Kafka. The worker collects records until it has 100 or until 5 seconds pass, whichever comes first. It then scores them together.
import queue
import time
import joblib
import pandas as pd
model = joblib.load("model.joblib")
feature_columns = ["tenure_months", "monthly_spend", "support_tickets"]
MAX_BATCH = 100
MAX_WAIT_SECONDS = 5.0
def collect_window(events: queue.Queue) -> list[dict]:
window = []
deadline = time.monotonic() + MAX_WAIT_SECONDS
while len(window) < MAX_BATCH:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
window.append(events.get(timeout=remaining))
except queue.Empty:
break
return window
def score_window(window: list[dict]) -> pd.DataFrame:
frame = pd.DataFrame(window)
frame["churn_score"] = model.predict_proba(frame[feature_columns])[:, 1]
return frame[["customer_id", "churn_score"]]A loop would call collect_window, skip empty windows, call score_window, and write the result to a database or file. The two limits matter. The size limit keeps memory bounded. The time limit stops a quiet period from delaying scores indefinitely.
Common errors
- No time limit on the window. If you wait only for a full batch, a slow period leaves records unscored.
- Windows that are too small. A window of two or three records loses the cost benefit, and you pay the overhead of a batch system.
- Scoring the same event twice. Workers restart and streams redeliver messages. Write scores keyed by event ID so a repeat overwrites the same row instead of adding a duplicate.
- Ignoring feature freshness. Fast scoring does not help if the features come from a table refreshed once a day. The score is only as fresh as its inputs.
- Silent lag. If scoring falls behind the arrival rate, the queue grows and delay increases without any error. Monitor the age of the oldest unscored event.
When to choose this pattern
Pick micro-batch when results must be minutes fresh, no caller needs an immediate reply, and traffic is high enough to fill windows. Pick true real time when a user or system waits on the answer. Pick plain batch when daily or hourly freshness is enough.
Exercise
A fraud team wants scores for card transactions within about 2 minutes of each purchase. No checkout page waits for the score. Traffic is about 500 transactions per second. Which pattern fits, and what window would you start with?
Show answer
Micro-batch fits. Nobody waits on the reply, and the 2-minute freshness target allows grouping. At 500 events per second, a 10-second window gives about 5,000 records per call, which keeps cost low and leaves a wide margin below the 2-minute target. Cap the batch size to bound memory, and monitor the age of the oldest unscored event.
Exercise
Your micro-batch worker crashes and restarts, and the stream redelivers the last 50 events. What happens to the stored scores, and how do you make this safe?
Show answer
Without protection, those 50 events are scored again and may appear twice. Write results keyed by a unique event ID, using an upsert, so a repeated event overwrites its earlier score instead of creating a duplicate.