Sub topic 12
Hybrid patterns: precompute with live fallback
Batch and real-time serving each have a weakness. Batch scores go stale and miss new records. Real-time scoring costs more and has to answer within a latency budget. A hybrid design uses both. It precomputes scores for the records you already know about, and it calls the model live for the rest.
This chapter assumes you know how a batch scoring job works and how an online prediction service loads a model and answers one request. It also assumes you have met the ideas of latency, staleness, and offline versus online features from earlier chapters.
The core idea
In a hybrid pattern, a scheduled job scores a large set of records and stores the results in a fast lookup store. At request time, the service reads the stored score first. It runs the model only when no usable stored score exists.
The decision at request time is small:
- Look up the entity (for example, a customer ID) in the precomputed store.
- If a score exists and is fresh enough, return it.
- If not, compute features, call the model, and return the live score.
The code below is the lookup rule in its simplest form.
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"The function returns the score and a label that says where it came from. Keep that label. It is useful for monitoring, and later sections show why.
When the pattern fits
The hybrid pattern works well when three conditions hold.
- Most requests hit known entities. If 95% of lookups are for customers the nightly job already scored, the live path handles only 5% of traffic. That keeps the online fleet small.
- A slightly old score is acceptable. A churn score that is up to 24 hours old is usually fine. A fraud score for a payment happening now is not.
- Some entities are unknown to the batch job. New customers, new products, and records created after the batch ran all need a live path.
It fits poorly when every request carries fresh context that changes the answer, such as the items in a shopping cart. A precomputed score cannot reflect that context, so the live path would handle nearly everything and the batch job would add cost without saving much.
Building the precompute side
The batch half is an ordinary scoring job. It reads the feature table, scores every row, and writes the output. The example below does this for a churn model.
import joblib
import pandas as pd
model = joblib.load("model.joblib")
customers = pd.read_parquet("customers_2026-11-28.parquet")
feature_columns = ["tenure_months", "monthly_spend", "support_tickets"]
customers["churn_score"] = model.predict_proba(customers[feature_columns])[:, 1]
customers[["customer_id", "churn_score"]].to_parquet("scores_2026-11-28.parquet")A Parquet file is fine for analytics, but a service needs fast key-based reads. A hybrid design therefore adds a step that loads the scores into a key-value store such as Redis, DynamoDB, or a similar database. Three details matter here:
- Store a timestamp with each score. The service needs it to decide whether the score is fresh enough.
- Store the model version. After you retrain, old scores come from an older model. Without a version you cannot tell which scores to distrust.
- Load atomically. If the loader overwrites rows one at a time, a request can see a mix of old and new scores. Write to a new table or key prefix, then switch a pointer when the load completes.
Building the live fallback
The live path is a normal online prediction service. It loads the model once at startup and scores one row per request.
import joblib
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
model = joblib.load("model.joblib")
class Features(BaseModel):
tenure_months: float
monthly_spend: float
support_tickets: int
@app.post("/predict")
def predict(features: Features):
row = [[features.tenure_months, features.monthly_spend, features.support_tickets]]
return {"churn_score": float(model.predict_proba(row)[0, 1])}The order of values in row must match the order of feature_columns in the batch job. If the two paths disagree, the same customer can receive different scores depending on which path answered. This is training-serving skew, now showing up between two serving paths. The safest fix is to define the feature list in one shared module that both the batch job and the service import.
Deciding what counts as "fresh enough"
A precomputed score is only useful while it is still trustworthy. Define a maximum age, called a time to live (TTL), and treat anything older as a miss.
The check looks like this:
from datetime import datetime, timedelta, timezone
MAX_AGE = timedelta(hours=26)
def usable(record, now=None):
now = now or datetime.now(timezone.utc)
return record is not None and now - record["scored_at"] <= MAX_AGEThe value 26 hours is chosen on purpose. A nightly job runs every 24 hours, so a limit of exactly 24 hours would turn every score into a miss whenever the job runs a few minutes late. A small margin absorbs normal delay. Set it too wide, though, and a failed batch run goes unnoticed for days because stale scores keep being served.
There are other reasons to treat a stored score as a miss, apart from its age:
- The score was produced by a model version that has been retired.
- Key inputs changed after the batch ran. For example, the customer just filed a complaint, and the support ticket count in the stored score is out of date.
- The score is missing because the batch job failed for that row.
Event-driven invalidation handles the second case. When an important input changes, delete or flag the stored score so the next request takes the live path.
Trade-offs
The table compares the hybrid design with the two pure approaches.
| Property | Pure batch | Pure real time | Hybrid |
|---|---|---|---|
| Request latency | Very low (lookup) | Model plus feature time | Low for hits, higher for misses |
| Handles new entities | No, until next run | Yes | Yes, through the fallback |
| Freshness | As old as last run | Current | Mixed, depends on the path |
| Online capacity needed | Almost none | Sized for peak traffic | Sized for the miss rate, plus headroom |
| Operational parts | One job and a store | One service and feature access | Job, store, service, and the rules between them |
The last row is the main cost. A hybrid system has more parts, and each part can fail. You also have two code paths that must agree, and two kinds of latency to track.
Failure modes
Mixed freshness. Two customers with similar data can get scores of different ages. A downstream consumer that compares scores across customers may see differences that reflect only the path used. If that matters, expose the scored_at time or the path label to the consumer.
Fallback overload. Suppose the batch job fails and the store empties or expires. Every request is now a miss, and the live service receives all traffic at once. Plan for this. Options include keeping the previous day's scores as a last resort, rate limiting the live path, and returning a default value for low-priority callers.
Cache stampede after a model change. If you replace the whole store with scores from a new model version at once and the load fails halfway, the miss rate jumps. The atomic load described earlier prevents this.
Silent divergence. The batch and live paths can drift apart through code changes in only one of them. Run a regular check that scores a sample of customers through both paths and compares the results. A difference above a small tolerance should raise an alert.
Feature availability in the live path. The live path needs the features for an entity it has never seen. For a new customer there may be little history. The fallback must handle missing values the same way training did, for example with the same imputation rule, or the live score will be unreliable.
Monitoring a hybrid service
Track these numbers, split by path where it makes sense:
- Hit rate: the share of requests answered from the precomputed store. A sudden drop usually means the batch job failed or the TTL is too tight.
- Latency per path: report batch-path and live-path latency separately. A combined average hides slow live calls behind many fast lookups, so use percentiles such as p95 and p99 for each path.
- Age of served scores: the distribution of
now - scored_atfor hits. - Batch job freshness: the time of the last successful load, with an alert when it passes your limit.
- Path agreement: the result of the sampled comparison between the two paths.
A worked decision
Take a subscription company that wants churn scores shown in a support agent's screen.
- There are 2 million customers, and agents open about 50,000 customer pages per day.
- Churn risk changes slowly, so a score that is a day old is acceptable.
- About 1,500 new customers sign up each day, and they have no precomputed score until the next run.
Scoring all 2 million customers nightly is cheap compared with keeping a large online fleet. The 1,500 new customers per day are the only gap, and the live fallback covers them with a small service. Hit rate should stay above 95% in this setup, so the live path needs little capacity. This is a good fit for the hybrid pattern.
Now change one fact: the agent screen must reflect a complaint filed five minutes ago. The stored score cannot know about the complaint. You would either invalidate the stored score on that event, so the next view uses the live path, or move to a fully real-time design. Which one is right depends on how often such events happen. Rare events favor invalidation. Frequent events push the miss rate up until the batch job saves little.
Summary
- A hybrid design reads precomputed scores first and calls the model live on a miss.
- It fits when most requests hit known entities and a slightly old score is acceptable.
- Store a timestamp and model version with each score, and load the store atomically.
- Use one shared feature definition for both paths so they cannot drift apart.
- Plan for the case where the store is empty, because the live path then takes all traffic.
- Monitor hit rate, per-path latency, score age, and agreement between paths.
Exercise
A nightly batch job scores all customers and loads the results into a key-value store. The service treats a stored score as fresh if it is at most 24 hours old. After a deploy, the job starts finishing about 20 minutes later each day, and the hit rate falls from 96% to 40% during the early morning hours. What is the likely cause, and how would you fix it?
Show answer
The job now completes more than 24 hours after the previous run's scores were written, so in the gap before the new load finishes, the old scores exceed the 24-hour limit and count as misses. Most requests then fall to the live path. Fix it by setting the maximum age with a margin above the run interval (for example 26 hours), and by alerting on batch job completion time so late runs are caught early. Also check that the live path can handle the extra load if misses do occur.
Exercise
The batch job uses the feature order ["tenuremonths", "monthlyspend", "supporttickets"], but a developer edits the live service so the row is built as [supporttickets, tenuremonths, monthlyspend]. No errors are raised. What happens, and what two practices would catch or prevent it?
Show answer
The model receives values in the wrong columns, so live scores become wrong without any error, and the same customer gets different scores from the two paths. Prevent it by defining the feature list in one shared module that both paths import. Catch it by running a scheduled check that scores a sample of customers through both paths and alerts when the results differ by more than a small tolerance.