Sub topic 13
Monitoring and handling failures
This chapter assumes you know the basics of batch jobs and online services from earlier chapters. You should also be comfortable with Python and HTTP APIs. Here you will see what to watch in each serving pattern, how each one tends to fail, and how to respond.
Why the two patterns fail differently
A batch job fails loudly or silently, and usually out of sight. A real-time service fails in front of a caller who is waiting.
- A batch job that crashes leaves yesterday's scores in place. Nobody notices until someone asks why the numbers look old.
- A real-time service that crashes returns errors immediately. Callers see the problem within seconds.
Because of this, batch monitoring focuses on whether the job ran and whether its output is sound. Online monitoring focuses on health and speed, measured continuously.
What to monitor
| Concern | Batch job | Online service |
|---|---|---|
| Is it running? | Did the run finish on schedule? | Is the endpoint up? |
| Speed | Total run time | Latency percentiles (p50, p95, p99) |
| Volume | Rows scored versus rows expected | Requests per second, error rate |
| Output quality | Score distribution, null count | Score distribution over a time window |
| Freshness | Age of the newest output file | Age of the features used |
Use latency percentiles instead of the average. A p99 of 2 seconds means 1 request in 100 took at least that long, even if the average looks fine.
Check the output, not just the exit code
A job can exit successfully and still write bad scores. Add checks before publishing results.
import pandas as pd
def validate_scores(scores: pd.DataFrame, expected_rows: int) -> None:
if len(scores) < 0.95 * expected_rows:
raise ValueError(f"Only {len(scores)} of {expected_rows} rows scored")
if scores["churn_score"].isna().any():
raise ValueError("Found missing scores")
if not scores["churn_score"].between(0, 1).all():
raise ValueError("Scores outside the range 0 to 1")
if scores["churn_score"].std() < 1e-6:
raise ValueError("All scores are nearly identical")
demo = pd.DataFrame({"customer_id": [1, 2, 3], "churn_score": [0.1, 0.7, 0.4]})
validate_scores(demo, expected_rows=3)
print("Validation passed")The last check catches a common silent failure. If an upstream feature turns into a constant, such as a column filled with zeros, the model returns almost the same score for everyone.
Common failures and responses
- Missing or late input data. Fail the job and keep the previous output. Alert on output age.
- Partial writes. Write to a temporary path, validate it, then rename it to the final path. Readers never see half a file.
- Bad or missing features in a request. Validate input at the API boundary and return a clear 4xx error. Reject out-of-range values instead of scoring them.
- Slow dependencies. If the online service reads from a feature store, set a timeout and decide what happens when it expires.
- Model load failure. Check the model at startup and refuse to become healthy if it cannot load.
- Drift. The input distribution or the score distribution slowly changes. Compare recent data to a training baseline.
Fallback behavior
When the primary path fails, choose a fallback deliberately.
- Serve the last good batch score and mark it stale.
- Fall back to a simpler rule, such as a business heuristic.
- Return an error and let the caller decide.
The hybrid lookup from the previous chapter already contains this idea. A retry with a short timeout makes the primary path more robust:
import time
def with_retry(fn, attempts=3, delay_seconds=0.2):
for attempt in range(attempts):
try:
return fn()
except TimeoutError:
if attempt == attempts - 1:
raise
time.sleep(delay_seconds * (2 ** attempt))
calls = {"n": 0}
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise TimeoutError("feature store slow")
return 0.42
print(with_retry(flaky))Retries need a limit. Unbounded retries under load can overwhelm a struggling dependency and turn a slow period into an outage.
Decision flow when a failure occurs
Exercise
A nightly batch job exits with status 0, but the downstream dashboard shows every customer with a churn score of 0.31. Name one likely cause and one check that would have caught it before publishing.
Show answer
A likely cause is an upstream feature that became constant or null-filled, so the model gets the same input for every row. A check on the score distribution, such as requiring a minimum standard deviation, would have failed the job before publishing. A check on null counts in the input features would also help.
Exercise
Why is p99 latency more useful than average latency for an online prediction service?
Show answer
The average hides slow outliers. p99 shows the latency that the slowest 1% of requests meet or exceed, which is what the unluckiest callers experience and what often breaks timeouts.