Sub topic 11
Automating detection and rollback safely
Earlier chapters covered how to define rollback triggers and how to execute a rollback by hand. This chapter shows how to let software do both, and how to stop that software from causing a second incident.
This chapter assumes you have read the chapters on triggers, the deployment pointer, and verification. It also assumes you can read Python, know what an MLflow model registry alias is, and have a metrics source (such as Prometheus) that reports error rate and latency per model version.
What to automate and what to keep human
Automation is worth building where the decision is fast, the evidence is clear, and the action is cheap to reverse. Moving an alias back to a validated version meets all three conditions. Deciding that a model's accuracy has drifted usually does not, because the evidence arrives late and is ambiguous.
| Step | Automate? | Reason |
|---|---|---|
| Detect a breach of service health thresholds (errors, latency) | Yes | Signals are fast and unambiguous |
| Abort a canary and send traffic back | Yes | The previous version is still running and the action is reversible |
| Move the production alias to a validated version | Yes, with guardrails | Cheap to reverse, but only safe if the target is known good |
| Judge model quality drops that rely on delayed labels | Alert only | Evidence is slow and noisy |
| Roll back across a feature or schema change | No | Needs a person to check compatibility |
| Roll forward with a patched model | No | Needs engineering judgment |
A useful rule is that automation may take the safe, pre-approved action. It should page a human for everything else.
How automated rollback fails
An automated rollback is a production change made without a person watching, so it can fail in its own ways.
- False positives from noise. A single bad minute of metrics triggers a rollback of a healthy model. Require several consecutive breaches.
- Too little traffic. An error rate of 7% on 20 requests means little. Set a minimum request count before any decision.
- Flapping. The system rolls back, the new target also breaches, and a controller that is not limited keeps moving the alias back and forth. Add a cooldown and a daily cap.
- A bad rollback target. The "previous version" may be one that was never validated, or whose features no longer exist. Pick only versions explicitly marked as validated.
- Blame on the wrong cause. If an upstream data source fails, rolling back the model changes nothing. Compare against a baseline, and check that the breach started at the release.
- Missing metrics. If the monitoring system is down, the lack of alerts looks like health. Treat missing data as its own alert, not as success.
- Silent action. If nobody learns that a rollback happened, the team will redeploy the bad version the next morning.
The decision loop
The controller runs on a schedule, reads a snapshot of metrics, and returns one of a small set of outcomes. Only one outcome changes production.
Writing the guard as testable code
Keep the decision logic separate from the code that touches the registry. The decision logic is then a pure function of its inputs and the clock, so you can test it without a cluster.
from dataclasses import dataclass, field
@dataclass
class Snapshot:
requests: int
error_rate: float
baseline_error_rate: float
p95_ms: float
@dataclass
class RollbackGuard:
p95_limit_ms: float = 250.0
max_error_increase: float = 0.02
min_requests: int = 500
breaches_needed: int = 3
cooldown_s: float = 1800.0
max_auto_per_day: int = 2
breaches: int = 0
rollback_times: list = field(default_factory=list)
def breached(self, s: Snapshot) -> bool:
error_regressed = (s.error_rate - s.baseline_error_rate) > self.max_error_increase
too_slow = s.p95_ms > self.p95_limit_ms
return error_regressed or too_slow
def decide(self, s: Snapshot, now: float) -> str:
if s.requests < self.min_requests:
return "insufficient_data"
if not self.breached(s):
self.breaches = 0
return "ok"
self.breaches += 1
if self.breaches < self.breaches_needed:
return "watching"
recent = [t for t in self.rollback_times if now - t < 86400]
in_cooldown = bool(recent) and (now - max(recent)) < self.cooldown_s
if in_cooldown or len(recent) >= self.max_auto_per_day:
return "page_human"
self.rollback_times.append(now)
self.breaches = 0
return "rollback"
snapshots = [
Snapshot(900, 0.03, 0.03, 180),
Snapshot(900, 0.07, 0.03, 180),
Snapshot(100, 0.20, 0.03, 400),
Snapshot(900, 0.08, 0.03, 190),
Snapshot(900, 0.07, 0.03, 200),
Snapshot(900, 0.07, 0.03, 200),
Snapshot(900, 0.07, 0.03, 200),
Snapshot(900, 0.07, 0.03, 200),
]
guard = RollbackGuard()
for i, snap in enumerate(snapshots):
print(i, guard.decide(snap, now=i * 60.0))Running it prints ok, watching, insufficient_data, watching, rollback, watching, watching, page_human, one per line with its index. Three details matter here:
- The snapshot with only 100 requests is ignored, even though its numbers look terrible.
- The breach counter keeps its value across the thin-traffic snapshot, so it neither resets nor grows. Choose this deliberately. Resetting instead would make a flaky traffic pattern hide a real problem.
- After the rollback, the old version breaches too. The cooldown blocks a second automatic action and the controller pages a human instead. If the previous version is also unhealthy, the cause is probably not the model, and further automatic moves would only add churn.
The action: moving the alias with an audit trail
The action should do three things: pick a validated target, record why the change happened, and change the pointer. A dry_run flag lets you run the whole path in staging or in production without effect.
This code assumes your promotion process sets a validated tag on a model version after it passes your checks.
from mlflow import MlflowClient
def last_known_good(client: MlflowClient, name: str, current: str):
versions = client.search_model_versions(f"name='{name}'")
good = [
int(v.version)
for v in versions
if v.tags.get("validated") == "true" and int(v.version) < int(current)
]
return str(max(good)) if good else None
def auto_rollback(name: str, reason: str, dry_run: bool = True):
client = MlflowClient()
current = client.get_model_version_by_alias(name, "production").version
target = last_known_good(client, name, current)
if target is None:
print("No validated earlier version. Paging a human.")
return None
print(f"Rollback {name}: version {current} -> {target}. Reason: {reason}")
if dry_run:
print("Dry run, no change made.")
return target
client.set_model_version_tag(name, current, "rolled_back_reason", reason)
client.set_registered_model_alias(name, "production", target)
return target
auto_rollback("fraud-detector", "error rate +4 points over baseline", dry_run=True)The tag on the failed version is part of the safety design. It keeps the bad release visible in the registry, so nobody promotes it again by accident.
The alias move changes what the registry says, not what the running servers are doing. If your servers cache the model, the controller must also trigger a reload or a restart, and the verification step must confirm that the servers report the target version. Otherwise the controller believes it fixed the incident while the bad model keeps serving.
Letting the release tool do it
For canary releases, you do not have to write the controller yourself. Progressive delivery tools such as Argo Rollouts and Flagger run analysis against your metrics during a canary and abort the release automatically if the analysis fails. Traffic returns to the stable version, which is still running. This is the safest form of automatic rollback, because the previous version never stopped serving and the blast radius is limited to the canary's share of traffic.
A custom controller like the one above fits the cases these tools do not cover: a model released to 100% of traffic, a rollback driven by model-quality signals, or a registry alias that is not tied to a Kubernetes rollout. Use one mechanism per service. Two controllers that both react to the same breach will fight each other.
Guardrails to build in from the start
- Minimum traffic and consecutive breaches. Both are in the code above. Tune them from historical data: choose a window long enough that normal noise rarely crosses the threshold.
- Cooldown and a daily cap. They bound the damage if the logic is wrong.
- A validated-target rule. Only versions with a
validatedtag are eligible. If none exist, the controller pages a human. - A kill switch. A single flag or environment variable turns automatic action off, leaving alerts on. During a manual investigation or a planned migration, the automation must not move things under you.
- Missing-data alerts. Page when the metrics feed is stale or empty. Never treat "no data" as "healthy".
- Notification and audit. Every decision except
okshould be logged with the snapshot that caused it. Every rollback should post to the incident channel with the versions and the reason. - A verification step after the action. Reuse the checks from the verification chapter. A rollback that is not verified has not finished.
Testing the automation
The controller is code that runs rarely and matters a great deal, so test it on purpose.
- Unit tests for
decide. Feed scripted snapshot sequences, as in the example, and assert the outputs. Cover thin traffic, a single spike, a sustained breach, a breach right after a rollback, and the daily cap. - Replay real incidents. Feed past metric history through the guard and check that it would have acted at a sensible time, and that it stayed quiet on days with no incident.
- Staging drills. Deploy a deliberately bad model version to staging and confirm that the whole path works: detection, alias move, server reload, and verification.
- Failure injection. Make the registry call fail and confirm that the controller pages a human instead of retrying forever.
The rehearsal side of this, including post-incident review, belongs to the next chapter.
Exercise
A controller rolled production from version 7 to version 6 at 02:10. At 02:25 the metrics still breach thresholds, and the guard's cooldown is 30 minutes. What should the controller do, and why? Also name one extra check you would add before trusting version 6 as the target.
Show answer
It should page a human and take no further automatic action, because the cooldown blocks a second rollback. If the previous version also breaches, the cause is probably outside the model (for example an upstream data problem), so moving versions again would only add churn. Before trusting version 6 as a target, check that it carries the validated tag and that it is compatible with the current feature pipeline and downstream consumers.
Exercise
Your monitoring system goes down for 20 minutes and the controller receives no snapshots. Why is "do nothing" the wrong design, and what should happen instead?
Show answer
Silence would look the same as a healthy service, so a real incident during the outage would go unnoticed. The controller should treat a stale or empty metrics feed as its own alert and notify a human, without rolling back, since it has no evidence about the model.