Sub topic 13
Monitoring and handling failures
This chapter assumes you know how batch scoring and online serving work, as covered in the earlier chapters. It also assumes you can read Python and know what a scheduled job and an HTTP endpoint are. It covers how each serving pattern fails, what to measure, and how to respond so a failure does not quietly produce wrong predictions.
Why failures look different in each pattern
A batch job and an online service fail in different ways, and people notice them at different times.
- A batch job fails at a known moment, and often nobody is watching. If the job does not run, downstream systems keep reading yesterday's file. Nothing errors. The predictions are simply old.
- An online service fails while a caller is waiting. A timeout or a 500 error is visible within seconds, but only if you are counting those errors.
Both patterns share one more risk: the system keeps running but the predictions are wrong. A feature column arrives full of nulls, or the input data has changed. Nothing crashes, and the scores are still numbers between 0 and 1.
So monitoring has three layers:
- System health: did it run, how long did it take, did it error.
- Data health: are the inputs and outputs shaped the way you expect.
- Model health: are the predictions still useful.
What to measure
| Layer | Batch job | Online service |
|---|---|---|
| System health | Run completed, run duration, output age | Request rate, error rate, latency percentiles (p50, p95, p99) |
| Data health | Input row count, null rate per feature, duplicate IDs | Rejected-request rate, missing-feature rate, feature lookup latency |
| Model health | Score distribution per run, share of rows above threshold | Score distribution per hour, fallback rate |
| Outcome health | Accuracy against labels once they arrive | Same, joined on logged request IDs |
Outcome health lags. For churn, the true label (did the customer leave) may arrive weeks later. Until then, the score distribution is your early warning. If the average score jumps from 0.12 to 0.45 overnight, something changed in the data or the pipeline, even though you cannot yet say the model is wrong.
Use percentiles for latency, not averages. A p99 of 2 seconds means one request in a hundred is slow, and an average of 80 ms hides that.
Handling batch failures
Common batch failures:
- The scheduler did not start the job, or the job crashed partway through.
- Upstream data arrived late or arrived empty.
- The job finished but wrote a partial or corrupt file.
- The job ran on time but a feature column was silently null for many rows.
The most useful habit is to validate before publishing. The job should write its output to a temporary path, check it, and only then move it into the location downstream systems read. A failed check then leaves the previous good file in place rather than a broken new one.
import os
import pandas as pd
def validate_scores(scores: pd.DataFrame, expected_rows: int) -> None:
"""Raise ValueError if the scored output looks wrong."""
if len(scores) < 0.95 * expected_rows:
raise ValueError(f"Only {len(scores)} rows scored, expected about {expected_rows}")
if scores["customer_id"].duplicated().any():
raise ValueError("Duplicate customer_id values in output")
if scores["churn_score"].isna().any():
raise ValueError("Null scores in output")
if not scores["churn_score"].between(0, 1).all():
raise ValueError("Scores outside the range 0 to 1")
def publish_scores(scores: pd.DataFrame, expected_rows: int, final_path: str) -> None:
validate_scores(scores, expected_rows)
temp_path = final_path + ".tmp"
scores.to_parquet(temp_path)
os.replace(temp_path, final_path) # atomic on the same filesystemos.replace swaps the file in one step on a single filesystem, so a reader never sees a half-written file. On object storage such as S3, a single object write is also all-or-nothing, but a multi-file output is not. For that case, write all the files to a dated folder and then update a small "latest" pointer.
Other batch practices:
- Make runs idempotent. Re-running the job for the same date should overwrite that date's output and give the same result. Then recovery from a crash is just "run it again."
- Put the run date in the output name, as in
scores_2026-11-28.parquet. You can then tell at a glance which day a file belongs to and backfill missed days. - Alert on output age, not only on job failure. A check such as "the newest scores file is older than 26 hours" catches the case where the scheduler itself is down and no failure message was ever sent.
- Keep the last few outputs. If you discover a bad run two days later, you can compare against or restore an earlier one.
Handling online failures
Common online failures:
- The model file fails to load at startup, or the service runs out of memory.
- A dependency, such as a feature store, is slow or down.
- A caller sends malformed or out-of-range input.
- Load rises faster than capacity, and latency climbs for everyone.
- A new model version raises errors or slows responses after a deploy.
The key design question is what the service returns when it cannot produce a prediction. You have four options:
- Return an error and let the caller decide.
- Return a safe default score.
- Return a precomputed batch score, as in the hybrid pattern from the previous chapter.
- Return a score from a simpler model or a rule.
Which is right depends on the use case. A fraud check on a payment may need to fail closed (reject or review). A product recommendation can fall back to a popular-items list. Make the choice explicitly, with the business owner.
import logging
import time
import joblib
from fastapi import FastAPI
from pydantic import BaseModel, Field
logger = logging.getLogger("scoring")
logging.basicConfig(level=logging.INFO)
app = FastAPI()
model = joblib.load("model.joblib")
FALLBACK_SCORE = 0.10
class Features(BaseModel):
tenure_months: float = Field(ge=0)
monthly_spend: float = Field(ge=0)
support_tickets: int = Field(ge=0)
@app.post("/predict")
def predict(features: Features):
start = time.perf_counter()
try:
row = [[features.tenure_months, features.monthly_spend, features.support_tickets]]
score = float(model.predict_proba(row)[0, 1])
source = "model"
except Exception:
logger.exception("prediction failed, using fallback")
score = FALLBACK_SCORE
source = "fallback"
latency_ms = (time.perf_counter() - start) * 1000
logger.info("predict source=%s score=%.4f latency_ms=%.1f", source, score, latency_ms)
return {"churn_score": score, "source": source}Three details matter here. The Field(ge=0) constraints make FastAPI reject impossible inputs with a 422 response before they reach the model. The response includes a source field, so callers and dashboards can tell a real score from a fallback. Every request logs its source and latency, which gives you the fallback rate and latency percentiles.
The diagram shows one request's path through these defenses.
Timeouts, retries, and load
- Set a timeout on every call the service makes, including feature lookups. Without one, a slow dependency ties up worker threads until the whole service stalls.
- Retry only when it is safe and cheap. Scoring is usually read-only, so a retry is safe, but retrying during an overload makes the overload worse. Use a small number of retries with a short, growing delay.
- Limit concurrency or queue length so the service sheds load instead of collapsing. Returning a fast error to some callers is better than a slow response to all of them.
- Roll out new model versions to a small share of traffic first, and compare error rate and latency to the old version before moving all traffic over. Keep the old version ready for a quick rollback.
Detecting silent problems
Some failures produce no errors. Two checks catch most of them.
Input drift means the data going into the model no longer looks like the training data. Compare each feature's recent distribution to a reference from training: the mean, the null rate, and the share of values outside the training range. This ties back to training-serving skew. A feature computed one way in training and another way in serving shows up as a sudden shift the day the new code deploys.
Output drift means the scores themselves have shifted. Track the mean score and the share of scores above your decision threshold, per batch run or per hour online. Set alert bands from a few weeks of normal history. Flag a change that is large relative to normal variation, not a fixed number that you guess at.
When labels arrive, compute real accuracy metrics on the logged predictions. To do that, log a request or customer ID, the model version, the features used, and the score with every prediction. Without those logs you cannot reproduce a bad prediction or evaluate the model later.
A short runbook
Write down, before an incident, what to do for each alert. A minimal version:
- Batch output is stale: check the scheduler, then the upstream data. Re-run the job for the missed date. Tell downstream owners that scores are old until it completes.
- Fallback rate is high: check the model's logs and dependencies. Roll back the latest deploy if it started at deploy time.
- Score distribution shifted: compare input feature distributions to find which feature changed, then trace it to its source.
- Latency rising: check traffic, dependency latency, and instance count. Scale out or shed load.
Exercise
A nightly batch job completes successfully, and its dashboard shows no errors. Two days later, the sales team reports that the scores look the same as last week's. Name two checks that would have caught this, and say what each one measures.
Show answer
First, an output-age check: alert when the newest scores file is older than the expected schedule plus a margin (for example 26 hours for a daily job). It catches the case where the job did not run or wrote to the wrong place. Second, an output distribution or row-level check, such as comparing the mean score and the share of rows above threshold to recent runs, or confirming the output's run date matches today. It catches the case where the job ran but scored stale or unchanged input data.
Exercise
An online churn service returns a fixed fallback score of 0.10 whenever the model call raises an exception. Why can this be dangerous, and what two changes make it safe to keep?
Show answer
It hides failures: callers get a plausible score and see no error, so a broken model can run unnoticed while every decision uses 0.10. Make it safe by (1) labeling each response with its source ("model" or "fallback") and (2) tracking the fallback rate and alerting when it rises above a small threshold. Logging the exception with the model version helps diagnose the cause.