Skip to content
Tech Interview Prep
Technical interview guide

Canary Releases & Rollback for Models

Rolling out a new model version safely: a small traffic slice first, with a fast path back to the previous version.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Amazon SageMaker deployment guardrails, Argo Rollouts, KServe, Kubernetes, and NIST AI RMF guidance current 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-20

Define rollout preflight checks.

Answer

What a strong candidate says first

A rollout preflight check is an automated gate that runs after the candidate is deployed but before any production traffic reaches it. It answers two questions: is this rollout safe to start, and will the old-vs-new comparison be valid? If either answer is no, the rollout does not start.

Assume a canary rollout of a stateless HTTP service: baseline (last-known-good) and candidate both behind a load balancer, SLO of 1% error rate and p99 < 300 ms. The checks fall into three groups (artifact integrity, environment readiness, observability and rollback readiness) and they run in that order because each is cheaper to fail than the next.

CheckProbePass conditionWhat it prevents
Artifact integritycosign verify --key cosign.pub ghcr.io/acme/myapp@sha256:<digest>signature verifies against the digest being deployedTampered or wrong image reaching production
Baseline healthPromQL error ratio over the last 5 min for version="baseline"≤ 0.2%Pre-existing errors attributed to the candidate
Candidate readinesskubectl get pods -l app=myapp,version=candidateevery pod ReadyTraffic to unready pods → 503s
Capacityfree allocatable CPU/memory on nodes after current pods≥ candidate's total requestsCanary starves baseline, latency spikes on both
Rollback pathkubectl rollout undo deployment/myapp --dry-run=serverAPI accepts, RBAC allowsFinding out mid-incident that you can't revert

The dry-run proves the API call and RBAC, not that the revert restores service: that is what a game-day rehearsal is for.

Why preflight, not just watch the canary

A canary comparison is only valid if the baseline is healthy and the metrics are trustworthy. If the baseline is already at 0.5% errors, a candidate at 0.6% looks fine and a candidate at 1.4% looks like a regression when it may not be. Preflight pins the baseline before the comparison starts. Same for metrics: if the candidate's pods don't carry the version label, the canary query returns nothing and you read silence as health.

Worked capacity check

Baseline runs 4 replicas at 500m CPU = 2000m. A full canary doubles that, so the cluster needs 2000m of allocatable CPU free after the baseline is scheduled. Say 3 nodes × 4 vCPU = 12 vCPU allocatable, other workloads hold 8 vCPU, baseline holds 2. Free = 2 vCPU: exactly enough for a full canary and no margin. Either add a node or cap the canary at 50% (2 replicas, 1000m). The check is arithmetic, not a vibe.

Failure modes and detection

  • Baseline health skipped: pre-existing errors get attributed to the candidate and you roll back a good release. Detection: the preflight itself fails and pages on-call with the failing check and the PromQL result.
  • Capacity skipped: canary and baseline compete for CPU, p99 climbs on both, and you can't tell whether the candidate is slow or the node is saturated. Detection: container_cpu_cfs_throttled_seconds_total rising on baseline pods.
  • Rollback rehearsal skipped: you discover during the incident that the previous image was garbage-collected or the migration isn't backward compatible. Detection: only at the worst possible time, which is the point.

When to run a reduced set

Preflight costs 2-5 minutes per rollout plus maintenance. The deciding criterion is blast radius × time-to-revert. A config-only change with no new image, no migration, and a rollback that is a single flag flip: keep baseline health and rollback, skip capacity and migration. A change that can hit all users and takes more than 10 minutes to revert: run everything.

If a check fails

The rollout is blocked before any traffic moves. On-call gets the failing check and its evidence: e.g. baseline error rate 0.5% against a 0.2% threshold, and investigates the baseline first. The goal isn't zero risk; it's a valid comparison and a way out.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-3

Define telemetry preflight and missing-data behavior for rollout.

Answer

Core answer (first 90 seconds). Telemetry preflight is the gate you run before any traffic shift: prove the signals you will use to judge the rollout actually arrive, carry the labels that separate candidate from baseline, and can be joined on the same clock. Missing-data behavior is the policy that decides what the rollout controller does when those signals are absent, late, or stale, and the default must be "unknown," never "healthy."

Two rules make it concrete. A gate signal is usable only if a synthetic request with a known cohort label shows up in the metric within one scrape interval. And absence of candidate errors is not evidence of candidate health: a missing series is unknown, and unknown fails closed for irreversible changes.

Preflight. Send a labeled probe through each fleet, a request carrying x-rollout-cohort: candidate, and assert the label appears in the metric's label set. Then check:

  • Freshness: time() - max(timestamp(http_requests_total{cohort="candidate"})) under three scrape intervals. At a 15s scrape that is 45s; Prometheus's default scrape_interval is 1m, so state the value you actually run.
  • Cardinality: adding a cohort label to a 4k-series metric makes 8k; adding rollout_id with 20 values makes 160k. Measure series count before and after.
  • Denominator: the ratio is sum(rate(errors)) / sum(rate(requests)). If the candidate's request counter is missing, PromQL returns no sample: the panel goes blank, not to zero, and a naive alert never fires.
  • Clock alignment: if a host's clock drifts past one scrape interval, rate() windows interleave and produce phantom spikes.

Missing-data behavior. Classify each signal as gating or informational. Gating signals (error rate, latency, saturation) fail closed: if the candidate's error-rate series is absent for two consecutive 1-minute evaluations, or more than 1% of expected samples are missing in a 5-minute window, pause the rollout. Informational signals fail open with a logged warning. Prometheus's query lookback delta (default 5m) keeps returning the last sample for up to five minutes after a pipeline dies, so a dashboard shows a flat line rather than a gap: detect the absence explicitly:

PROMQL
absent(rate(http_requests_total{cohort="candidate"}[5m])) == 1

Failure modes and detection.

failuresymptomdetection
exporter up, scrape target downno candidate samplesup{job="candidate"} == 0
relabeling drops cohortprobe label missingpreflight label assertion
denominator collapseratio panel blankabsent(rate(requests{cohort="candidate"}[5m]))
cardinality blowupscrape duration and TSDB memory climbseries count per metric
clock skewspurious rate spikessample timestamp vs time() at ingest

Trade-offs. Fail-closed costs rollout velocity and produces false pauses during telemetry outages; fail-open keeps velocity but can promote a broken candidate. Decide by reversibility and blast radius: a reversible config change on a small cohort can fail open with a manual check; a schema migration or backfill fails closed. Shadow deployment sidesteps the gate: no user traffic, so missing data delays the comparison rather than the decision.

Keep the probe results and the raw samples behind each gate decision for the rollout window; redact request bodies.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Define the rollback unit for an ML serving release.

Answer

The rollback unit is one immutable manifest, not the model file.

The rule I'd state first: anything that can change a prediction, or change whether you can serve one, belongs in the unit. Anything the request path writes does not: that needs a compensating action instead.

So the unit is a content-addressed release manifest. Every field is a digest or an immutable version, never a mutable tag:

fieldexamplewhy it's in the unit
model artifacts3://models/ranker/2024-06-11-a3f9/, sha256 9c1f…weights change outputs
registry versionMLflow registered model ranker v42integer, immutable once created
preprocessingtransform git SHA 7d2a1c9, Feast feature view user_ctr_v3train/serve skew
tokenizertokenizer.json sha256 4b8e…token-id drift silently rewrites inputs
runtime imageserve:2.14.0@sha256:ab12…digest, not :latest
librariestorch 2.3.1, CUDA 12.1, onnxruntime 1.18.0kernel and opset differences
policydecision threshold 0.42, blocklist v9business rules, not model
endpoint configKServe InferenceService revision 17: min 4 / max 40 replicas, A10Gcapacity
schemasrequest/response JSON schema v3caller contract
dependent APIspricing-svc v2.7.0upstream feature source

Rollback automation selects this whole unit, pre-flights it, warms it, then shifts traffic. A worked trace, ranker v43 → v42, illustrative timings on a 4-replica A10G pool:

  • t+0:00 quality alert fires (CTR −6% on a 5% canary). On-call triggers rollback; automation reads the v42 manifest.
  • t+0:05 compatibility pre-flight: v42 needs feature view user_ctr_v3, still live → pass. Had v43 cut over to v4, the rollback blocks here, not halfway through.
  • t+0:10 capacity pre-flight: v42 needs 4 A10G; 6 free → pass.
  • t+0:12 image digest already on the node → 0 s pull. Cold node: ~90 s.
  • t+0:12–0:52 load and warm (40 s for this model).
  • t+0:52 shift 5% of traffic, replay the 200-sample golden set stored alongside the manifest; 198/200 within tolerance → promote.
  • t+1:00 100% traffic. Warm path ≈ 60 s; cold path ≈ 2.5 min.

The golden set is the part people skip. Without it, a rollback that loads the wrong tokenizer looks healthy (pods Ready, latency fine) and you learn otherwise from the metric three hours later.

Failure modes, with how you catch them:

  1. Mutable tag. serve:latest is overwritten between test and rollback. Detect: compare the running pod's imageID (kubectl get pod -o jsonpath='{.status.containerStatuses[0].imageID}') to the manifest digest. Cost: you roll back to an image you never tested, silently.
  2. Half-rollback. Weights revert, transform doesn't. Detect: golden-set diff, or a drift monitor keyed on the transform version. Cost: a quality drop that looks like a model bug and burns the incident.
  3. Capacity. Target needs more GPU than is free. Detect: pre-flight; skip it and pods go Pending, serving 503s during the incident.
  4. Cold warm-up. Shifting 100% to a cold model adds ~40 s of latency spike. Detect: latency histogram during the shift. Cost: SLO burn on top of the incident.
  5. Schema skew. v42 expects response schema v2, callers moved to v3. Detect: contract test in pre-flight.

Narrow or wide? The deciding criterion is the manifest diff: roll back the smallest set of fields that covers every difference between current and target. If only model artifact differs (a plain retrain, same transform, same image digest) roll back weights alone; that's a 60-second operation. If runtime image, preprocessing, or tokenizer differ, roll back the whole unit, because any subset produces a combination that never existed in testing. Keep the last five manifests so you can go back two releases, not one.

Data and side effects sit outside the unit. A migration that added a column or rewrote the feature store isn't undone by shifting traffic. Either make migrations additive and dual-write so v42 can still read, or accept that rollback is forward-only and you fix forward. Sent notifications, placed bids, cache writes: compensation, not rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design an auditable rollout state machine.

Answer

Assumptions I'd state up front. The rollout is a controller reconciling a desired release against observed cluster state. The actors are CI, a human operator, and the controller itself. "Auditable" means any transition can be reconstructed from durable records alone, without reading controller logs, so the record, not the log, is the evidence.

Core answer. Model two orthogonal things, not one enum. A phase says where the rollout is; a reason says why it stopped. Collapsing them is what makes these systems unauditable: "inconclusive" is not a place, it is an analysis outcome, and if you make it a state you can no longer tell whether the rollout is still moving or waiting on a human.

Phases: Pending, Preflight, Shadow, Canary, Analyzing, Paused, RollingBack, and terminal Promoted / RolledBack / Failed. Every transition is guarded, and every guard is evaluated against observed state, not against the command that arrived.

That is the mechanism that makes it safe: the controller is level-triggered. A command writes an absolute intent ("desired canary weight = 25%"), never a delta ("advance one step"). The controller reads current state, computes the next state, and writes it under an optimistic-concurrency precondition. Replaying an absolute intent is a no-op by construction. Idempotency keys dedupe the audit log; the concurrency token is what actually prevents a double advance.

phaseguard to entermax durationon timeout
Pendingrelease ID resolved to an image digest5 mfail (nothing to roll back)
Preflightconfig validated, quota checked10 mfail
Shadowmirror tap attached, 0% prod traffic30 mroll back
Canary step nprevious step healthy for one full interval15 mroll back
Analyzingat least one analysis sample reported2× worst-case analysis windowpause
Pausedhuman ack or scoped override4 hroll back
RollingBack—15 mfail and page

Kubernetes Deployment is the precedent for the timeout column: progressDeadlineSeconds defaults to 600 s and flips the rollout to ProgressDeadlineExceeded rather than leaving it hanging.

Trace: two identical promote commands, key promote-7f3a, 400 ms apart, both meaning "desired step = 4".

  • t=0.000: controller reads the rollout: resourceVersion 8812, phase Canary, step 3.
  • t=0.010: writes step 4 with precondition resourceVersion=8812, and inserts the audit row (rollout_id, key='promote-7f3a', from=3, to=4) in the same transaction. Commit → resourceVersion 8813.
  • t=0.400: second command arrives. Controller reads 8813, sees desired step already 4, writes nothing, logs nothing.

If the two had raced, the loser's write fails the precondition with a 409 and the unique index on (rollout_id, idempotency_key) rejects the duplicate audit row. Had the command been "increment step", the second arrival would have taken 4→5 and shipped a step nobody asked for.

Timeout arithmetic. With a 30 s analysis interval and a 5-consecutive-failure threshold, the analysis concludes in about 2.5 minutes worst case. Set the Analyzing max duration to 2× that (5 minutes) so a slow-but-working provider does not trip the timeout before the analysis itself would have finished. The timeout action for Analyzing is Pause, never Promote: an analysis that never reported is missing evidence, not passing evidence.

Failure modes and how they are detected.

  • Analysis provider down. The rollout sits in Analyzing. Detect by the age of the last analysis sample exceeding 2× the interval. Action: pause and page. Cost: MTTR grows by the human ack time. That is the price of refusing to promote on missing evidence.
  • Split brain. Leader-election flap leaves two controllers reconciling one rollout. Detect two distinct writer identities in the audit log within the same second, or a spike in resourceVersion conflicts. The precondition turns a split brain into a 409 storm instead of a double advance.
  • Override expiry evaluated client-side. An expired override keeps working because the client clock lags. Store issued_at and expires_at and evaluate expiry in the controller against server time.
  • Audit gap. If the state write and the audit write are separate transactions, a crash between them advances the rollout with no record. Fix: same transaction, or make the event log the source of truth and the phase a projection.

Trade-offs. Reconcile-from-observed versus event-sourced: reconciliation is self-healing and idempotent by construction but loses the "why" unless you also write events; event sourcing gives a perfect audit and replay, at the cost of owning schema evolution and replay correctness. Pick reconciliation when the rollout is already a Kubernetes controller; pick event-sourced when the audit must survive across systems and the controller state is just a projection.

Auto-rollback versus pause-and-page: auto-rollback cuts MTTR to seconds but fires on noise. If your error-rate metric's noise floor is within 2× the regression you are trying to catch, it will thrash: pause instead. And do not auto-roll-back when the rollback itself is unsafe: a forward-only schema migration already applied means reverting the binary leaves the data ahead of the code.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Validate traffic allocation and exposure during a canary.

Answer

Assumptions I'd state first: canary is 10% of traffic, assigned by a stable unit id (user or tenant), sticky across sessions, and exposure is logged at the moment the variant is actually applied. After routing and flag evaluation, not at request receipt. If any of those is false, the checks below change, so I'd confirm them before trusting any share comparison.

The core answer: there are three shares, and they must be compared in order, because each one localizes a different failure.

  1. Configured: what the flag says (10% / 90%).
  2. Routed: what the load balancer or flag SDK actually sent to the candidate backend.
  3. Exposed: what the client logged as having received the variant.

Configured vs routed catches delivery failures (health checks, fallback, capacity). Routed vs exposed catches logging gaps and cache/proxy contamination. Exposed vs configured is the sample-ratio-mismatch (SRM) test: a chi-square goodness-of-fit on the observed split against the configured split, flagged at p < 0.001 (critical value 10.83 at 1 df). Run it overall and per dimension (region, tenant, client version, hour) because a global pass can hide a single-tenant SRM.

Worked check. 200,000 exposures, configured 10% candidate:

armexpectedobserved(obs-exp)²/exp
candidate20,00016,400648
stable180,000183,60072
chi-square720

720 ≫ 10.83, so this is SRM, not noise. The candidate is under-delivering by 18% relative. Before touching outcome metrics, I'd find where the 3,600 missing candidate exposures went: most likely retries or fallback.

Why SRM appears. Assignment is a deterministic hash of the unit id into buckets:

Python
import hashlib

def bucket(unit_id: str, salt: str = "canary-2024-06") -> int:
    h = hashlib.sha256(f"{salt}:{unit_id}".encode()).digest()
    return int.from_bytes(h[:4], "big") % 10_000

# candidate if bucket(unit_id) < 1000  -> 10%

Stickiness is free: the same id always lands in the same bucket. SRM comes from a non-uniform hash (e.g. id % 10 on auto-increment ids, which correlates with signup cohort), from a salt change mid-canary, or from a routing layer that drops some candidate requests before exposure.

Retries distort shares. If the candidate returns 5xx and the client retries into the stable pool, the routed share drops while configured stays at 10%. If retries are logged as fresh exposures, the candidate share inflates instead. Either way, dedupe by request id before counting.

Failure modes and how I'd detect each:

  • Fallback masking: health check pulls the candidate, LB drains it, share silently falls. Detect by comparing configured vs routed, not just exposed.
  • Sticky-assignment break: a user flips variant across sessions. Detect by re-hashing a sample of unit ids and diffing against the logged variant; mismatch rate should be exactly 0.
  • Cache/proxy contamination: a CDN serves a cached candidate response to stable users. Detect by including the variant in the cache key, or by checking response headers against the logged variant.
  • Exposure logging gap: log emitted before flag evaluation. Detect by exposure count vs routed request count; the ratio should be ~1.0.

Trade-off: intention-to-treat vs per-protocol. For the rollout decision, analyze by assigned variant and keep failed candidate requests in the candidate denominator. Dropping them conditions on a post-treatment variable, successful delivery, and makes the candidate look better precisely when it is failing. Per-protocol (as-treated) is a secondary diagnostic for mechanism, not a rollout gate. The cost of ITT is a conservative estimate when failures are common; that conservatism is the point.

One more caveat: don't peek at the SRM p-value continuously without a sequential test. Repeated looks inflate false positives. Fix the horizon or use an always-valid bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design cohort assignment for a model canary and later A/B test.

Answer

I'd start by clarifying what the model changes and what the product state is. For a model canary, the goal is safety: catch regressions in latency, error rate, or quality before full rollout. For an A/B test, the goal is causal lift on business metrics. The randomization unit should match the unit of interference.

Assume a ranking model served via an API, with a stable user_id for logged-in users and a device_id for anonymous. Assume we can log assignment and exposure.

For the canary, randomize by request if the model output is stateless per request (e.g., search ranking). If the model updates user state (e.g., recommendations that persist), randomize by user. For the A/B test, randomize by user to avoid inconsistent experiences and to measure user-level metrics.

Hash a stable identifier with a salt: bucket = hash(experiment + salt + user_id) % 10000. Use SHA-256 or MurmurHash3. For canary, assign bucket < 100 to canary (1%). For A/B, assign bucket < 5000 to treatment (50%). Record assignment at first exposure. Preserve across retries by using the same user_id.

Python
import hashlib

def bucket(user_id: str, experiment: str, salt: str) -> int:
    key = f"{experiment}:{salt}:{user_id}".encode()
    h = int(hashlib.sha256(key).hexdigest(), 16)
    return h % 10000

def in_canary(user_id: str) -> bool:
    return bucket(user_id, "model_v2_canary", "v1") < 100

def in_treatment(user_id: str) -> bool:
    return bucket(user_id, "model_v2_ab", "v1") < 5000

The hash is deterministic: the same user always gets the same bucket. For user_id "u123", the string "model_v2_canary:v1:u123" hashes to a 256-bit integer; modulo 10000 gives a bucket in [0, 9999]. If < 100, the user is in the canary.

Check allocation with a chi-square test on daily traffic. Example:

| Variant | Expected | Observed | Chi-square | p-value | | Control | 50,000 | 49,800 | 1.6 | 0.21 | | Treatment | 50,000 | 50,200 | 1.6 | 0.21 |

p=0.21, no SRM. If p < 0.001, investigate.

Failure modes:

  • SRM: detected by chi-square test on daily traffic. Symptom: one variant gets more users than expected. Cost: invalidates experiment, waste of weeks.
  • Contamination: users in control see treatment due to shared cache or state. Detected by logging model version served per user and checking overlap. Cost: biased estimate, false positives.
  • Hash collisions or non-uniform hashing: detected by checking bucket distribution. Cost: uneven groups, reduced power.
  • Exposure logging missing: detected by comparing assignment logs to exposure logs. Cost: can't compute intent-to-treat vs per-protocol.

Tradeoffs: user-level randomization gives consistent experience but requires more users for the same MDE. For a 1% relative lift on a 10% conversion rate, you need ~1.44M users per variant (alpha=0.05, power=0.8). Request-level randomization gives 10x data if each user makes 10 requests, but it's invalid if the model affects user state. Cluster-level randomization is needed when interference exists (e.g., social network), but fewer clusters mean higher variance.

When not to apply: if the model is a safety-critical change, don't A/B test; canary and roll back on error. If the model is a compliance requirement, randomization may be unethical.

What would change the decision: if interference is high, randomize by cluster. If the model is stateless and you need fast signal, request-level canary is fine, but switch to user-level for the A/B test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a shadow evaluation before a live model canary.

Answer

Assumptions: the model is already serving live traffic, it's registered under an immutable version ID, features come from a feature store, and there's a request-mirroring layer in front of the serving path. Envoy or Istio in most stacks. Under those, shadow evaluation means copying a fraction of real production requests to the candidate out-of-band and discarding its responses. The candidate never touches the user. That's the whole idea; everything below is about not fooling yourself while you do it.

The mechanism matters more than the checklist. In Envoy you attach a mirror policy to the route:

YAML
route:
  cluster: primary
  request_mirror_policies:
    - cluster: candidate_shadow
      runtime_fraction:
        default_value:
          numerator: 5
          denominator: HUNDRED

Two properties make that safe. The mirror is fire-and-forget, the primary response returns without waiting on the candidate, and the shadow cluster gets its own circuit breakers and a short timeout, so a candidate that hangs can't exhaust the primary's connection pool. If your mirroring layer shares the upstream cluster or the connection pool with the primary, you've built a latency bomb, not a shadow.

The hard part is inputs. The candidate must see the same feature vector the baseline saw, not a freshly recomputed one. If the shadow reads the online feature store at mirror time, it can pick up a value written after the baseline's request: that's training/serving skew arriving through the back door, and it shows up as prediction disagreement you'll wrongly blame on the model. Log the baseline's feature vector and replay it. Then alert on the mismatch rate between replayed and recomputed vectors; a nonzero rate means your replay path is broken, not that the model is bad.

Comparisons also drift for boring reasons. Traffic is non-stationary, so a shadow run over a quiet window over-represents whatever slices happen to be active. That's why you need a sample-size number before you start. To detect a 1-point absolute change in a binary agreement metric at 80% power and 5% two-sided alpha you need roughly 39,000 samples per arm: n = 15.7·p(1−p)/δ² with p = 0.5, δ = 0.01. That figure is what tells you whether a 5% mirror fraction over a day covers your rarest slice. Usually it doesn't.

Shadow can answerShadow cannot answer
Does the candidate predict differently on the same input?Would that prediction have been better for the user?
Agreement rate per sliceCTR, conversion, retention
Candidate latency, memory, error rateLong-horizon and feedback-loop effects
Schema and contract violationsAnything needing randomized treatment assignment

That right column is the reason a canary exists. Shadowing only ever observes the baseline's chosen action, so it can never see the counterfactual: what would have happened if the candidate's action had been taken. No amount of shadow traffic answers a business question.

Failure modes to name explicitly. Side effects: the candidate writes to a cache, fires a notification, or logs into the store that trains the next model. Stub the side-effect clients and assert zero writes; a single write is a failed run. Silent capture loss: the mirror drops under load, and you read the missing samples as agreement. Track mirror success rate as a first-class metric and treat missing capture as unknown, never as pass. Slice starvation: per-slice counts below your power threshold mean no conclusion for that slice.

Exit criteria before the canary: mirror capture rate at or above your target on the sampled fraction, zero side-effect writes, prediction agreement within tolerance on the slices you have power for, candidate p99 latency inside budget, and no unexplained feature-vector mismatches. Then move to a live canary with randomized assignment: that's the only instrument that answers the right-hand column.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Choose canary size and baking duration.

Answer

Pick canary size from the sample size needed to detect the smallest regression you care about, then set baking duration to the longer of (a) time to collect that sample and (b) label delay plus analysis window. For a 5% baseline error rate and a 1 percentage point absolute increase, at 95% confidence and 80% power, you need about 7,500 requests per variant. At 100 rps total, a 5% canary gives 5 rps, so that's ~25 minutes of eligible traffic. If labels arrive 24 hours later, the bake is 24 hours plus the analysis window, not 25 minutes. If you can't tolerate 5% exposure, drop to 1% and accept ~2 hours for the immediate metric, but still wait for labels.

The mechanism is a two-sample proportion test. n per variant ≈ 2 (z_{α/2}+z_β)^2 p(1-p) / Δ^2. With α=0.05 and power=0.8, z_{α/2}=1.96, z_β=0.84, sum=2.8, squared=7.84. For p=0.05, Δ=0.01: n ≈ 27.840.0475/0.0001 ≈ 7,450. For p=0.01, Δ=0.005: n ≈ 6,200. For p=0.50, Δ=0.01: n ≈ 39,200. Time is n divided by canary rps.

baseline pMDE Δn per varianttime at 5% of 100 rps
0.050.01~7.5k~25 min
0.010.005~6.2k~21 min
0.500.01~39k~2.2 h

Use stages. A concrete Argo Rollouts canary: setWeight 1, pause 10m; setWeight 5, pause 30m; setWeight 25, pause 1h; setWeight 100. Flagger's analysis block has interval, threshold, maxWeight; its documented defaults are interval 1m, threshold 5, maxWeight 50. Set interval to your metric scrape interval, threshold to 3-5 consecutive failures, maxWeight to 25-50. Istio VirtualService weight does the same split. Promote only when both minimum eligible samples and minimum elapsed time across representative peaks are met. For delayed labels, hold at the canary weight until label lag p95 has passed and the delayed metric is within its guardrail.

Trade-offs: fixed percentage is simple but if traffic drops, sample time stretches; adaptive stepWeight adjusts but can overexpose. Time-based baking is easy but can promote with zero eligible requests; sample-based is statistically sound but can stall. Single-stage exposes more if bad; staged catches early but lengthens rollout. Choose 1% when harm is severe or traffic is high; choose 5-10% when traffic is low and you need samples fast. A 30-minute bake is wrong when labels lag 24 hours. A 1% canary is wrong at 10 rps if you need 7.5k samples: that's 20 hours; either raise to 10% or accept the longer bake.

Failure modes and detection:

failuredetectioncost
underpowered canarypre-computed power; observed CI wider than MDEmiss 1pp regression, ship bad model
bake ends before labelslabel lag p95 > bake duration; proxy vs label divergencesilent quality drop
non-representative sliceper-slice sample count below thresholdregression in one region/device
peeking / early stopsequential test alpha spending; false positive raterollback churn
too long bakerollout duration SLO; queue agestale model, duplicate infra cost

Decision rule: set canary weight so required n arrives within your rollout SLO, cap exposure at the harm you can tolerate, and set bake to max(sample time, label delay + analysis window). Recompute when traffic mix or label lag changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Handle repeated looks and many rollout metrics.

Answer

The 90-second answer

First I'd pin down what "repeated looks" means: is someone reading the dashboard daily and wanting to ship when it's green? Assume yes: a two-arm A/B rollout, one primary success metric, a handful of guardrails, stakeholders asking for daily reads. Then the answer is to fix the decision rule before launch and treat the two metric families separately, because they're tested differently.

For the primary metric, pick one of two regimes. Fixed horizon: one analysis at the precomputed sample size, no peeking. Or group-sequential / always-valid: precompute the boundary so you can look as often as you like. Everything else, the other fifteen metrics, is diagnostic, not a decision.

Why peeking breaks it

Each look is a test at α=0.05. If looks were independent, ten of them give 1 − 0.95¹⁰ ≈ 40% chance of at least one false positive. They aren't independent (they share data), so the real number is smaller but still large: continuous monitoring of a two-sided α=0.05 test pushes the false-positive rate to roughly 30% (Armitage, McPherson & Rowe, 1969). That's the mechanism: you're giving the null many chances to look significant.

The two fixes, with numbers

Group-sequential alpha spending splits α across looks. For five equally spaced looks, two-sided α=0.05:

DesignLook 1 critical ZFinal look ZSample inflation
Pocock2.41 (p≈0.016)2.41~20%
O'Brien–Fleming4.56 (p≈5e-6)2.04 (p≈0.041)~1–3%

OBF spends almost nothing early and is nearly free in sample size, so it's the default when you'd only stop early for a huge effect. Pocock is easier to stop early but costs sample.

Always-valid (mSPRT). A mixture sequential probability ratio test gives a p-value valid at every look, so you can monitor continuously. Cost: you specify a prior on the effect size, and at a fixed sample it's slightly less powerful than a fixed-horizon test.

Many metrics

Predeclare one primary with direction and a practical threshold (e.g. +0.4pp on a 4% baseline). Secondaries are diagnostic. If you must test a family, control the error: Bonferroni at α/m (20 metrics → 0.0025 each) or Benjamini–Hochberg at q=0.10 for FDR. Guardrails are different: one-sided non-inferiority checks where you want high power to catch harm, and they often have low event rates (crash rate, payment failure), so they need a longer window than the primary.

Sizing

Baseline 4%, detect +0.4pp, α=0.05, power 80%: n = 2(1.96+0.84)²·0.04·0.96 / 0.004² ≈ 37,600 per arm. With OBF, ~38,000.

Failure modes

  • Stopping at the first look that crosses 0.05: the classic. Detect by logging every look and its decision.
  • Resetting or re-running after a failed analysis, or sliding the window until it's green. Detect by pre-registering the window and analysis.
  • A guardrail underpowered because it was sized off the primary's event rate.
  • Twenty metrics, no correction, one is "significant."

What changes the decision

A guardrail breach rolls back regardless of the primary. If the primary hasn't crossed the boundary at the final look, you stop: you don't extend. If you genuinely need continuous monitoring, use mSPRT and accept the power cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Choose proxy metrics when labels arrive weeks later.

Answer

Clarify first: how late are labels, how often do you ship, and what action can a proxy trigger? Assume labels land 21 days later, you ship weekly, and you can roll back or retrain. The answer: pick proxies that sit on the causal path from model output to the delayed label, validate them against historical backfills, and use one primary proxy plus guardrails. Do not let a proxy certify long-term quality.

Mechanism: a delayed label Y is caused by model behavior plus confounders. A useful proxy P must be downstream of the model and upstream of Y, or at least an early observable consequence of the same cause. Input validity and service health are not quality proxies; they catch breakage, not degradation. Prediction distribution shift and calibration disagreement are closer: if the model's score distribution moves, the eventual label distribution often moves. Human review and downstream user actions are closest but costlier and slower.

Score candidates on five criteria: validated rank correlation with Y on backfilled data, traffic coverage, lead time versus decision cadence, actionability, and cost per sample. Pick the primary with the best correlation × coverage / cost whose lead time is inside the decision window. Add guardrails for safety, schema, and feature freshness.

Hypothetical backfill, 90 days, delayed label = task success at 21 days:

candidatelead timeSpearman with Ycoveragecostverdict
edit distance to accepted answer1 day0.61100%lowprimary
human review pass rate (2% sample)3 days0.742%200 reviews/dayweekly audit
prediction entropyminutes0.42100%lowguardrail
feature freshness lag > 15 minminutes0.18100%lowguardrail
safety rule violationminuteshigh for harm<0.1%lowhard block

Set thresholds from baseline percentiles. If edit-distance p95 rises more than 20% relative to the concurrent baseline over 7 days, block release. If safety violations exceed 0.1%, block immediately. Keep 5% traffic on the old model as baseline.

Failure modes:

  • Proxy passes, delayed label degrades. Detection: backfill after 21 days shows task success down 4 points. Cost: three weeks of bad model. Mitigation: predefine rollback and keep baseline.
  • Proxy flags benign drift. Detection: false block rate >10% on historical backfill. Cost: release velocity drops and alerts get ignored. Mitigation: set threshold at baseline p99, not p95.
  • Human review sampling bias. Detection: review sample PSI >0.2 versus random traffic. Cost: correlation overestimated. Mitigation: stratified random sample.
  • Feature freshness green but quality drops. Detection: freshness lag <15 min while prediction entropy p95 rises 30%. Cost: silent degradation. Mitigation: combine freshness with disagreement guardrail.

Trade-offs: human review has the highest correlation but low coverage and high cost; use it to audit, not to gate every release. Downstream outcomes are causal but confounded by UI and seasonality; validate across slices. Distribution shift is cheap and fast but noisy; it catches drift, not correctness. Safety rules are precise but rare; they block harm, not quality. The deciding rule: primary proxy must be validated on backfill, cover the traffic you ship to, and lead the decision by at least one cadence. If no candidate clears 0.5 rank correlation, do not ship on proxies alone; hold the release or run a canary with human review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design a baseline comparison resistant to confounding.

Answer

Core answer (first 90 seconds). Assume an online service, a candidate build, and a metric like p99 latency or error rate. I'd run a concurrent A/B: split live traffic 50/50 at the request level, keep the baseline on the current build, and hold both arms to the same eligibility rules, time window, regions and request mix. Randomize on a stable key, request ID or user ID, so a request cannot flip arms mid-flight. Before reading any metric, check the split itself: a sample-ratio mismatch means the comparison is already broken. Then compare identical metric definitions and denominators, and stratify the slices that matter (region, endpoint, client version). Historical baselines are context only; they cannot separate a candidate effect from a demand or seasonal shift.

Why each step removes a specific confound.

ConfoundHow it biases the deltaControlDetection signal
Time / seasonalitydemand moves between windowsboth arms share the same windowA/A arm drift
Assignment biasnon-random split correlates with heavy usershash on stable request IDSRM chi-square, p < 0.001
Shared dependencyboth arms hit the same DB; its slowdown moves bothmeasure the dependency separatelydependency p99 moves in both arms
Metric driftdifferent denominators inflate one sideone definition, one denominatorrequest-count reconciliation
Interferencecandidate saturates a shared poolisolate or use a holdoutpool saturation in one arm only

Sizing the test. For a tail metric, don't compare p99 directly: compare the fraction of requests over a threshold. Baseline: 1.0% of requests exceed 300 ms. To detect a 10% relative change (to 1.1%) at alpha 0.05 and 80% power: n per arm ≈ (1.96 + 0.84)² × [0.01·0.99 + 0.011·0.989] / (0.001)² ≈ 163,000. At 20,000 req/min that is ~8 minutes per arm, ~16 minutes total. With 163,000 per arm, a 1% assignment imbalance (164,630 vs 161,370) gives chi-square ≈ 28, p < 1e-6; the p < 0.001 gate fires at roughly a 0.6% skew.

Failure modes and how you catch them.

  • SRM from an assignment bug: hashing on a field that differs between builds (e.g. a new header) splits arms unevenly. Caught by the chi-square gate above; cost is a wasted run, so check it in the first minutes, not at the end.
  • Shared-infrastructure interference: candidate and baseline share a connection pool or cache. If the dependency's own p99 rises in both arms, the delta is contaminated and you cannot attribute it; isolate the dependency or run a holdout.
  • A/A noise floor: run an A/A first. If A/A shows a 2% p99 swing, a 5% effect is not credible and you need more samples or a tighter metric.
  • Denominator drift: per-request vs per-session counts. Reconcile total request counts across arms before trusting any ratio.

Trade-offs and deciding criteria. A concurrent baseline costs capacity: you hold half your traffic on the old build for the duration, so you cannot ship to 100% until the test closes. A/A variance sets the smallest effect you can defend. When the change is global or irreversible (a schema migration, a third-party upgrade, a config that cannot be split) a pre/post is the only option; then use a matched historical window and difference-in-differences against a control region. If assignment can be randomized at the request level, concurrent A/B wins; if it cannot, interrupted time series with a control series is the fallback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Explain when a canary result must not be reported as an experiment.

Answer

Short answer. A canary result must not be reported as a treatment effect whenever the canary's design breaks an assumption a causal estimate needs: a stable randomized unit, concurrent uncontaminated control, a metric and horizon fixed before data collection, and an analysis that does not condition on the outcome. A canary is built to limit blast radius, and each of those safety properties is a way of violating one of those assumptions. Report it as a guardrail result, "the change did not trip the error-rate or latency guardrail at 5% of traffic", and stop there.

Why the properties bias the estimate. Take a service with 10% baseline checkout conversion, a canary ramping 1% → 5% → 25% → 100% over a day, and a dashboard someone reads hourly.

canary propertyassumption it breakswhat it does to the estimate
progressive ramptreatment and control observed over the same periodtreatment is exposed later; any time trend (traffic mix, another team's deploy, weekday) lands in the effect
operator-selected cohort (one region, internal dogfood)random assignmentselection on covariates correlated with the outcome
stop on guardrail breachanalysis independent of the outcomethe estimate is conditioned on the signal being measured; only canaries that did not trip produce a "result"
hourly dashboard readsfixed sample size or valid sequential designrepeated looks inflate false positives
shared backend, cache, or downstream serviceno interference (SUTVA)control is partly treated; the contrast is diluted

The stopping rule is the sharpest. If the canary halts when p99 latency crosses 300 ms, the surviving sample is the sample that did not cross: you have selected on the outcome, and the remaining difference is not an effect estimate.

Power arithmetic. With 10% baseline conversion, two-sided α=0.05, 80% power, detecting a 1% relative lift (0.1 percentage points) needs about 1.4M users per arm: 2·(1.96+0.84)²·0.09 / 0.001² ≈ 1.41M. A 1% canary running two hours might deliver 5,000 treated users against a much larger control; the 95% interval on the difference is then about ±0.8 percentage points: wider than the effect you hoped to see. A canary that size can rule out a catastrophic regression; it cannot estimate a lift.

Peeking. Twenty independent looks at α=0.05 give about a 64% chance of at least one false positive (1−0.95²⁰). Real sequential looks are correlated, so the true rate is lower, but still far above 5%. If the canary dashboard was read daily and the "result" is the day it went green, that number is not a p-value.

When it is acceptable. If the canary is genuinely randomized at a stable unit, has a concurrent holdback, a metric and horizon fixed before launch, and either a fixed end date or a pre-registered sequential boundary, then it is an experiment that happens to be small: report it with the wide interval and say so. If user-level randomization is impossible (a shared database, a CDN config), the credible alternatives are switchback or stepped-wedge designs, or a difference-in-differences against a pre-period; each carries its own assumption, and none of them is "the canary looked fine."

Detection. Compare canary and control on the pre-period: divergence before the change means the comparison is broken. Check the experiment log for unplanned looks. Run an A/A holdback, if it shows a difference, you have interference. And check whether the analysis window ends at a guardrail crossing; if it does, label it "stopped for safety," not "no effect."

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Protect small but high-risk slices during rollout.

Answer

Assumptions. A change is ramping to a service doing ~500k sessions/day. "Protect" means: the slice has its own guardrail metric with a pre-agreed non-inferiority margin, and the ramp does not advance past a stage while that guardrail is breached. Whatever the aggregate says. The slice is named before launch from a failure-mode analysis (which users does this change plausibly harm?), not from a dashboard afterwards.

Core answer. Give the slice its own guardrail and gate the ramp on it. If the slice is too small to power, don't randomize it into the ramp: hold it on baseline and get evidence from shadow/replay or a bounded canary with a hard stop. Report n and confidence intervals per slice, not point estimates.

What you can actually detect. Slice = 0.2% of traffic = 1,000 sessions/day. Baseline payment-failure rate 1.5%. Two-proportion test, α=0.05, 80% power:

  • Detect 1.5% → 3.0% (2x): ~1,530 per arm, ~3 days at 50/50 inside the slice.
  • Detect 1.5% → 1.8% (20% relative): ~28,000 per arm, ~56 days.

The margin you can defend is set by the traffic you have. A 20% relative regression in this slice is not measurable in a normal rollout window, and pretending otherwise is how you ship it.

Why the aggregate won't save you. 1,000 of 500,000 sessions. Slice failure 1.5% → 3.0% adds 15 failures/day. Aggregate failure rate moves 1.500% → 1.503%. The slice can double its harm rate and the top-line number stays flat.

Options.

optionslice exposureevidenceuse when
hold on baselinenonenone from prodsafety metric; change not plausibly beneficial to the slice
shadow / replaynoneoffline, biased if replay traffic differspre-launch, cheap
bounded canary (5% of slice, hard stop)smallcatches large regressions onlyslice too small to power
randomize within slicefull slicepoweredbenefit metric, or slice big enough

Deciding criterion: expected harm × slice size against cost of delay, and whether the change is plausibly a fix for that slice, in which case withholding it also costs something.

Failure modes.

  • Slice guardrail fires, aggregate looks fine, ship anyway. Detect: wire the slice guardrail to auto-halt, not to a dashboard. Cost: 3 days × 15 extra failures/day ≈ 45 failed payments.
  • Multiplicity: 40 slices at α=0.05 gives ~2 false alarms per experiment. Detect: pre-register slices; Holm-Bonferroni or partial pooling (shrink slice estimates toward the global mean). Cost: false halt, ~1 week delay.
  • Simpson's paradox from mix shift: aggregate improves while every slice worsens because the ramp changed traffic composition. Detect: sample-ratio-mismatch check plus per-slice deltas.
  • Underpowered slice read as "no harm". Detect: report the CI. [−0.5pp, +3pp] is not evidence of safety.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design technical and model-quality rollout guardrails.

Answer

Assume a canary: 1% of traffic to the candidate, 99% to the current production version, split by a stable hash of user ID so a user stays in one arm. The guardrail set has three tiers, and each tier gets a different decision rule because they fail at different speeds.

Tier 1: technical, auto-rollback. Watch candidate-scoped p99 latency, 5xx rate, deadline-miss rate, queue depth, GPU saturation, cold-start rate, and cost per 1k requests. Compare candidate to baseline over the same window, never to a fleet average: at 1% traffic the candidate is invisible in a fleet number. Roll back automatically when candidate 5xx exceeds baseline by 0.5 percentage points absolute for 5 consecutive minutes, or p99 latency exceeds 1.5x baseline for 10 minutes. These signals are fast and low-variance, so you need a threshold and a window, not a hypothesis test.

Tier 2: model-quality proxies, alert. Schema validity, feature freshness (max staleness), prediction distribution shift, safety-policy violation rate, and disagreement with the baseline. Disagreement is the one that earns its keep: shadow-score the candidate on a sample of live requests, log both outputs, and alert when the disagreement rate on high-confidence baseline predictions exceeds 5%. That catches a model that is confidently wrong in a new way before any labels arrive. For distribution shift, PSI above 0.2 on the top 20 features is a reasonable alert line; it is a heuristic, not a p-value.

Tier 3: delayed outcomes, sequential test. Click-through, conversion, task success, and a calibrated proxy arrive hours to days later and are noisy. Do not peek daily against a fixed p-value; that inflates false positives. Pre-register the looks and spend alpha with O'Brien-Fleming, or use SPRT if you can state a minimum detectable effect. For a 5% baseline conversion and a 1 percentage point absolute drop you want to detect, a fixed-sample two-proportion test at alpha 0.05 and power 0.8 needs about 7,500 users per arm:

n = 2 * (1.96 + 0.84)^2 * p(1-p) / delta^2
  = 2 * 7.84 * 0.05 * 0.95 / 0.01^2
  = 7,448 per arm

Below that denominator, report "insufficient data", not "pass".

TierSignalThreshold / windowMin denominatorMissing data
15xx, p99, saturation+0.5pp for 5 min; 1.5x for 10 min1,000 requestsfreeze, alert
2disagreement, PSI, safety5% disagreement; PSI 0.2500 scored requestsfreeze, alert
3conversion, task successsequential, alpha 0.05, power 0.87,500 per armhold decision

Missing data is the quiet killer. If the feature-freshness or label pipeline is stale, freeze the decision rather than treating null as zero. A guardrail that silently passes on missing data is worse than no guardrail.

Concrete failure modes. Baseline contamination: candidate and baseline share a downstream dependency, both degrade, and the comparison looks healthy. Detect it by monitoring the shared dependency directly, not the ratio. Slice flapping: a critical slice with 200 users will cross thresholds by chance, so require a minimum denominator per slice (500 is a workable floor) before you slice at all. Feedback loop: the model's own decisions change the labels, so outcome metrics drift in both arms. Hold a random 1% of traffic on the old model as a fixed control.

Trade-offs. Guardrails cost engineering time and can block good launches. For an internal tool with no user harm and 100 requests a day, skip the sequential machinery: shadow-evaluate offline, review a sample, ship. For a user-facing ranking or a safety-relevant model, the three tiers above are the floor, and the sequential rule is what keeps you from rolling back on noise.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design the automated rollback trigger for a model canary: which production signals fire a rollback, what thresholds and detection windows apply to each, and how do you debounce or add hysteresis so it doesn't flap between promote and roll back?

Answer

Two trigger classes, because the signals have different measurement latencies. Hard safety signals (serving errors, latency, guardrail breaches) are observable per request, so they fire in seconds to a minute and roll back unconditionally. Quality signals (drift, delayed-label proxies) need minutes to hours of data and may hold or roll back, but never promote on their own. A trigger is a triple: threshold, detection window, debounce rule. The window is set by how many samples the canary actually sees, not by how much you care about the metric.

signalscopeexample thresholdwindowdebounce
serving error rate (5xx + inference failures)canary revision only≥1% absolute, or ≥3× stable1 min period, 2 periods2 consecutive breaching periods
p99 latencycanary revision only≥2× stable p99, or >800 ms5 min period, 3 periods2 of 3 breaching
guardrail breach (schema violation, PII, toxicity above hard cap)per request1 eventimmediatenone: zero tolerance
input/output drift (PSI vs baseline)sampled batchPSI > 0.215 min2 consecutive windows
delayed quality proxy (thumbs-down, conversion)labelled cohortrelative drop >5%hourssequential test, not a raw threshold

Why 1% and not "any increase": canary at 5% of 200 rps sees 10 rps, so a 1-minute period is 600 requests. Baseline error rate 0.1% gives 0.6 expected errors; a canary at 1% gives ~6, and under Poisson(0.6), P(X≥6) ≈ 4×10⁻⁵. One period already separates them, so requiring two consecutive periods costs almost nothing in detection time. A 0.2% threshold gives 1.2 expected errors against 0.6: indistinguishable in a minute. Separating 0.1pp at 10 rps needs roughly 18,000 requests, about 30 minutes. Set the threshold where the window has power, or lengthen the window.

Hysteresis, in order of how much flapping it removes:

  • Asymmetric thresholds. Roll back at 1% errors; promote only if the canary stays under 0.3% for the whole bake. The gap is the hysteresis band.
  • M-of-N consecutive periods, never a single sample.
  • Cooldown after every traffic step (one full period, or two minutes) so cold-start latency and cache warming don't count as evidence.
  • Latching abort. Argo's abort sets canary weight to 0 and the rollout stays aborted until a new revision or a manual retry; nothing auto-resumes. SageMaker's guardrail rolls back the endpoint and stops the deployment.
  • Minimum dwell between steps, and no re-promotion of the same revision inside the bake window.

yaml apiVersion: argoproj.io/v1alpha1 kind: AnalysisTemplate metadata: {name: canary-safety} spec: metrics:

  • name: error-rate interval: 1m count: 10 failureLimit: 2 # tolerate 2 breaching samples before the run fails consecutiveErrorLimit: 3 # 3 failed Prometheus queries -> fail, not pass successCondition: result[0] < 0.01 failureCondition: result[0] >= 0.01 provider: prometheus: address: http://prometheus.monitoring:9090 query: | sum(rate(http_requests_total{job="model",version="canary",code=~"5.."}[1m])) / sum(rate(http_requests_total{job="model",version="canary"}[1m]))

Validate with dryRun: true before the template is allowed to abort anything.

Failure modes worth naming. An alarm on aggregate service metrics dilutes the canary: at 5% weight a canary with 20% errors moves the aggregate by 1pp, which can sit under the threshold. Filter on the canary revision label. A CloudWatch alarm stuck in INSUFFICIENT_DATA is not OK; SageMaker evaluates alarm state during bake, so a misconfigured metric is a silent pass. A monitoring outage should hold the rollout, not promote it: that is what consecutiveErrorLimit decides. A drift alarm firing because the canary got a non-random slice is an assignment bug, not a model bug. And the trigger is only as good as the rollback unit: shifting traffic back does nothing if the candidate already wrote to a shared feature store or cache.

Record every evaluation and decision (threshold, observed value, window, action) so the abort is auditable after the fact (NIST AI RMF Measure).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Create severity-aware promotion and rollback rules.

Answer

Assumptions first: 30-day SLO window, canary stepping 5% → 25% → 50%, guardrail metrics scraped every 15s, daily release train. A 7-day window or a shadow deployment changes the numbers below, not the tiers.

The rule set

Three tiers, split by what a violation costs, not by how noisy the metric is.

Tier 1: correctness and safety. Cross-tenant exposure, auth bypass, PII in logs, schema corruption, wrong money movement. Any single confirmed instance halts promotion and rolls back immediately; there is no sample-size argument. Detection is a hard assertion, not a statistic: a tenant-isolation check in the canary path, a checksum on output, a row-level ownership assert. One hit is enough because the cost is unbounded and irreversible.

Tier 2: availability and latency. These are budgeted, so spend the budget. A 99.9% 30-day SLO gives 43.2 minutes of error budget. Use the SRE Workbook multiwindow burn rates: 14.4x over 1h, 6x over 6h, 1x over 3d. Promotion rule: the canary advances only while the 1h burn rate stays under 2x; a 1h burn above 14.4x rolls back automatically.

Tier 3: quality and product proxies. CTR, conversion, error-free session rate, ranking relevance. Noisy, so they need a sequential test, not a fixed-horizon p-value. Peeking ten times at a fixed-horizon test pushes the false-positive rate toward 40% (1 − 0.95¹⁰); correlated peeking is lower but still inflated. Use an always-valid confidence sequence or mSPRT, or Argo Rollouts analysis on the lower bound of the interval:

YAML
metrics:
  - name: error-rate
    interval: 1m
    count: 5
    failureLimit: 3
    successCondition: result[0] < 0.01
    provider:
      prometheus:
        query: |
          sum(rate(http_requests_total{job="canary",code=~"5.."}[1m]))
          / sum(rate(http_requests_total{job="canary"}[1m]))

Why overrides expire. An override is a bet that the guardrail is wrong. Without a TTL it becomes permanent policy nobody re-examines. Require a named approver, a reason string, a scope (one metric, one service, one release) and an expiry: 4 hours for a Tier 3 metric, never for Tier 1. Log it; alert when an override is renewed twice.

Worked trace (hypothetical numbers)

Canary at 25%, 15s scrapes.

teventdecision
0:00promote to 25%—
0:04p99 180ms vs 120ms baseline, 1h burn 3.1xhold, no advance
0:11tenant-isolation assert fails on 1 requestTier 1 → roll back now
0:12override requested, reason "known test tenant"denied: Tier 1 has no override

At 0:11 the aggregate p99 was still inside budget. The slice check is what caught it.

Failure modes and how they surface

  • Missing telemetry read as healthy. Detect with up == 0 or absent() on the canary job; fail closed and pause promotion.
  • Aggregate masking a bad slice (Simpson's paradox). Require a minimum sample per slice and all-slices-pass; alert when any slice is red while the aggregate is green.
  • Flaky Tier 3 metric causing a false rollback. Cost is a burned deploy cycle and an hour of on-call. Widen the interval; don't delete the guardrail.
  • Override drift. Query the audit log for overrides past their TTL. That query should return zero.

What would change the decision: a 7-day SLO window (budget drops to ~10 minutes, so burn thresholds tighten), a shadow deployment instead of a live canary (Tier 1 still applies, Tier 2/3 don't), or a release with no rollback path, then the gate moves earlier, into staging.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Govern human and automated rollout authority.

Answer

Core answer (first 90 seconds)

Assume a Kubernetes-based progressive delivery stack (Argo Rollouts or Flagger) with GitOps as the source of truth, humans authenticating to the cluster via OIDC, and a controller that shifts traffic. The governing principle: authority is split by verb, not by role. "Release engineer" is not a permission. create rollout, patch service selector, edit analysis template, override failed analysis, and delete baseline deployment are five separate grants. Whoever can create a release must not automatically be able to delete the baseline that makes rollback possible: that asymmetry is what turns a bad deploy into an outage.

Automation gets its own workload identity (SPIFFE/SPIRE SVID, or a cloud workload identity), never a borrowed human token. It may advance only when a versioned policy object says so and the evidence it reads is attested. Humans get break-glass, but time-boxed and dual-approved.

The grant table

VerbHumanAutomationWhy separate
create releaserelease engineerCI service accountcheap, reversible
shift traffic %release engineercontroller onlythe actual blast radius
edit analysis templateplatform ownernobodyediting the gate defeats the gate
override failed analysis2 distinct approvers, 15 minneverthe exception path
delete baseline capacity2 distinct approversneverremoves rollback

Worked trace: the override path (design, not a vendor default)

  • t=0: on-call runs rollout override --release payments-2024-11-05 --reason "...". The CLI does an OIDC token exchange and receives a 900-second token scoped to patch rollouts in namespace payments only.
  • t=0: the API server audit log (policy level RequestResponse) records user, verb, resource, and the request object carrying the reason annotation.
  • t=0: an admission webhook (OPA/Gatekeeper) checks three things. Two distinct approver subjects in the approval annotation, token TTL ≤ 900s, release ID exists. Any failure returns 403 and no state changes.
  • t=+2s: the controller sees the override annotation, skips the analysis gate, advances traffic 10% → 50%.
  • t=+15min: the token expires and a reconciler strips the override annotation, so the next analysis failure halts the rollout again.

Why dual approval, in numbers. With 40 engineers, single-actor override gives 40 possible actors; requiring two distinct subjects gives 780 unordered pairs: 19.5× more distinct approval pairs, so a single compromised account is no longer sufficient.

Trade-offs. The alternative is one broad deployer role: fewer moving parts, and genuinely fine for a five-person team with one service. Split-verb plus dual approval costs latency: an override that took 30 seconds now waits 5–15 minutes for a second human. Skip the delete-baseline grant when rollback is instant and cheap (stateless blue/green with warm capacity). If you have no second on-call, dual approval becomes a queue; use time-boxed break-glass instead.

Failure modes and detection.

  • Approval fatigue. If overrides are approved 20×/week and >90% are approved within 30 seconds, the gate is decorative. Alert on approval latency.
  • Split brain. Two controllers shifting the same Service selector. Use a coordination.k8s.io/v1 Lease (defaults: leaseDurationSeconds 15, renewDeadline 10, retryPeriod 2) or optimistic concurrency. A patch with a stale resourceVersion returns 409. Detect via Lease holder changes.
  • Break-glass that never ends. The token expires; the override annotation may not. Alert on override annotations older than their TTL.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Choose between blue/green and rolling model deployment.

Answer

Assumptions first. Stateless inference service, N identical replicas, each replica holds one model version on one accelerator, a load balancer that can shift traffic per replica, and a model that takes ~90 s to load from cold storage plus ~10 s of readiness probing (hypothetical, but in the right range for a 7B–70B checkpoint on local NVMe). No request affinity, no KV-cache stickiness across replicas.

Answer: default to rolling when the fleet is large relative to spare capacity and a rollback measured in minutes is acceptable. Choose blue/green when you need a single-command, near-instant full-fleet reversal or side-by-side comparison on identical traffic, and you can pay for a second full fleet for the release window.

Why they differ. Rolling replaces replicas in batches, so during the window both versions serve and the load balancer splits traffic by whatever rule it uses: round-robin means roughly batch/N of requests hit the new version. Rollback is not a flip; it is the same rollout run in reverse, so its RTO is bounded by how many old replicas you already replaced times per-replica load time. Blue/green keeps two complete fleets and cuts over at the load balancer, so rollback is one weight change, seconds, but you hold 2× accelerator capacity for the whole window.

rollingblue/green
spare capacitymaxSurge replicasfull second fleet
mixed-version windowyes, batch-sizednone after cutover
rollback actionroll forward in reverseLB weight flip
rollback RTObatch × (load + readiness)seconds

Arithmetic. 8 replicas, 100 s per replica to load and pass readiness. With maxSurge: 1, maxUnavailable: 0, rollout is 8 × 100 s ≈ 13 min. If you abort after 3 replicas are replaced, rollback is 3 × 100 s ≈ 5 min. Blue/green needs 8 spare GPUs; cutover and rollback are sub-second, and you pay roughly 2× GPU-hours for the window.

YAML
# Kubernetes apps/v1 Deployment; defaults are 25%/25%
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1
    maxUnavailable: 0   # never dip below N serving replicas

Failure modes and how you see them.

  • Mixed-version window. A request lands on a new replica whose response schema or tokenizer changed. Detect by tagging every response with its model version and alerting on per-version 5xx or schema-validation failures: aggregate error rate hides this because only ~1/8 of traffic is affected for ~100 s.
  • Capacity dip. If maxUnavailable > 0 on an already-saturated fleet, serving replicas drop below N, queue depth grows, and time-to-first-token p99 climbs before any error appears. Alert on queue depth and TTFT, not on error rate.
  • Green fails after cutover. Gate the cutover on green passing a canary of real traffic, and keep blue warm with its GPUs held until the bake completes. Releasing blue early turns a rollback into a full cold start.
  • Quota. If cluster quota is exactly N GPUs, blue/green cannot start at all. That is a hard constraint, not a preference.
  • Both. Rollback RTO is bounded by model load time, not by the load balancer. If you need sub-minute rollback, keep a warm standby or shrink the model.

When not to use them. Blue/green is the wrong tool for a 200-replica fleet under tight quota. Rolling is the wrong tool when you need two versions scored on identical traffic for a quality comparison: that is a traffic split, not a deployment strategy, and it can run on top of either.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Plan a rollout containing data and schema changes.

Answer

Assumptions. Postgres 14 primary, two async read replicas, orders at 400M rows and ~3k writes/s peak, two services read it (billing, fulfillment), weekly deploys, no maintenance window. The change: add currency_code, backfill it from legacy currency, cut reads over, then drop currency.

Core answer. Four phases: expand, migrate, cut over, contract. Never combine a schema change with a data change in one deploy, and never let contract run in the same release as cutover.

Phase 1, expand. Additive DDL only, all metadata-only or non-blocking:

SQL
ALTER TABLE orders ADD COLUMN currency_code text;            -- metadata only
ALTER TABLE orders ADD CONSTRAINT orders_cc_nn
  CHECK (currency_code IS NOT NULL) NOT VALID;               -- brief ACCESS EXCLUSIVE
ALTER TABLE orders VALIDATE CONSTRAINT orders_cc_nn;         -- SHARE UPDATE EXCLUSIVE

On PG 11+ ADD COLUMN with a constant default doesn't rewrite the table; on PG 12+ the validated CHECK lets a later SET NOT NULL skip the full scan. Wrap every DDL in SET lock_timeout = '3s' and retry on timeout: otherwise a 30s analytics query ahead of you in the lock queue turns into a site-wide stall.

Phase 2, migrate. Deploy app code that writes both columns behind a flag, then backfill in batches with a checkpoint:

Python
# Python 3.11, psycopg 3
BATCH = 10_000
while True:
    with conn.transaction():
        rows = conn.execute("""
            UPDATE orders SET currency_code = currency
            WHERE id IN (SELECT id FROM orders WHERE currency_code IS NULL
                         ORDER BY id LIMIT %s FOR UPDATE SKIP LOCKED)
            RETURNING id""", (BATCH,)).fetchall()
        if not rows:
            break
        conn.execute("""INSERT INTO backfill_checkpoint(table_name, last_id, updated_at)
                        VALUES ('orders', %s, now())
                        ON CONFLICT (table_name) DO UPDATE
                        SET last_id = EXCLUDED.last_id, updated_at = now()""",
                     (rows[-1][0],))
    time.sleep(0.1)

400M rows / 10k = 40,000 batches; at ~50ms per batch plus 100ms sleep that's ~100 minutes. Drop the sleep and staging showed replica replay_lag climbing to 45s, which means billing reads stale currency and issues invoices in the wrong currency. Alert on replay_lag > 5s and pause the job.

Phase 3, cut over. Flip reads to currency_code via flag, keep dual writes. Reconcile: SELECT count(*) FROM orders WHERE currency_code IS DISTINCT FROM currency must be 0 for a full day before proceeding.

Phase 4, contract. Stop writing currency, wait two full deploys (the rollback window), then ALTER TABLE orders DROP COLUMN currency; under lock_timeout. After this, rolling the app back to the previous release 500s on every request, because the old code selects a column that no longer exists.

PhaseLockRollback
ExpandACCESS EXCLUSIVE, msDROP COLUMN
ValidateSHARE UPDATE EXCLUSIVEnone
Backfillrow locksresume from checkpoint
Cutovernone (flag)flip flag
ContractACCESS EXCLUSIVE, msrestore from backup

Failure modes. (1) DDL queued behind a long query: ACCESS EXCLUSIVE blocks everything behind it, p99 40ms → 30s+; detect via pg_locks and pg_stat_activity wait events, alert on any ACCESS EXCLUSIVE wait over 1s. (2) Unbatched backfill floods WAL and replica lag; detect via pg_stat_replication.replay_lag. (3) Dual-write divergence when a batch job writes only the old column, leaving NULLs in the new one; detect with a nightly count(*) WHERE currency_code IS NULL alert. (4) Contract before the rollback window expires: old code 500s; detect via error rate on the deploy.

Trade-offs. Dual write buys instant rollback at the cost of a reconciliation job and a doubled write path; backfill-then-single-write is simpler but rollback means a second backfill. Pick dual write when the write path is already idempotent and the rollback window is shorter than the backfill. For MySQL, gh-ost or pt-online-schema-change do this without triggers; on Postgres the native path above is enough, and pg_repack is for bloat, not column adds. If the table is under ~1M rows and you have a 5-minute window, skip all of this: one ALTER TABLE ... ADD COLUMN ... NOT NULL DEFAULT is simpler and the expand/contract dance is pure overhead. A type change (int → bigint) is different: it rewrites the table, so you need a shadow column plus a trigger or pg_repack.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design coordinated rollback for a multi-component model pipeline: retrieval, ranker, and feature service: which components must roll back together, how version compatibility between them is pinned, and in what order the rollback executes?

Answer

Start by naming the coupling, because it decides everything else. The ranker consumes features from the feature service and candidates from retrieval. Retrieval's index was built with a specific embedding model; the ranker was trained on that embedding space and that feature schema. Roll back the ranker alone and it scores embeddings it has never seen: no error, no 500, just a silent quality collapse. So the rollback unit is the compatibility set: {embedding model, index build, feature transform version, ranker model}. Components inside it move together; components outside it (a logging sidecar, an additive reranker) can move alone.

Pin compatibility with a release manifest, not with convention. Each artifact is addressed by digest, and the manifest names the contract versions:

componentpinned identitycontract
embedding modelsha256:9f2c…emb-v7
index buildidx-2024-11-03-aemb-v7
feature transformft-31schema-12
rankersha256:41ab…schema-12, emb-v7

The router resolves a single bundle id against this manifest and refuses to pair mismatched contracts: each service advertises its contract version on a health endpoint, and the router drops any backend whose advertised version differs from the manifest. That check is what turns a partial rollback from a silent quality bug into a routing error.

The feature service is the one component that should serve several schema versions at once. Versioned feature namespaces (schema-12 and schema-13 side by side) let the baseline ranker keep reading schema-12 features while the candidate writes schema-13. Never let both write the same keys: a candidate that overwrites shared feature rows poisons the baseline the moment you roll back.

Order of execution, reverse of promotion:

  1. Stop candidate admission. Freeze the canary step; no new traffic, no new writes to candidate namespaces.
  2. Flip the routing pointer to the last-known-good bundle. One atomic change, and it is what actually restores service: every component version resolves from the manifest at once.
  3. Verify baseline serving on real traffic: contract-version match rate, score distribution against the pre-rollout baseline, error rate.
  4. Roll back the expensive stateful piece by alias, not rebuild. The previous index stays online through the whole bake; rollback flips the index alias back. A rebuild is hours, an alias flip is seconds.
  5. Roll back stateless services (ranker, feature service) with the platform's revision mechanism: kubectl rollout undo deployment/ranker returns to the previous ReplicaSet revision, Argo Rollouts abort reverts its canary, but only after the pointer flip, so no request ever sees a mixed set.
  6. Drain in-flight candidate requests and quarantine their outputs; keep candidate artifacts and the manifest for forensics.

Failure modes worth naming. Partial rollback where the pointer flips but the index alias does not: detect via embedding-space drift on a sample of queries. Shared feature keys written by both versions: detect via per-namespace write counters. A rollback that reverts the ranker Deployment but leaves the router pinned to the candidate bundle: detect via contract-version mismatch rate going non-zero. All three are silent; none raises an exception, so each needs its own alarm rather than a log line.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Handle in-flight, asynchronous, and cached results during rollback.

Answer

Assumptions I'd state first: we're rolling back release v2 to v1; v2 wrote results into a shared store and a shared cache; async work runs on a queue with at-least-once delivery; some v2 results are already visible to users. If any of those is false the answer changes, so I'd confirm them before touching anything.

The 60-second answer. Rollback is a data problem before it's a deploy problem. Stop v2 from producing new results, then classify every existing v2 result on two axes: is it already observable to a user, and is it reversible without side effects? In-flight requests that haven't committed can be cancelled and re-run on v1, but only if the handler is idempotent and side-effect-free. Anything that already wrote must be allowed to finish and then reconciled. Async jobs get version-stamped and rejected at the worker, not deleted from the queue. Caches get a new key namespace, not a mass invalidation.

In-flight. The deciding question is whether the response has been committed. If not, cancel and re-run on v1; this is safe only when the handler is idempotent and emits no external side effect. If it already charged a card, sent mail, or wrote a row, cancelling leaves a half-applied operation: let it finish, then reconcile. A late v2 callback must not overwrite a recovered v1 result, so the write path checks the release stamp and drops stale writes.

Async. Don't drain by default. Draining a queue of 12,000 jobs at 400 jobs/s takes 30s (hypothetical figures) during which v2 keeps producing bad results. Instead stamp each job with its release and have workers reject v2 jobs enqueued after the rollback epoch, then re-enqueue on v1. This is only correct if the job is idempotent and re-runnable; a non-idempotent batch write must be drained or quarantined instead.

Cached. Namespace by contract version rather than deleting. Deleting a hot key set causes a thundering herd against the origin; a new prefix lets old entries expire on their own TTL.

Python
# Python 3.12
def result_key(tenant: str, request_id: str, contract: str) -> str:
    return f"{contract}:{tenant}:{request_id}"

Trace: result_key("acme", "r-91", "v2") returns "v2:acme:r-91". After rollback the contract is "v1", so the same request produces "v1:acme:r-91": a different key. The v2 entry is never read again and expires on its TTL. With a 300s TTL the worst-case stale window is 300s; if your staleness budget is shorter than the TTL, you must delete, and you pay the herd.

ClassDefault actionUse it whenWrong when
In-flight, uncommittedCancel, re-run on v1handler idempotent, no side effectsa card was charged or mail sent
In-flight, committedLet finish, reconcileside effects already emitted—
Async jobReject at worker by version stampjob idempotent, re-enqueueablenon-idempotent batch write
Cached entryNew key namespace, expire by TTLTTL within staleness budgetTTL longer than the budget

Failure modes and how I'd detect them. Duplicate side effects from replay show up as duplicate downstream records: detect by counting distinct idempotency keys against emitted effects. A late v2 write overwriting a v1 result shows as a version-stamp mismatch in the store; alert on any write whose stamp predates the rollback epoch. A cache herd shows as an origin QPS spike right after the rollback; watch origin latency, not cache hit rate. Queue backlog that never drains means a worker is still accepting v2 jobs: check the reject counter.

When this is wrong. If v2 and v1 share a result contract, you don't need namespacing or reconciliation at all: just stop v2 and let in-flight work finish. The whole apparatus above exists because the contract changed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Handle a rollout stuck between traffic steps.

Answer

First thing I'd establish: which controller owns this rollout, and whether traffic is actually where the controller thinks it is. I'll assume Argo Rollouts 1.x driving an Istio VirtualService, canary steps 20 → 50 → 100 with 5- and 10-minute pauses, and a Prometheus AnalysisRun on 5xx rate. On Flagger the shape is the same, just with interval, threshold and maxWeight as the knobs.

The direct answer: freeze the rollout at its current weight, find which gate is unresolved, and only then choose hold or rollback. Don't abort reflexively. Abort sets canary weight to 0 and scales the canary ReplicaSet down, which destroys the evidence you need if the stall turns out to be a controller bug rather than a bad release.

Why it wedges: the rollout controller is level-triggered. It reads the current step index, writes the desired weight into the VirtualService, then blocks on that step's gate: a pause timer expiring, an AnalysisRun reaching Successful, or the canary ReplicaSet reporting availableReplicas == desiredReplicas. Nothing retries while it waits, so a gate that can never resolve looks exactly like a slow one. The stuck state is stable and silent, which is what makes it dangerous: you're serving a split at a non-zero weight the whole time.

So the checks, ordered by how fast they resolve the stall:

symptomcheckaction
weight flaps between two values; status.observedGeneration lags metadata.generationkubectl argo rollouts get rollout checkout -wfind the second writer (Argo CD showing the Rollout OutOfSync, or Flagger managing the same Deployment) remove it, then resume
controller reports 50%, mesh serves 20%diff the VirtualService spec.http[].route[].weight against the step's targetfix VS ownership or a stale gateway revision; the controller writes and the mesh ignores it
AnalysisRun Running past its own durationkubectl get analysisrun -o yaml, then run the PromQL by handusually the query returns no series: wrong label selector or a scrape gap. Inconclusive is not success; the rollout waits forever
canary ReplicaSet short of desiredReplicaskubectl describe pod, check the PodDisruptionBudget and ResourceQuotaclear ImagePullBackOff, a PDB with zero allowed disruptions, or exhausted quota
status.pauseConditions non-empty with no expirykubectl get rollout -o yamla step of pause: {} is indefinite: it waits for a manual promote, so promote or abort deliberately

Hold vs rollback, with the deciding numbers: if the canary's 5xx rate is inside the SLO, under 1% over 5 minutes, and the stall is control-plane, hold and fix the gate. If the canary is serving errors above SLO, or the rollout has passed progressDeadlineSeconds (600s by default, after which Argo marks it Degraded), abort. Aborting is cheap and reversible; a bad canary at 50% weight is not.

Fix-forward, don't rewrite history. Don't hand-edit the VirtualService weight to force the next step: the controller overwrites it on the next reconcile and you lose the audit trail of what actually happened. Correct the gate instead: fix the query, clear the competing controller, raise the quota. Then let the controller advance, or abort and cut a new release carrying the fix.

One thing I'd say out loud: alert on time-in-step, not on failure. A rollout sitting at 20% for three times its pause duration is the signal. By the time the error rate moves, you've already been serving a bad canary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Plan the final shift and baseline termination.

Answer

Assumptions. A model-serving rollout behind a version-aware router: candidate version C is taking 100% of production traffic, baseline version B is still deployed. Recovery objective: put B back at full traffic within 5 minutes of a decision. Peak load is 12k QPS; one B replica sustains about 300 QPS at p99 120 ms, so B needs 40 replicas resident. B's weights are 14 GB and a cold replica takes roughly 6 minutes to load, capture CUDA graphs and pass warmup. That 6 minutes is why "warm enough" has to be a number.

The answer in 90 seconds. I'd hold C at 100% and start a declared 24-hour bake, because the signals that decide this (human review queue, downstream conversion, nightly batch scoring) lag by hours, not seconds. During the bake I pin B at 40 replicas with scale-to-zero disabled, so a rollback is a routing change, not a cold start. Every routing change is one atomic write of a routing table carrying a monotonic generation, so a retried write is a no-op. I terminate B only after the bake window closes with no regression in the delayed signals and the artifact registry holds B's exact weights plus a redeploy path that has been exercised in the last 30 days. The artifacts outlive the fleet.

Why the shift has to be idempotent. A control plane that retries can apply "50% to C" twice and land at 75%. Keying each write by (version, weight, generation) and rejecting any generation at or below the current one makes the retry a no-op. You verify it by summing per-version request counters and comparing against the ingress total: they must match exactly. A mismatch means a slice was applied twice.

Sizing the warm baseline. Keeping 40 GPU replicas resident costs roughly $100/hr at $2.50 per replica-hour, about $2.4k/day (illustrative pricing). That is the price of a 5-minute recovery objective. If the objective were 30 minutes, 8 warm replicas plus cold-start headroom would do, and the bake would cost a tenth as much. The objective sets the warm pool, not the other way around.

stepC weightholdabort if
11%30 minp99 > 150 ms or error rate > 0.5%
225%2 hany slice counter mismatch
3100%24 h bakedelayed signal regression
4terminate B—bake incomplete or artifact missing

Trade-offs. Terminating at hour 1 saves $2.3k and risks a 6-minute cold start at reduced capacity if the first label batch lands at hour 6. Keeping B warm forever doubles GPU spend permanently, which is only defensible when rollback is a compliance obligation. And if C and B share an embedding index or tokenizer, tearing down B does not remove the shared artifact: you have to version the index too, or a rollback restores a model that reads a mutated index.

Failure modes and how they show up.

  • B reports Ready but is stale: a readiness probe passes on a process still holding old weights after a partial reload. Have /health return the model hash and assert it equals B's artifact digest.
  • Autoscaler scales B down mid-bake: watch the replica-count gauge for drift below the pinned minimum and alert on it.
  • Non-idempotent shift: the counter-sum mismatch above, caught within one scrape interval.
  • Delayed regression found after termination: the label pipeline surfaces it hours later; recovery is redeploying B from the immutable artifact registry, which is exactly why that registry and a recently tested redeploy path survive fleet cleanup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Set recovery objectives for model rollback.

Answer

First I'd pin down what "recovered" means, because a rollback isn't done when the control plane flips the version. It's done when intended traffic is getting correct baseline behavior and the bad model's side effects are contained. I'll assume a synchronous ranking model at ~12k QPS, p99 40 ms, deployed as a versioned artifact behind a router, with a feature store and a downstream embedding index, and I'll use hypothetical numbers to make the budget concrete.

I'd split RTO into five components, because they have different owners and different levers:

componenthypotheticallever
detection3 minquality/drift alert on a golden set
decision5 minauto-rollback on threshold vs human
traffic convergence90 srouter drain, connection reuse
load + warm45 s load + 2 min warmpre-pulled artifact, warm pool
validated recovery5 mincanary on golden set

That's ~16.5 min end-to-end. The point of splitting is that detection and decision dominate, and they're the ones people forget to budget. If you only measure "time to flip the flag" you'll report 90 seconds and miss 13 minutes of bad serving.

RPO-like bounds: decision loss is the requests served by the bad model between the first bad response and convergence. At 12k QPS over 16.5 min that's ~11.9M requests, which is exactly why you want auto-rollback to cut decision time. Queued-work replay covers async jobs (batch scoring, index rebuilds) that ran on the bad version; bound it by how far back you can replay from the raw event log.

Trade-off: how much standby to pay for. Three options: hot standby (full duplicate fleet, RTO seconds, ~2x serving cost), warm standby (baseline scaled to ~30% and burst, RTO minutes, ~1.3x), cold (redeploy the previous artifact, RTO 20–40 min, no idle cost). Deciding criterion: cost of a bad minute vs cost of idle capacity. If a bad minute costs more than the monthly standby bill, pay for hot; if rollback is rare and tolerable, cold is right. Don't pay for hot standby on a model whose failures offline eval catches before serving.

Failure modes and how I'd detect them:

  • Feature cache poisoning: the cache still holds features computed by the bad version. Detect by comparing feature freshness/version tags against the rolled-back model's expected schema; symptom is the right model reading the wrong inputs.
  • Schema drift: the baseline expects the old feature schema but the pipeline already migrated. Detect via a feature-fetch 4xx/5xx spike on the canary.
  • Downstream index: embeddings rebuilt by the bad model aren't restored by a model rollback. Detect by recall on a golden query set; this is the one that silently survives rollback.

I'd validate the whole budget with quarterly drills and log every real rollback's per-component time, then set the objective from the p90 of actuals, not the aspiration.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you verify that a model rollback actually restored baseline behavior, and catch a partial rollback or residual state left behind?

Answer

A rollback is not verified by the controller's status. SageMaker deployment guardrails and Argo Rollouts both report a rollback as complete when the desired state is written and the controller has converged the traffic split: that says nothing about which model served the last request, what the cache still holds, or what the candidate version already wrote downstream. Verify at three layers: control plane, data plane, behavior. Assume the baseline is a pinned artifact (model version, endpoint config, image digest) and that caches, async queues, and persisted outputs exist.

Control plane. Compare desired and observed. SageMaker: describe-endpoint should show ProductionVariants[].CurrentWeight == DesiredWeight for the baseline variant and zero for the candidate; the EndpointConfigName should be the pinned baseline config, not a new one. Argo Rollouts: kubectl argo rollouts get rollout <name> should show the stable revision and no active canary; the ReplicaSet hash and image digest must match the baseline. Kubernetes kubectl rollout undo reverts to the previous ReplicaSet: check kubectl rollout status and the pod image digest, not just the command exit code.

Data plane. Control-plane convergence can still leave requests on the candidate: connection draining, sticky sessions, long-lived gRPC streams, or a second controller. Emit a version identifier on every response (header, log field, or model registry alias) and assert it equals the baseline for 100% of requests over a window longer than the longest connection. A trace:

POST /predict -> 200 x-model-version: baseline-2024-11-03 x-endpoint-config: baseline-config-v7

Any candidate-* value is a partial rollback.

Behavior. Replay a frozen golden set through the endpoint and compare to the pre-incident baseline outputs: exact-match or diff rate, score distribution, refusal rate, token counts, latency p50/p99. A diff rate above the baseline's own noise floor means behavior is not restored even if the version header says baseline. NIST AI RMF Measure expects defined metrics tracked over time: use the same metrics that gated promotion.

Residual state. Enumerate what the candidate version touched and check each: feature store or Redis keys written with candidate outputs, prompt/response caches keyed without a version tag, CDN or edge caches, async queues still holding candidate jobs, materialized tables or embedding indexes updated by the candidate, downstream consumers that already ingested candidate outputs. Version-tag cache keys and queue messages so a rollback can invalidate or drain them; without tags, you cannot prove the cache is clean.

Partial rollback. The common shape: one variant rolled back, another did not; or the controller rolled back the deployment but a second controller (or a manual kubectl set image) still points at the candidate. Detect by asserting every serving replica's identity, not the aggregate. A verification table:

LayerCheckPassFail signal
Control planeDesired vs observed weightsbaseline weight 100, candidate 0candidate weight > 0 after deadline
Data planePer-request version100% baseline over 2× max connection ageany candidate version served
BehaviorGolden-set replaydiff rate ≤ baseline noisediff rate above noise
ResidualCache/queue/table version tagsno candidate-tagged entriesstale candidate outputs served

Failure modes: rollback marked complete while a cache still serves candidate outputs (detect by version-tagged cache misses or by replaying a known candidate input); async jobs from the candidate completing after rollback (detect by queue depth and job provenance); downstream state already mutated (detect by comparing downstream table snapshots). Clearing a CloudWatch alarm that triggered auto-rollback is not evidence of recovery.

Curated: · Written: · Reviewed:

Difficulty: Hard