TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Rollback, Fallbacks and Model Incidents

Rollback, Fallbacks and Model Incidents

Sooner or later a model release goes wrong. The new version was trained on a broken extract, or it behaves differently on a segment the validation set barely covered, or a feature it depends on stops arriving. At that moment the question is not "why?" but "how fast can we get back to something safe?". The answer is decided long before the incident: by keeping previous versions ready, by making a rollback one small, tested operation, by wrapping the model in fallbacks that work when the model does not, and by a runbook that a tired on-call engineer can follow at 3 a.m. This lesson builds those pieces for the risk-model service and ends with the incident process around them.

Replay and rollback introduced guarded updates and a version history for an online learner. Here the setting is a deployed service with a registry, a deployment system and people on call.

Keep the previous versions ready

A rollback is only fast if the thing you roll back to is still there and still works:

  • Keep N previous versions of the model artifact and everything it needs: the preprocessing, the feature definitions, the container image, the signature (artifacts and signatures). A model file without the matching feature code is not a rollback target. Three to five versions is common; never let a retention job delete the version an alias points to.
  • Roll back by moving a pointer, not by rebuilding. With a model registry, the service loads models:/risk-model@champion; rolling back means moving the champion alias to the previous version and letting the service reload. With deployments, it means redeploying the previous image tag (rollback in CI/CD), or reverting the commit that changed the version in a GitOps repository (GitOps rollback). Either way, the operation is the same one used for every release, so it is exercised daily.
  • Know what is not rolled back. Predictions already served, decisions taken on them, data written by the new version (a new column, a changed cache format) stay. A rollback that needs a data migration in reverse is not a quick rollback; make releases backward compatible.

From scratch: aliases and retention

A registry reduced to its essentials: numbered versions with their gate metrics, aliases that point to versions, a retention rule and an audit log of every alias move.

python · try it yourself
class Registry:
    def __init__(self, keep=3):
        self.versions, self.aliases, self.log, self.keep = {}, {}, [], keep

    def register(self, metrics):
        v = max(self.versions, default=0) + 1
        self.versions[v] = metrics
        self._retain()
        return v

    def set_alias(self, alias, v, reason):
        old = self.aliases.get(alias)
        self.aliases[alias] = v
        self.log.append(f"{alias}: {f'v{old}' if old else 'none'} -> v{v} ({reason})")

    def _retain(self):
        protected = set(self.aliases.values())
        newest = sorted(self.versions)[-self.keep:]
        for v in sorted(self.versions):
            if v not in newest and v not in protected:
                del self.versions[v]                # archive the artifact in real life

reg = Registry(keep=3)
for auc in (0.861, 0.866, 0.870, 0.874):
    v = reg.register({"auc": auc})
    reg.set_alias("champion", v, "passed the gate")
v5 = reg.register({"auc": 0.879})
reg.set_alias("champion", v5, "passed the gate")
print("versions kept:", sorted(reg.versions), " champion:", reg.aliases["champion"])

# incident: v5 approves far too many applicants -> roll back to the previous champion
previous = int(reg.log[-2].split("-> v")[1].split()[0])
reg.set_alias("champion", previous, "rollback: approval rate +15 pts on canary")
reg.set_alias("quarantine", v5, "kept for the investigation")
for v in (6, 7):
    reg.register({"auc": 0.88})               # later candidates arrive
print("versions kept:", sorted(reg.versions), " aliases:", reg.aliases)
print("\n".join(reg.log[-3:]))
versions kept: [3, 4, 5]  champion: 5
versions kept: [4, 5, 6, 7]  aliases: {'champion': 4, 'quarantine': 5}
champion: v4 -> v5 (passed the gate)
champion: v5 -> v4 (rollback: approval rate +15 pts on canary)
quarantine: none -> v5 (kept for the investigation)

After five releases the registry keeps versions 3, 4 and 5, the newest three. The rollback is a single alias move, v5 to v4, and the bad version is kept under a quarantine alias for the investigation instead of being deleted. When versions 6 and 7 arrive, retention keeps four versions, not three: 4 is the champion and 5 is quarantined, so neither may be removed, while version 3, old and unreferenced, goes. The last three log lines are the audit trail of the incident.

Fallbacks: what serves when the model cannot

Rollback takes minutes. Requests arrive every millisecond. Between the two, the service needs a defined answer for every failure, decided per request:

requestvalidate input model v7champion model v6previous rulessimple policy defaultmanual review error, timeout,invalid score fails toono rule kill switch on, or invalid input: skip the models
  • Previous model: the version before the current one, loaded in the same process. Good when the new version fails on some inputs; useless when the cause is shared (a missing feature breaks both).
  • Rules: a simple, explainable policy that business owners have signed off ("decline if debt ratio above 0.6, refer otherwise"). Worse than the model, but predictable.
  • Default: a safe constant answer, chosen per product: "refer to manual review" for credit, "show the most popular items" for a recommender, "allow and flag" or "hold" for fraud, depending on which mistake is cheaper.
  • Kill switch: a feature flag, read at runtime from configuration, that turns the model off and serves the rules for everyone, without a deployment. It is what the on-call engineer flips first when the model misbehaves and the cause is unknown.

Every response records which path served it, so that monitoring sees the fallback rate, and an alert fires when it rises: a fallback that silently serves 30 % of traffic for a week is an outage nobody noticed.

From scratch: a guarded predict

The course's running example, a Pipeline(StandardScaler, LogisticRegression) on make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0), as two versions. Version 7 has a bug: it raises an error on about 5 % of requests and returns NaN for large values of feature 3. The guard validates the input against the training ranges, tries v7, falls back to v6, then to a rule, and honours a kill switch.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_train, y_train, X_live = X[:1500], y[:1500], X[1500:]
v6 = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train[:1000], y_train[:1000])
good_v7 = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)

class BuggyV7:                                   # the release with a bug
    def __init__(self, model, seed=0):
        self.model, self.rng = model, np.random.default_rng(seed)
    def predict_proba(self, x):
        if self.rng.random() < 0.05:
            raise TimeoutError("feature store timeout")
        p = self.model.predict_proba(x)
        return np.where(x[:, [3]] > 1.5, np.nan, p)   # NaN for large feature 3

LO, HI = X_train.min(axis=0), X_train.max(axis=0)
MARGIN = 0.5 * (HI - LO)

def rules(x):                                    # signed-off fallback policy
    return 0.8 if x[0, 1] > 1.0 else 0.3

def guarded_predict(x, primary, previous, kill_switch=False):
    x = np.asarray(x, dtype=float).reshape(1, -1)
    if x.shape[1] != 8 or not np.isfinite(x).all():
        return None, "rejected"
    if ((x < LO - MARGIN) | (x > HI + MARGIN)).any() or kill_switch:
        return rules(x), "rules"
    for name, model in (("v7", primary), ("v6", previous)):
        try:
            p = float(model.predict_proba(x)[0, 1])
        except Exception:
            continue
        if 0.0 <= p <= 1.0:                      # NaN fails this test too
            return p, name
    return rules(x), "rules"

requests = list(X_live[:200]) + [[0.1] * 7, [np.nan] * 8, [50.0] + [0.0] * 7]
for kill in (False, True):
    paths, v7 = {}, BuggyV7(good_v7)
    for x in requests:
        _, path = guarded_predict(x, v7, v6, kill_switch=kill)
        paths[path] = paths.get(path, 0) + 1
    print(f"kill switch {'on ' if kill else 'off'}: {dict(sorted(paths.items()))}")
kill switch off: {'rejected': 2, 'rules': 1, 'v6': 27, 'v7': 173}
kill switch on : {'rejected': 2, 'rules': 201}

With the switch off, v7 answers 173 of the 203 requests and v6 catches 27, the requests on which v7 timed out or returned NaN. One request, the one with a value of 50 in feature 0, far outside the training range, goes to the rules: no model is trusted outside the range it was trained on. Two malformed requests (7 values, and NaN inputs) are rejected. With the kill switch on, all 201 valid requests are served by the rules, without a deployment. In production, 27 fallbacks out of 200 (13.5 %) would itself be an alert.

Automatic rollback

During a canary, the new version serves a small share of traffic while a watchdog compares it with the champion on label-free signals, window by window, and rolls back without waiting for a human when a guardrail breaks. Labels are too slow for this; the guardrails are the monitoring layers that react in minutes.

python · try it yourself
import numpy as np

rng = np.random.default_rng(3)
GUARDRAILS = {"invalid_rate": 0.005, "approval_gap": 0.08, "p95_ratio": 1.5}

def window(version, w):
    """Simulated 10-minute window of metrics; the canary degrades from window 4."""
    n = 500
    bad = version == "canary" and w >= 4
    approval = rng.binomial(n, 0.78 if bad else 0.67) / n
    invalid = rng.binomial(n, 0.004 if bad else 0.0) / n
    p95 = rng.normal(70, 3) * (1.2 if version == "canary" else 1.0)
    return {"approval": approval, "invalid_rate": invalid, "p95": p95}

aliases = {"champion": 6, "canary": 7}
for w in range(1, 8):
    champ, canary = window("champion", w), window("canary", w)
    breaches = []
    if canary["invalid_rate"] > GUARDRAILS["invalid_rate"]:
        breaches.append(f"invalid {canary['invalid_rate']:.3f}")
    if abs(canary["approval"] - champ["approval"]) > GUARDRAILS["approval_gap"]:
        breaches.append(f"approval {canary['approval']:.3f} vs {champ['approval']:.3f}")
    if canary["p95"] > GUARDRAILS["p95_ratio"] * champ["p95"]:
        breaches.append(f"p95 {canary['p95']:.0f} vs {champ['p95']:.0f} ms")
    print(f"window {w}: " + ("; ".join(breaches) if breaches else "ok"))
    if breaches:
        aliases.pop("canary")                     # all traffic back to the champion
        print(f"  ROLLBACK: canary v7 removed, champion stays v{aliases['champion']}; page the owner")
        break
window 1: ok
window 2: ok
window 3: ok
window 4: ok
window 5: approval 0.802 vs 0.650
  ROLLBACK: canary v7 removed, champion stays v6; page the owner

The canary starts to degrade in window 4, but its approval gap stays inside the 0.08 guardrail by chance in that window; in window 5 it reads 0.802 against 0.650, the watchdog removes the canary and pages the owner. Two other observations: the canary's invalid-output rate (0.4 % from window 4) stays below the 0.5 % guardrail, so it never fires, and its latency is 20 % higher throughout but under the 1.5-times limit. Guardrails catch what they are set for; too loose and they catch nothing, too tight and every canary is rolled back on noise. Set them from the spread of the champion's own windows.

The incident process

When an alert fires, a runbook tells the responder what to do. For a model service it should cover, in order:

text
RUNBOOK: risk-model quality alert (approval rate, invalid scores, data quality)
1. Stabilise (minutes, no diagnosis needed)
   - Recent release? Roll back: move alias champion to the previous version (command in the repo).
   - No release, or rollback did not help? Turn on the kill switch: rules for all traffic.
   - Record what you did and when in the incident channel.
2. Scope
   - Since when? Which model version, which segments, which share of traffic?
   - Which decisions were made in that window (request ids from the prediction log)?
3. Diagnose
   - Data quality first: missing rates, ranges, upstream schema changes.
   - Then the model: drift reports, canary comparison, the training data of the new version.
4. Repair and recover
   - Fix the cause; retrain or re-release through the normal gate, never by hand.
   - Decide with the product owner what to do about the affected decisions.
5. Close: open the postmortem.

Stabilise first and diagnose later: a rollback or kill switch is cheap and reversible, while every minute spent investigating with the bad model still serving costs real decisions. Afterwards, a blameless postmortem records the timeline, the impact (how many predictions, which customers), the root cause and the contributing factors, and the actions that make it less likely or less harmful next time: a new data quality check, a missing guardrail, a gate on a segment, a faster rollback. For model incidents, "the impact" often includes decisions that must be revisited (applications re-scored, transactions reviewed), so the prediction log with request ids and versions is part of the recovery, not only of the analysis.

Pitfalls

  • A rollback target that does not run. The previous version needs its feature code and image; test the rollback path, for example by rolling back and forward in staging on every release.
  • Fallbacks nobody watches. Log the path of every response and alert on the fallback rate.
  • A previous model that shares the failure. If a missing feature breaks v7, it breaks v6 too; the rules must not depend on the same feature.
  • A kill switch that needs a deployment. It must be a runtime flag, changeable in seconds by the on-call engineer.
  • Rollback without a record. Every alias move and switch flip goes in an audit log with who, when and why (governance).

Practice

  1. In the guarded predict, with the kill switch on, two requests were still not served by the rules. Which ones, and why is that correct?
  2. In the registry example, why did version 4 survive the retention rule when versions 6 and 7 arrived, and version 3 did not?
  3. Write a guardrail for the canary that does not need labels and would catch a model that suddenly returns the same score for every request.
Answers
  1. The request with 7 values (wrong shape) and the request with NaN values: both are rejected before the kill switch is checked, because no policy, model or rule, should guess on malformed input; the caller gets an error. Every valid request goes to the rules, including the out-of-range one.
  2. Version 4 is the target of the champion alias after the rollback, so it is protected; version 3 was not among the newest three and had no alias. Version 5 is protected by quarantine.
  3. Compare the spread of the canary's scores with the champion's in the same window, for example the standard deviation or the number of distinct rounded scores, and breach if the canary's is below a fraction (say 20 %) of the champion's. A constant output has a standard deviation of zero.

Test yourself

What is the fastest safe action when a new model release misbehaves and the cause is unknown?

  1. Debug the model in production
  2. Retrain immediately
  3. Roll back (move the alias to the previous version) or turn on the kill switch
  4. Wait for labels

Why must every response record which path (model version, fallback, rules) served it?

  1. For billing
  2. So that monitoring can see and alert on the fallback rate, and incidents can be scoped
  3. It is required by HTTP
  4. To make the response larger

Which retention rule is safe for a model registry?

  1. Delete all but the newest version
  2. Keep the newest N versions plus every version an alias points to
  3. Keep only versions with the best AUC
  4. Delete versions older than a week

Why are canary guardrails usually label-free signals?

  1. Labels are inaccurate
  2. Labels arrive too late to stop a bad canary in minutes
  3. Labels are private
  4. Guardrails cannot use numbers