Sub topic 14
Choosing between batch and real time
This chapter assumes you know basic machine learning vocabulary (training, model, features, prediction), can read Python, and understand HTTP APIs and scheduled jobs. It also assumes you have seen the earlier chapters on batch scoring, online serving, freshness, skew, cost, and hybrid patterns. Here those ideas are turned into a repeatable decision process.
Why a framework helps
Teams often pick a serving pattern by habit. Some default to a REST endpoint because it feels like "real" production. Others default to a nightly job because the data team already runs one. Both habits cause problems. A real-time service built for a use case that only needs daily scores costs more and breaks more often than a scheduled job. A nightly job built for a use case that needs a score within seconds produces stale answers that users notice.
A structured set of questions replaces habit with reasons. The questions below follow the concepts from earlier chapters, and each one narrows the choice.
The decision questions
Ask these in order. Stop early if an answer settles the choice.
- When is the prediction consumed, and who asks for it?
- How fresh must the inputs be?
- Can the features be computed at the moment of the request?
- How many predictions are needed, and how are they distributed over time?
- What does it cost, and what can your team operate?
- What happens when the system fails?
1. When is the prediction consumed?
If a person or system waits for the answer inside a single interaction, you need a response in milliseconds to seconds. Examples are fraud checks at payment time, search ranking, and chat moderation. This points to real time.
If the answer is used later, you can compute it ahead of time. Examples are a weekly email list of customers likely to churn, a daily demand forecast for warehouse planning, and a monthly credit-limit review. This points to batch.
A useful test: ask "what would break if the score arrived an hour later?" If nothing breaks, batch is a candidate.
2. How fresh must the inputs be?
A prediction is only as current as the data behind it. A batch score computed at 02:00 reflects the world at 02:00, and it stays in use until the next run. Define the maximum staleness the business accepts, then compare it to the batch interval.
- If the signal changes slowly (tenure, account age, yearly income), a daily score loses little.
- If the signal changes within a session (the items a user just clicked, the last three card transactions), a daily score misses the point.
Note that freshness depends on the inputs, not on the model. A real-time endpoint that reads a feature table updated once a day is no fresher than a batch job. The system is only as fresh as its slowest input.
3. Can the features be computed at request time?
This question often decides the matter. Some features are cheap to compute for one request: values sent in the request body, or a key lookup in a store. Others need heavy work, such as a 90-day aggregate across millions of event rows, or a join across several large tables.
If a feature cannot be produced within your latency budget, you have three options:
- Precompute it on a schedule and store it for lookup (an online feature store, or a key-value store).
- Precompute the whole prediction (batch).
- Drop or simplify the feature, and accept some accuracy loss.
Also check training-serving skew. If you serve online, the online feature code must match the code that built the training data. If you cannot guarantee that, a batch pipeline that reuses the training feature code can be the safer choice.
4. How many predictions, and how are they spread?
Batch jobs suit large volumes with no per-record deadline, because they can use vectorized scoring and run on temporary machines. Online services suit lower per-request volume with a deadline per request.
Look at the shape of the traffic too. Online traffic is often bursty, so you must provision for peak load while paying for idle time at quiet hours. Batch work is predictable, and you can shift it to cheap hours.
Also count the possible inputs. If you have 2 million customers and need a score for each one, precomputing is cheap. If the input space is open-ended (free text, arbitrary images, a new combination of user and query), you cannot precompute it, and real time is the only option.
5. Cost and operational load
Real time carries extra work: an always-on service, autoscaling, latency monitoring, on-call coverage, and versioned deployments. Batch needs a scheduler, retries, and data checks. Batch is usually simpler to run.
Estimate cost with the utilization view from the cost chapter. The next code block compares a continuously running service against a nightly job. The prices and durations are made-up numbers for illustration. Replace them with your own.
def monthly_cost_always_on(instances, price_per_hour, hours=730):
return instances * price_per_hour * hours
def monthly_cost_batch(machines, price_per_hour, hours_per_run, runs=30):
return machines * price_per_hour * hours_per_run * runs
online = monthly_cost_always_on(instances=2, price_per_hour=0.40)
batch = monthly_cost_batch(machines=4, price_per_hour=0.40, hours_per_run=0.5)
print(f"online: ${online:,.2f} per month")
print(f"batch: ${batch:,.2f} per month")Two instances are the minimum for availability in this example, so the online cost has a floor even when traffic is low. The batch job costs more per hour of machine time but runs for a short window.
6. Failure behavior
Think about what the user sees when the system is down.
- A failed batch run leaves yesterday's scores in place. The system degrades gracefully, as long as you monitor how old the scores are.
- A failed online service returns errors to the caller. You need a timeout, a default score, or a fallback to a precomputed value.
If the consumer cannot tolerate missing predictions, plan the fallback before you choose.
Putting the answers together
The table maps common answer patterns to a recommendation.
| Situation | Typical choice | Reason |
|---|---|---|
| Result used hours or days later, finite set of records | Batch | Cheapest and simplest. Staleness is acceptable. |
| Result needed during a user interaction, inputs come with the request | Real time | A deadline exists, and the request carries the data. |
| Need fast response, but features are heavy aggregates | Hybrid | Precompute slow features or whole scores, serve with a lookup. |
| Need results within minutes, not milliseconds | Micro-batch or near real time | Avoids per-request serving cost while cutting staleness. |
| Most records stable, a few new or changed | Hybrid with live fallback | Batch covers the bulk, live scoring covers the gaps. |
| Open-ended inputs, such as free text | Real time | Cannot be enumerated ahead of time. |
The flowchart below shows the same logic as a path through the questions.
Applying the framework: three cases
Churn outreach. A marketing team emails at-risk customers every Monday. Nobody waits on a score, and the inputs (tenure, spend, tickets) change slowly. The set of customers is finite. Choose batch. The scheduled job from the batch chapter fits well.
Card fraud check. A payment must be approved or declined in under 200 ms. The most important signals are the current transaction and the last few minutes of activity. Choose real time, with a feature store that keeps recent aggregates up to date. A nightly score would miss the pattern entirely.
Product recommendations on a home page. Millions of users, a page that must load fast, and a model that is expensive to run. The candidate list changes slowly, while the last click matters a little. A hybrid design works well: precompute candidates in batch, then re-rank a small set live using session data.
Hybrid with a fallback
When you mix the two, the lookup logic must be explicit about which path produced each score. This helps you debug and measure how often the live path is used.
def get_score(customer_id, precomputed, live_predict, features_for):
score = precomputed.get(customer_id)
if score is not None:
return score, "batch"
return live_predict(features_for(customer_id)), "realtime"Log the second value. If the live path handles a large share of traffic, the batch job is missing records, or the data it uses is too old.
Common mistakes and edge cases
- Choosing real time for prestige. If nobody needs the score within seconds, the endpoint adds cost and failure modes without adding value.
- Ignoring the slowest input. A real-time model fed by a daily-refreshed table is a batch system with extra steps.
- Forgetting new entities. Batch scores do not exist for customers who signed up after the run. Decide the default behavior, or add a live fallback.
- Mixing feature code paths. Separate implementations for training, batch, and online invite skew. Share one definition where you can.
- Silent staleness. A batch job that fails quietly leaves old scores that look valid. Store a score timestamp and alert when it exceeds the limit.
- Treating the choice as permanent. Start with the simplest pattern that meets the requirement. Move to a more complex one when a measured need appears, such as a drop in business value from stale scores.
Summary of the process
- State when and by whom the prediction is consumed.
- Set a maximum staleness for the whole pipeline, including inputs.
- Check whether each feature is available within the latency budget.
- Estimate volume, traffic shape, and cost.
- Plan failure behavior and monitoring.
- Pick the simplest pattern that satisfies all of these. Use hybrid or near-real-time designs only when a pure pattern fails a requirement.
Exercise
A telecom company wants a monthly list of customers likely to cancel, to be used by a retention call team. A second team wants to block suspicious SIM-swap requests while the customer waits on the line. Which serving pattern fits each use case, and what is the main reason for each?
Show answer
The retention list fits batch. The calls happen later, the customer set is finite, and monthly staleness is acceptable, so a scheduled job is cheapest and simplest. The SIM-swap check needs real time. A person waits for the decision, so there is a latency deadline, and the signals (the current request and recent activity) must be fresh. A precomputed score would miss a fraud attempt that has just started.
Exercise
A real-time endpoint scores loan applications. One feature, "average account balance over 12 months", takes 8 seconds to compute from raw transactions, but the latency budget is 300 ms. Name two ways to resolve this and one risk each introduces.
Show answer
Option one: precompute the feature nightly and store it in a key-value or online feature store, then look it up at request time. The risk is staleness, because the value is up to a day old, and skew if the nightly code differs from the training code. Option two: precompute the whole score in batch and serve it by lookup (hybrid). The risk is that new applicants have no precomputed score, so you need a live fallback that does not rely on the slow feature, or a default policy.