Skip to content
Tech Interview Prep
Technical interview guide

Deployment Strategies (Blue-Green, Canary, Rolling)

Different ways to roll a new version out safely, trading off speed, blast radius, and infrastructure cost.

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

Scope: Kubernetes, Argo Rollouts, Istio, Flagger, Amazon ECS, OpenFeature, DORA, Google SRE, and NIST guidance current 2026-08-31.

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-1

Choose a deployment strategy for a critical service.

Answer

Assumptions I'd state up front: Kubernetes, ~200 pods, 1,000 rps peak, p99 40 ms, SLO 99.95% availability, and the service owns its own schema. The hard part of deploying a critical service isn't the pod swap: it's that a bad release shows up in the tail, and that rollback must still work after the new version has written data.

The answer: canary with automated metric analysis (Argo Rollouts or Flagger driving Istio/Envoy traffic weights), feature flags for capability exposure, and expand/contract migrations so every step is reversible. Blue-green only when I must validate a whole environment before any user sees it and can afford 2× capacity. Rolling only for low-risk, schema-compatible changes.

Why canary, mechanically

A canary bounds blast radius and gates promotion on evidence. Rolling gives you neither: every pod is eventually replaced, and nothing stops the rollout when error rate climbs. You find out from the SLO burn. Blue-green gives you a fast switch (seconds, a weight flip) but exposes 100% of traffic at once, and both versions run against one database during the switch, so any non-additive schema change is a live hazard.

extra capacityexposureevidence gaterollbackstate risk
rolling~25% surgeall users, graduallynonere-roll, minutesschema must be compatible
blue-green100%all at switchpre-switch smokeflip, secondstwo versions, one DB
canary1–5%bounded cohortautomated metricssetWeight 0, secondssame as rolling

The rollout

YAML
apiVersion: argoproj.io/v1alpha1
kind: Rollout
spec:
  strategy:
    canary:
      canaryService: svc-canary
      stableService: svc-stable
      trafficRouting:
        istio:
          virtualService: {name: svc-vs}
      analysis:
        templates: [{templateName: success-rate}]
        startingStep: 1
      steps:
      - setWeight: 1
      - pause: {duration: 10m}
      - setWeight: 5
      - pause: {duration: 10m}
      - setWeight: 25
      - pause: {duration: 15m}
      - setWeight: 50
      - pause: {duration: 15m}
      - setWeight: 100

The AnalysisTemplate queries Prometheus every minute and aborts after failureLimit: 2 consecutive failures:

YAML
metrics:
- name: success-rate
  interval: 1m
  successCondition: result[0] >= 0.995
  failureLimit: 2
  provider:
    prometheus:
      address: http://prometheus.monitoring:9090
      query: |
        sum(rate(http_requests_total{service="{{args.service-name}}",code!~"5.."}[2m]))
        / sum(rate(http_requests_total{service="{{args.service-name}}"}[2m]))

Why 1% first, then 5%: at 1,000 rps, 1% is 10 rps. Ten minutes gives 6,000 requests, so p99 rests on ~60 tail samples: enough to catch a hard 5xx spike, too noisy for a latency regression. 5% (50 rps) over ten minutes gives 30,000 requests and ~300 tail samples, which is where the p99 gate becomes trustworthy. That's the arithmetic that sets the step sizes, not taste.

Failure modes and how I'd catch them

  • Canary passes, 100% breaks. Usually cohort skew: header-routed canary gets internal traffic only. Detect by asserting canary request rate > 0 and comparing canary vs. stable on the same metric before each promotion.
  • gRPC/long-lived connections pin to stable pods, so the canary sees no traffic and the analysis passes vacuously. Detect: alert if canary rps is below the expected weight × total.
  • A migration poisons stable too. Run migrations as a pre-sync step, additive only (add column, backfill, dual-write, then drop in a later release). Detect: schema-diff check in CI against the previous release.
  • Rollback isn't instant. Pods drain for 30–60 s; watch 5xx during termination, and keep the previous ReplicaSet warm so setWeight: 0 is a traffic flip, not a reschedule.
  • Retries mask errors. A 0.5% error rate can hide behind client retries; gate on server-side 5xx and client-observed latency, not just success rate.

Feature flags sit on top: they decouple capability exposure from code deployment, so a canary that passes can still ship dark and be enabled per-tenant later.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Design a safe rolling update.

Answer

The 90-second answer. A rolling update is safe only when three things hold at once: old and new code can serve traffic simultaneously, you have capacity to run both, and you can detect harm and stop before it spreads. If any of those is false: a schema change that isn't backward compatible, a service with long-lived connections, no spare capacity: a rolling update is the wrong tool and you want blue/green or a canary on a separate fleet.

Assume a stateless HTTP service on Kubernetes behind a Service: 20 replicas, p99 40 ms at 60% CPU, SLO 99.9%. The design:

  • Pin the image by digest, not tag: image: registry/app@sha256:.... A tag can be repointed mid-rollout, so two Pods you believe are the same version run different code and your version-distribution check lies.
  • maxUnavailable: 0, maxSurge: 25% (5 Pods). Zero unavailable keeps full serving capacity; surge costs 25% extra nodes for the duration. If the cluster can't schedule those 5, the rollout stalls at progressDeadlineSeconds instead of degrading service: that's the point of the deadline.
  • minReadySeconds: 30, so a Pod must pass readiness for 30 s before it counts as available. Without it, a Pod that passes readiness and then dies on its first real request still advances the rollout.
  • Readiness probe checks a real dependency, not /healthz returning 200. A lazy connection pool passes readiness instantly and then 500s under load.
  • preStop: sleep 15 plus terminationGracePeriodSeconds: 60. Endpoint removal is asynchronous, kube-proxy and the cloud LB take seconds to stop sending new connections, so a Pod that exits immediately on SIGTERM drops in-flight requests.

Trace. 20 replicas, maxSurge 5, maxUnavailable 0. Wave 1: the controller creates 5 new Pods; they pass readiness at t+40 s and minReadySeconds at t+70 s. It then terminates 5 old Pods, each getting SIGTERM after a 15 s preStop and draining for up to 60 s. Four waves, roughly 5 minutes total. Watch kubectl rollout status and the live version split from metrics (sum by (version) (requests_total)). Halt if new-version 5xx exceeds your error-budget burn rate over a 5-minute window; kubectl rollout undo only works if the new version didn't write data the old version can't read.

Trade-offs.

RollingBlue/greenCanary
Extra capacitymaxSurge only2× fleet1 canary Pod
Blast radiusall users, graduallynone until switchcanary's traffic share
Rollbackredeploy old digestflip LB backshift traffic back
Requiresbackward-compatible API + schema2× costtraffic splitting

Rolling is wrong when the schema change isn't backward compatible: use expand/contract across separate deploys: add the column, dual-write, backfill, switch reads, then drop the old column once the old version is gone. It's also wrong for long-lived connections (WebSockets, gRPC streams), where draining takes minutes and you need connection draining at the LB, and for apps with multi-minute cache warmup, where a fresh Pod serves worse than an old one.

Failure modes. A Pod stuck Terminating on a finalizer hangs the rollout: check kubectl get pod -o yaml for deletionTimestamp. A PDB with minAvailable equal to the replica count blocks voluntary eviction, so drain never completes. Node loss mid-rollout removes capacity you counted on, so size maxSurge from headroom after an N-1 node failure, not from steady state. And during a partial migration, old and new both write to the same table under different assumptions: dual-write with a reconciliation job, and don't drop the old column until the old version is fully gone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design a blue-green deployment.

Answer

Core answer

Blue-green means two full production environments. Blue serves 100% of traffic; green is deployed, verified, then takes 100% in one cutover. Assume a web service behind a load balancer with a shared relational database. The cutover itself is the easy part: flip a target group or an ingress weight. Two things decide whether it works: capacity and state.

Capacity: green must serve full production load before it gets any. That is 2x compute for the length of the window. If you cannot pay for that, blue-green is the wrong tool: use canary.

State: everything not in the deployable artifact (schema, sessions, caches, queues, cron jobs, external side effects) is shared or duplicated, and you decide which for each one.

The switch

On AWS: two target groups behind one ALB, blue at weight 100, green at 0. Verification traffic reaches green through a listener rule matching a header (X-Env: green). Cutover is a rule change: seconds. In-flight requests on blue drain over the target group's deregistration delay, default 300s in ALB; set it to your longest request (say 30s) or you hold connections open for five minutes.

Cutting over by DNS instead bounds you by TTL. Route 53 TTL 60 means some clients keep hitting blue for a minute, and resolvers that ignore TTL keep hitting it longer. Flip at the LB, not DNS, unless you have no choice.

State, component by component

ComponentHandling
DB schemaExpand-contract: green's migration adds nullable columns/tables only; blue must still run against the new schema. Drop old columns a release later.
SessionsExternalize to Redis, or accept that in-memory sessions on blue are lost at cutover. ALB stickiness (AWSALB cookie) pins a user to one target group but does not survive the flip.
Cron / singleton jobsDisable schedulers in green via an env flag until cutover; two schedulers double-fire.
Queue consumersBoth versions consume; payloads must be readable by both, so no new required fields until blue is gone.
External effectsEmails, payments, webhooks are not undone by flipping traffic. Gate them behind a flag or accept them.

Warm-up and verification

A cold JVM or cold connection pool serves badly. Push synthetic traffic to green for several minutes before cutover: illustrative: p99 40ms warm versus 180ms on a cold JVM, converging after roughly 5 minutes. Run the same synthetic journey against green through the preview listener and compare error rate and latency to blue.

Rollback

Flip back. That is the point of blue-green. It only works if green's writes are safe for blue to read, which is what expand-contract buys you. If green ran an irreversible migration or emitted side effects, rollback is a lie; you roll forward.

When not to use it

Canary gives 1% → 10% → 100% exposure on one environment, no 2x capacity, and catches problems at low blast radius. Blue-green gives instant whole-version rollback and a clean pre-cutover verification target. Pick blue-green when the risk is the version as a whole and you can afford the duplicate; pick canary when the risk is gradual and capacity is tight.

Failure modes

  • Both schedulers fire → duplicate invoices. Detect: count job executions per interval, alert if >1.
  • Green reads a column blue has not backfilled → nulls in responses. Detect: error rate on green during preview.
  • Cutover with 300s deregistration delay → blue holds connections, looks healthy, serves stale. Detect: connection count on blue after flip.
  • Rollback after green wrote → blue cannot parse green's rows. Detect: 5xx spike immediately after flip-back.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do you implement weighted traffic routing and sticky sessions for canary deployments at the load balancer or ingress layer?

Answer

To implement weighted traffic routing with session affinity, decouple replica count from exposure. In vanilla Kubernetes Service definitions, traffic splits across identical endpoints: a 5% canary on 20 pods requires running 1 canary pod and 19 stable pods, collapsing when scaling to 100 pods or when running low-percentage tests (like 1%). Instead, push weight management to the ingress or service mesh layer using an ingress controller (like NGINX Ingress), a service mesh (Istio VirtualService), or a progressive delivery controller (Argo Rollouts or Flagger).

1. Weighted Routing Mechanism

Traffic weighting at L7 configures the proxy data plane to evaluate upstream pools using weighted round-robin or random distribution across distinct backend targets. For example, using Istio VirtualService with destination subsets backed by Kubernetes Deployment selectors:

YAML
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: checkout-route
spec:
  hosts:
  - checkout.internal
  http:
  - route:
    - destination:
        host: checkout-service
        subset: stable
      weight: 90
    - destination:
        host: checkout-service
        subset: canary
      weight: 10

2. The Sticky Session Dilemma and Architecture

Naive cookie-based session stickiness breaks canary deployments. If a sticky cookie pins a client directly to an upstream service instance or pod IP, two failure modes occur:

  1. Cohort Drift / Skew: As canary weight increments from 10% to 25%, users already pinned to stable never evaluate the new weight until their cookie expires. Conversely, if sticky cookies pin users indefinitely, the canary cohort accumulates traffic over time, exceeding the configured 10% cap.
  2. Canary Flapping: If sticky sessions are evaluated before weight routing, new clients receive the canary weight, but returning sessions bypass weight calculation, making statistical metrics invalid.

To resolve this, structure cookie affinity into a two-tiered decision:

  • Tier 1 (Cohort Stickiness): The proxy evaluates whether a user has a cohort cookie (e.g., X-Canary-Cohort=canary|stable). If present, route via exact match. If absent, apply the 90/10 weight, evaluate headers, and inject the Set-Cookie header on the downstream response with an explicit short Time-To-Live (TTL, e.g., matching average session duration: 15–30 minutes) or scoped to the browser session.
  • Tier 2 (Pod Affinity): If internal state requires instance stickiness (e.g., in-memory websocket state), use standard consistent hashing (such as consistentHash.httpCookie) nested inside the selected destination subset, not globally across both deployments.

3. Worked Routing Logic

Traffic StageEvaluation OrderMechanismUpstream Target
1. Pinned OverridesCheck header X-Canary: alwaysExact Header MatchCanary subset (100%)
2. Existing SessionCheck cookie canary-cohortCookie Value MatchSpecified subset (Canary or Stable)
3. New SessionWeighted Random Selection90% Stable / 10% CanarySelected subset + Set-Cookie injected
4. Instance AffinityConsistent Hash on Pod IDUpstream LoadBalancingSpecific pod inside selected subset

4. Failure Modes and Mitigation

  • Weight Dilution via Long-Lived Keep-Alives: Persistent HTTP/1.1 or HTTP/2 TCP connections from reverse proxies or internal microservices can reuse an existing connection and bypass per-request L7 weighting. Mitigation: Ensure the ingress operates at per-request HTTP stream level (e.g., Envoy stream_idle_timeout and per-request routing), not L4 connection level.
  • Canary Abort and Zombie Sessions: When metrics trip guardrails and the rollout aborts (canary weight set to 0), clients holding the canary sticky cookie continue sending traffic to an unhealthy or terminating pod. Mitigation: In the ingress configuration, tie cookie routing to an active health check or ensure the abort hook clears or overrides the route regardless of cookie presence (e.g., set fallback route: subset: stable when canary replica count drops to 0).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Validate configured versus achieved traffic split.

Answer

What a strong candidate says first

Pin down two things before measuring anything: is the split request-level or user-level, and what is the denominator. All requests, or only eligible ones? A canary configured at 5% by request weight on the edge router is not 5% of users, and neither is 5% of requests that reach the service. The configured weight is applied at exactly one hop; every hop after it can only dilute or distort the number.

Then instrument the routing decision itself. Emit a counter where the router picks a variant, keyed by route and variant, before any retry, cache or fallback. That counter is the only one whose denominator you control. Compare it to the configured weights with a binomial confidence interval, not a point estimate.

Where the observed split drifts

LayerWhat it countsWhy it distorts
Edge / LBconnections or requestslong-lived connections counted once; health checks and bots included
Router decisionrouting decisionsthe true denominator; needs instrumentation
Serviceserved requestsincludes retries, excludes cache hits
Async workerjobsone request can fan out to many jobs

Sticky sessions are the most common cause. If the LB sets an affinity cookie on the first request, the split converges to user-level: a user with 10,000 requests counts once at assignment but 10,000 times at the router. Request-level and user-level counters diverge, and the configured weight, usually request-level, is not what you measured.

Retries inflate the candidate. A retry of a candidate request is another candidate request. If the candidate is the one failing, service-level candidate exposure climbs while router-level exposure stays flat. The gap between the two counters is retry amplification, and it is a signal, not noise.

Long-lived connections route once. gRPC, HTTP/2 and WebSocket connections pick a variant at connection setup. A connection carrying 10,000 requests is one routing decision. A 5% connection-level split can be a 30% request-level split if candidate connections happen to be stickier.

Caches and CDNs serve before the router, so those requests never appear in any split counter. Bots and synthetic probes come from fixed sources and can be pinned to one variant.

Arithmetic

Configured 5%, n = 10,000 routing decisions. Expected 500, sd = sqrt(10000 × 0.05 × 0.95) ≈ 21.8. The two-sigma band is 500 ± 44, or 4.56%–5.44%. An observed 4.4% is inside noise; 3.5% is not. For more than two variants use a chi-square test; for continuous monitoring use a sequential test (SPRT) so you are not peeking and stopping.

Choosing an approach

An edge counter is cheap but has the wrong denominator. A router counter has the right denominator but needs code in the router. A service counter measures what was actually served but includes retries. Use the router counter as the source of truth and the service counter as a cross-check; if they disagree by more than the confidence band, stop and find out why before reading anything into the split.

Failure modes

Aggregate split looks correct but one route gets 0% candidate: only per-route counters catch this. The router fails open to baseline on a config error, so the candidate silently gets nothing: a "no variant" counter and a router health metric catch it. Sticky sessions make the split converge to user-level: comparing request-level and user-level counts catches it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design an evidence-based canary rollout.

Answer

Assumptions. Stateless HTTP service, ~50k requests/min, user-facing change, metrics pipeline already labels every request with the serving version. If this were a data migration or a stateful change, the cohort and rollback design would differ: I'll flag where.

Core answer. A canary is a controlled experiment, not a slow deploy. Four parts: a randomized cohort with a concurrent control, predeclared stages sized by statistics, guardrail metrics with numeric thresholds, and a decision rule that can only promote on evidence and abort on harm.

Cohort. Randomize on a stable hash of user ID (request ID for stateless paths) so a user stays in one arm across requests. The control runs the same traffic mix in the same time window, which is what makes the comparison valid. Segment-based cohorts (one region, one tenant) bound blast radius but confound the result with whatever is special about that segment. Use them only when you must limit exposure to a specific risk.

Stages and sample size. Pick percentages so each stage has enough samples to detect the smallest regression you care about. Worked example: baseline error rate 0.5%, you want to catch a rise to 1.5%. Two-proportion test, 95% confidence, 80% power:

n = (1.96 + 0.84)² × (0.005×0.995 + 0.015×0.985) / 0.01² ≈ 1,550 per arm.

At 50k req/min, a 1% canary is 500 req/min, so you clear 1,550 canary requests in ~3 minutes. That is the floor, not the bake time.

StageCanary trafficMin canary requestsBake
1%500 req/min1,55030 min
5%2,500 req/min1,5501 h
25%12,500 req/min1,5504 h
50%25,000 req/min1,55024 h

Bake time. Sample size is necessary, not sufficient. Bake must cover the metric's natural period. If latency has a daily cycle, bake ≥ 24h or you compare morning canary against evening control. For leak-class bugs, add a soak stage at 25% for several hours.

Guardrails, evaluated canary vs concurrent control at every stage:

  • Error rate: canary > control + 0.5pp, or > 2× control.
  • Latency: p99 > control p99 × 1.2.
  • SLO burn: 1h burn rate > 14.4× (2% of a 30-day budget in one hour).
  • Saturation: CPU, memory, queue depth per instance.
  • Segment-level: the same checks per top-N segments, so one broken region isn't diluted by the aggregate.

Verify exposure and identity before trusting any metric. Confirm the canary actually serves the new build: check a build-SHA label on requests and that the canary received the intended fraction. A routing bug that sends 0% to the canary looks perfectly healthy.

Decision rule. Promote only when every guardrail passes for the full bake. Abort on any hard breach. On ambiguity, metric moved but under threshold, hold and extend bake rather than promote. Rollback must be idempotent: re-point the route, then re-verify version identity on every instance, because partial rollback is a common failure.

Failure modes.

  • Silent no-op: canary gets no traffic. Detect via request count per version label. Cost: you promote nothing and believe you validated.
  • Confounded cohort: canary skews to one device or region. Detect via covariate balance on the cohort. Cost: false confidence.
  • Diluted regression: aggregate fine, one segment broken. Detect via segment-level thresholds. Cost: user-visible outage in that segment.
  • Slow burn: leak or cache growth. Detect via soak stage and memory slope. Cost: OOM hours later.

Trade-offs. Shadow/dark launch measures no user-facing metrics but has zero blast radius: good for perf, useless for correctness. Blue-green rolls back instantly but exposes 100% at once. Feature-flag rings give the same control as a canary with less infra, but you still must verify exposure. Longer bakes buy confidence at the cost of delivery speed; the deciding criterion is the cost of a bad rollout against the cost of a slow one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Select a representative canary cohort.

Answer

I'd answer this in three moves: choose the assignment key, size the cohort to the smallest effect I care about, then verify the cohort's shape before I read a single metric.

Assume a B2B SaaS with roughly 1M monthly active accounts, web and mobile clients, and a flag platform already wired up.

Assignment. Bucket on a stable identity, not a session: bucket = SHA-256(salt || account_id) mod 10000, and treat bucket < 100 as the 1% canary. Account-level assignment keeps a user's sessions, devices and tabs on one side of the line. A session-level split shows the same person both versions within a day, which contaminates the readout and is the most common way a canary lies. Use session-level only for logged-out traffic where no stable ID exists. LaunchDarkly and Statsig both bucket deterministically on a key you supply, so the real decision is which key, not which vendor.

Sizing. For a two-proportion test at 80% power and α=0.05, n per arm ≈ 8·(p₁(1−p₁)+p₂(1−p₂))/δ². To detect a 1pp lift on a 5% baseline: 8·(0.0475+0.0564)/0.0001 ≈ 8,300 per arm, about 16,600 total. A 1% canary of 1M accounts is 10,000: enough. A 0.1pp effect needs ~830,000 per arm, so don't put that question to a canary; it belongs in a full A/B test.

Shape check. Compare the canary against the population on the dimensions that actually move the metric:

DimensionWhy it decides the readPre-launch check
Tenant sizeEnterprise and self-serve respond differently to the same changeEnterprise share within 1pp of population
RegionLatency and compliance behavior differNo region >2× its population share
Client/deviceOld app versions may not exercise the code pathVersion mix matches baseline
Data shapeLarge or sparse accounts hit different code pathsp99 account size comparable
DependencyA shared downstream service can absorb the blastCanary traffic <10% of that service's capacity
Delayed outcomeChurn and refunds land weeks laterWindow length set before launch

Trade-offs. Internal-first is fast and risks no customer, but dogfooders are power users on the newest build, so it validates plumbing, not effect: treat it as a smoke test, not a cohort. Stratify when a dimension is both imbalanced and correlated with the metric (enterprise vs self-serve); stay random when the population is homogeneous. Stratifying on too many dimensions is the failure mode: you fragment the cohort below the 8,300 you computed and lose the power you sized for.

Failure modes and how you catch them. Cohort skew: standardized mean difference above 0.1 on any dimension triggers a re-bucket. A 2pp drift in enterprise share can manufacture a fake 0.5pp lift. Concentration: if the top tenant exceeds 5% of canary traffic, one account's behavior is driving the number; cap per-tenant share. Novelty: compare day-1 against day-7 metrics; a gap that closes means you measured surprise, not value. Delayed outcomes: 30-day retention is unreadable on day 3, so hold the canary until the window closes rather than promoting on a partial signal. Guardrails: error rate, p99 latency and crash-free sessions auto-halt the ramp. A canary that ships a regression to 1% of accounts has still shipped it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design canary promotion guardrails.

Answer

Assumptions first. This is a request-serving service with an existing SLO, a control (current version) and a candidate, and a traffic splitter that can pin a fixed share to the candidate. I'll assume 5% to the candidate, 95% to control, both measured over the same wall-clock window, and per-version SLI telemetry already in place. If any of those don't hold (no per-version telemetry, no splitter) the design changes and I'd say so before going further.

The answer. Promotion is two gates in series, not one score. Gate one is hard invariants: any authz bypass, any PII written to logs, any data corruption, any write to a shared store that can't be rolled back. These abort on first occurrence, with no waiting for statistical significance, because the cost of the breach is unbounded and the sample size needed to "prove" it is irrelevant. Gate two is statistical: user-journey success rate and latency, candidate vs control, with thresholds and sample sizes declared before the canary starts.

Why burn rate, not raw error rate. A raw error-rate threshold doesn't tell you whether you're spending budget fast or slow. Burn rate does: 1x consumes the error budget at exactly the rate that exhausts it over the SLO window. For a 30-day SLO window, 1 hour at 14.4x burns 14.4/720 = 2% of the budget: the fast-burn alert. 6x over 6 hours burns 6×6/720 = 5%: the slow-burn alert. Those are the thresholds from the SRE workbook's multiwindow multi-burn-rate pattern, and they're what I'd wire to the canary's abort.

Sample size, so you don't promote on noise. To distinguish 99.5% from 99.3% success at 95% confidence and 80% power, the two-proportion test gives n per arm ≈ 7.84 × (0.004975 + 0.006951) / 0.002² ≈ 23,000 requests. At 5% of 1,000 rps = 50 rps to the candidate, that's about 8 minutes of canary traffic. If the service does 5 rps total, the candidate sees 0.25 rps and you will never reach 23,000 in a sane window: that's the case where statistical gating is the wrong tool and you fall back to invariants plus a long soak plus human review.

gatesignalthresholdaction
hard invariantauthz bypass, PII in logs, corruptionany occurrenceabort, no stats
fast burncandidate error rate14.4x over 1h (2% of 30d budget)abort
slow burncandidate p99 latency6x over 6h (5% of budget)abort
promotionsuccess-rate delta vs control0.2pp, 95%/80% power, ~23k req/armpromote

Where it breaks. Averages hide harm: a cohort that's 1% of traffic can be 100% broken while the aggregate moves 0.1pp. Segment on the dimensions that decide correctness (device class, region, tenant tier, auth state) and require a per-segment minimum sample before trusting the aggregate. Evaluation delay: metric pipelines lag, so the last few minutes are incomplete; deciding at minute 8 on data that lands at minute 12 promotes on partial data. Wait out the pipeline lag before the decision. Shared-resource contamination: if candidate and control share a database, a candidate that saturates the DB degrades control too and the comparison looks neutral. Measure dependency-level signals (DB p99, connection-pool saturation) not just the service's own SLIs.

Auto-abort vs human review. Auto-abort when the action is reversible, the signal is well-instrumented, and traffic is high enough to reach sample size. Route to human review when the change is irreversible (schema migration, backfill) or the signal is ambiguous: a small latency regression that might be a noisy neighbor. Missing data is fail-closed: if canary telemetry drops, that's an abort, not a pass.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you design synthetic testing and automated canary analysis (ACA) to gate traffic promotion in phased rollouts?

Answer

Synthetic testing verifies critical functional paths before exposure to real users, while Automated Canary Analysis (ACA) evaluates statistical deviations between canary and baseline pods under real production load. An effective promotion gate couples these two mechanisms sequentially: run active synthetics against the canary revision in isolation, shift a small traffic slice (for example, 5%), run continuous statistical evaluation over an observation window, and advance promotion steps only when both gates pass.

1. Phased Architecture and Traffic Shifting

Using an ingress or service mesh controller (such as Istio or Argo Rollouts), direct synthetic probes to canary pods using dedicated internal routing headers before public traffic shifts. Once synthetics clear, route production weight progressively.

Step 0 (Preview): Weight 0%  --> Synthetic Probe with header (x-canary-test: true) --> Canary Pods
Step 1 (Shift 5%): Weight 5% --> Real Users + Baseline Comparison --> ACA Metric Gating
Step 2 (Shift 20%): ACA passes over 15m window --> Weight 20% --> ACA Re-evaluation
Step 3 (Shift 100%): Complete promotion or auto-abort to 0% on any metric breach

2. Statistical Metric Gating (ACA)

Avoid raw static thresholds (like error_rate < 1%); cluster-wide incidents or downstream outages will fail healthy canaries. Instead, run twin deployments: a baseline (current stable image deployed identically alongside canary) and canary (new image). Both receive identical traffic distributions, isolating software delta from cluster noise.

Compare metrics across three core vectors:

  • Reliability: HTTP 5xx rate and gRPC non-zero codes.
  • Performance: p95 and p99 server-side latency.
  • Resource Health: Resident memory (RSS) growth rate and CPU per request.

Use statistical scoring algorithms (such as Mann-Whitney U test or threshold variance over a sliding 10–15 minute window) to compare the metric distributions between baseline and canary.

PhaseTarget CohortGate TypePass CriteriaFailure Action
Pre-Traffic (0%)Synthetic probes (x-canary: test)Synthetic End-to-End Suite100% assertions pass on core transactional pathsImmediate abort; 0% user impact
Canary Step 1 (5%)Live traffic + BaselineStatistical ACA (Mann-Whitney U)Canary error rate not statistically > baseline ($p < 0.01$); latency drift $\le 5%$Revert weight to 0%; isolate pods for triage
Canary Step 2 (25%)Live traffic + BaselineSustained ACA & Saturation CheckLinear memory ceiling; error delta $\approx 0$ over 15 min windowRevert weight to 0%; alert on-call

3. Failure Modes and Guardrails

  • Synthetic Side Effects in Production: If synthetics write state (e.g., placing orders), use mock billing tokens or dedicated synthetic test tenants to avoid ledger contamination.
  • Low Traffic / Cold-Start Noise: Low request volumes produce high metric variance. Enforce minimum sample counts (e.g., minimum 500 requests per analysis window) before computing p99 or error ratios. If minimum volume is missing, pause the rollout rather than promoting.
  • Abort Cleanup: On rollback, instantly set traffic weight to 0%, drain existing connections gracefully, and mark the analysis run as failed to block downstream pipelines.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How do you define error budgets, key metrics, and observation windows to detect canary regressions and avoid false promotions?

Answer

To prevent false canary promotions, automated canary analysis (ACA) must evaluate relative delta between parallel cohorts: canary vs. baseline: rather than raw static thresholds, backed by sample size guardrails and distribution-aware statistical tests.

1. Metric Selection and Baseline Setup

Never compare the canary to historical time-shifted metrics (e.g., yesterday at the same time), which are distorted by diurnal shifts, upstream latency, or client traffic composition. Deploy identical baseline and canary replica sets concurrently receiving the same routing weight:

  • Canary: New code artifact.
  • Baseline: Current production artifact, spun up simultaneously to cancel out cache warm-up, runtime JIT compilation, and instance age differences.

Key metrics are separated into two tiers:

  • Hard Gating (Failure Criteria): HTTP 5xx rate, unhandled exceptions, panics, goroutine/thread leaks, and data write errors. Any breach triggers immediate rollback.
  • Degradation Criteria (Comparative Analysis): p95/p99 latency, downstream dependency duration, CPU/memory per request, and core business conversion rates (e.g., checkout success).

2. Statistical Mechanics: Avoiding False Positives

Single-point averages hide outliers, while raw percentiles on small sample sizes yield high variance. For latency distributions, use a non-parametric two-sample test like the Mann-Whitney U test (Wilcoxon rank-sum) or Kolmogorov-Smirnov test, which makes no normal distribution assumptions:

  • Set significance level $\alpha = 0.01$ or $0.05$.
  • Reject null hypothesis $H_0$ (distributions are identical) only when $p < \alpha$ and the median shift exceeds an acceptable degradation delta (e.g., $> 5%$ increase).

For binary failure rates (e.g., error counts vs. total requests), use a two-proportion z-test or an explicit error budget burn rate gate across the canary duration.

3. Traffic Sizing, Observation Windows, and Math

Statistical power depends on request volume. Let baseline error rate be $p_1 = 0.001$ ($0.1%$) and we want to detect a jump to $p_2 = 0.002$ ($0.2%$) at $\alpha = 0.05$ ($95%$ confidence) and power $1 - \beta = 0.80$:

$$n \approx \frac{\left(Z_{1-\alpha/2}\sqrt{2\bar{p}(1-\bar{p})} + Z_{1-\beta}\sqrt{p_1(1-p_1) + p_2(1-p_2)}\right)^2}{(p_2 - p_1)^2}$$

Where $\bar{p} = 0.0015$, $Z_{0.975} = 1.96$, $Z_{0.80} = 0.84$: $$n \approx \frac{\left(1.96\sqrt{0.003} + 0.84\sqrt{0.003}\right)^2}{(0.001)^2} \approx \frac{(0.1073 + 0.046)^2}{10^{-6}} \approx 23,500\text{ requests per cohort}$$

If the canary receives $5%$ of traffic at $500\text{ total RPS}$, canary RPS is $25$. Reaching $23,500$ requests requires $\approx 940\text{ seconds}$ ($\sim 16\text{ minutes}$). Advancing a canary step in 2 minutes would guarantee false negatives due to statistical underpowering.

Canary Step Matrix

StepTraffic AllocationMin Sample SizeWindow DurationAnalysis Evaluated
Phase 12% Canary / 2% Baseline5,000 reqs10 minHard fail gates (5xx, crashes, leaks)
Phase 210% Canary / 10% Baseline25,000 reqs20 minMann-Whitney latency + error z-test
Phase 325% Canary / 25% Baseline50,000 reqs30 minSaturation metrics, resource burn, business KPIs
Phase 4100% Final PromotionN/APost-promo 15mFinal baseline deconstruction and alert handover

4. Guardrails Against False Promotions

  • Minimum Request Threshold: If traffic drops below the calculated sample size ($N_{\min}$), halt promotion timer; never auto-promote on an empty or low-traffic window.
  • Consecutive Interval Rule: Require $M$-of-$N$ consecutive successful evaluation cycles (e.g., 3 consecutive checks spaced 5 minutes apart) to clear transient blips.
  • Error Budget Consumption Limit: Calculate Canary Error Budget Burn Rate. If the canary consumes $> 2%$ of the service's monthly error budget over an hour window, halt immediately.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Handle missing or delayed rollout telemetry.

Answer

Core answer

Assume a staged rollout, a canary at some percentage, with guardrail metrics coming from a pipeline I don't fully control. The decision is advance, hold, or revert when the numbers don't arrive.

Missing telemetry is never evidence of health. I hold at the current percentage, treat the analysis as unknown rather than zero, and work out which of three things happened: the data is late, the data is gone, or the query is lying. Only then do I decide whether the cohort keeps running.

Delay, loss, or a query artifact

These look identical on a dashboard and have different fixes.

  • Query artifact: Prometheus's default lookback delta is 5 minutes (--query.lookback-delta). A series whose newest sample is older than that is excluded from instant-vector results, so rate() over a window with no samples returns an empty vector. A panel written sum(rate(rollout_requests_total[5m])) or vector(0) renders that as 0.
  • Real loss: the OTel Collector's batch processor defaults to a 200 ms timeout and 8192 batch size, with retry_on_failure on and max_elapsed_time: 5m. A backend unreachable for 12 minutes means batches older than 5 minutes of retries are dropped: gone, not late.
  • Genuine delay: Kafka's log.retention.hours defaults to 168, so a lagging consumer catches up. Waiting is fine, but the analysis window must be event-time, not wall-clock.

Worked trace

Canary at 5% of 240,000 req/h → 12,000 req/h in the cohort → 50 requests per 15 s scrape. Guardrail: 5xx rate ≤ 1%. Prometheus scrapes rollout_requests_total{job="canary"} every 15 s; the last sample lands at 09:38:00 when the scrape target disappears from the target list.

Eval timeWindow (t−5m, t]Samplessum(rate(...[5m]))... or vector(0)
09:42:0009:37:00–09:42:004 (09:37:15 → 09:38:00)3.333.33
09:45:0009:40:00–09:45:000empty0
10:00:0009:55:00–10:00:000empty0

rate() needs two samples; once the window holds fewer, it returns empty and the or vector(0) fallback fires. From 09:45:00 the panel reads a flat 0. A healthy-looking zero for the next 15 minutes. The 5xx-ratio panel, sum(rate(rollout_requests_total{job="canary",code=~"5.."}[5m])) / sum(rate(rollout_requests_total{job="canary"}[5m])), shows No data over the same window. Two panels disagreeing is itself the tell.

Cross-check on an independent path: load-balancer access logs for 09:38–10:00 show 4,400 requests and 22 5xx = 0.50%, inside the 1% guardrail. The cohort is safe to keep running, but I don't advance the stage: 22 minutes of guardrail are unverified.

Policy and exposure cap

The pause/abort rule is predeclared, not invented mid-incident. Mine: if the guardrail can't be evaluated for the stage's minimum window, hold at the current percentage; if the hold exceeds 60 minutes, revert to 0%. That caps how long users sit in an unmonitored cohort.

Late data must not evaluate the wrong step. Partition by event time, and when backfill lands, re-run the analysis for the affected window rather than letting it flip a decision already made on a later stage.

Failure modes

The one that bites: an or vector(0) panel turning a stale series into a green zero, and someone promoting on it. Detect it with an alert on time() - timestamp(metric) > 300 per job, not on the metric value. The second: retry buffers masking permanent loss. Alert on otelcol_exporter_send_failed_metric_points and dropped-batch counters, not just on the backend being up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Handle delayed outcomes in a canary.

Answer

What I'd say in the first two minutes

Assume the change is a pricing, ranking or fraud-rule edit whose real outcome (settled payments, 30-day retention, chargeback rate) lands days after the request. The canary's decision window is shorter than the outcome latency. That mismatch is the entire problem, and it is not solved by watching harder.

My answer: split the decision into two gates. Gate 1 runs in hours on a proxy that has been validated against the true outcome on historical data, and it authorises continued exposure only: never full promotion. Gate 2 runs in days on the true outcome, measured on a held cohort, and it authorises promotion. Keep a small holdback on the old version for the full latency window so the true outcome stays measurable after full rollout.

Why a proxy is not the outcome

A proxy is only usable if it moves with the outcome at the effect size you care about. Validate it before the canary: take the last several settled cohorts, compute the rank correlation between proxy and settled outcome, and check it holds in the segment you are canarying. If the proxy explains little of the outcome variance, it can pass while the outcome fails: a false negative, and the expensive direction.

Arithmetic that decides the design

Say the settled-outcome baseline is 5% and you want to catch a 10% relative move (0.5pp absolute). Per-arm sample size ≈ 16·p(1−p)/δ² = 16·0.05·0.95/0.005² ≈ 30,400 accounts. At 5% of 100,000 daily active accounts, the canary accrues 5,000/day, so exposure alone takes ~6 days; add a 7-day settlement lag and the first fully-settled read is ~13 days out. That number, not the proxy, is what you are trading against.

Illustrative latencies and what gates what

OutcomeLatency (illustrative)Proxy visible in hoursGate
Settled payment / chargebacksettlement T+1–T+3; disputes weeks laterauth decline rate, 3DS challenge rate, refund rateproxy gates exposure; settled outcome gates promotion
Subscription retention30–90 daysday-1 activation, session depthsame
Batch / reconciliation jobone cyclejob failure rate, row-count deltacanary on a partition; the true outcome is cheap, so just wait one cycle
Fraud lossdays–weeksblock rate, manual-review queue depth, false-positive rateproxy gates; realised loss gates

Failure modes and how each is detected

  1. Proxy drift. The correlation was measured last quarter and no longer holds. Detect by recomputing proxy-vs-settled correlation on every settled cohort; halt when it falls below the level you validated at.
  2. Post-treatment conditioning. The settled cohort contains only users who stayed, so if the canary changes retention, the settled comparison is biased. Detect by comparing exposure-to-settlement attrition between arms; a gap wider than the metric's confidence interval invalidates the settled read.
  3. Assignment leakage. A user hits both versions. Log the version per request keyed by the assignment key; any key with more than one version in the window is contaminated. Assign on account ID, not session or device, when the outcome is account-level.
  4. Mix shift. The canary draws a different traffic mix. Detect with a chi-square on assignment counts (p < 0.001) plus pre-period covariate balance.
  5. Irreversible actions. Money moved, data deleted, mail sent. A canary cannot undo these; gate on the true outcome or take an explicit, written risk acceptance.

When not to canary

If the outcome latency exceeds your release cadence, a canary is the wrong instrument. Run a long-lived A/B with a permanent holdback, or a shadow run that computes the outcome without acting on it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design promotion and abort as an idempotent state machine.

Answer

What a strong candidate says first

Idempotency here means every actor converges on the same desired state, however many events arrive and whichever controller is alive. Three mechanisms: a durable row per (release, target) that every transition compare-and-sets; an operation key per command, so a retry returns the stored result instead of acting again; a reconcile loop that drives observed state to desired state rather than replaying the request.

Assume events arrive twice and out of order, any external call (traffic weight, rollout, flag flip) can succeed server-side while the client times out, and one controller owns a target at a time.

Commands carry an Idempotency-Key (the IETF draft header): same key and body returns the stored response, same key with a different body is 409, as Stripe does.

One row per target, six states

statenextguard
PENDINGPROMOTING, ABORTINGevidence frozen, lease held
PROMOTINGVERIFYING, ABORTINGall targets at desired weight
VERIFYINGPROMOTED, ABORTINGanalysis green, soak elapsed
PROMOTED—terminal for this operation key
ABORTINGABORTEDall targets at the recovery target
ABORTED—terminal; reopening needs a new key

Promotion leaves VERIFYING only on the evidence set frozen before the release starts; a post-release rollback is a new operation with its own key.

Postgres 16:

UPDATE release_target
   SET state = 'ABORTING', epoch = epoch + 1, updated_at = now()
 WHERE release_id = $1 AND target = $2
   AND state = 'VERIFYING' AND epoch = $3;
-- 0 rows: stale event or lost race. Return current state, HTTP 200, stop retrying.

epoch is a fencing token: a controller stalled 40 s in a GC pause writes 0 rows and is dropped.

Abort chooses a mode before it moves anything

  • Isolate: weight to 0 in about a second. Stops the bleed while you decide.
  • Roll back: the previous revision still exists and can read current data.
  • Roll forward: the migration already ran and the old revision cannot read the new schema; jump to a known-good revision.
  • Repair: retry a transient failure, such as a throttled image pull or exhausted node quota.

The deciding question is whether the last irreversible side effect is backward compatible: expand phase, roll back; after the contract phase, roll forward.

Worked trace: figures are examples

Release 812: revision 41 (v7) to v8, 100 pods, canary at 20%, 5-minute Prometheus analysis, SLO 99.9% over a 30-day month = 0.001 * 43,200 min = 43.2 minutes of error budget.

  1. t=0: lease won, CAS PENDING to PROMOTING, epoch 41 to 42, desired weight 20.
  2. t=0.2 s: the traffic API applies weight 20; the client times out at 3 s, recording nothing. The loop sees desired 20, observed 0, calls again: already 20, a no-op. Reconciling, not replaying.
  3. t=20 s: the controller OOMs. The lease (client-go defaults: 15 s, renewed every 2 s) expires at t=35 s and a standby takes it at epoch 43. The restarted old process writes with epoch 42 at t=38 s, gets 0 rows, exits.
  4. t=4 min: the analysis webhook fires twice; the unique index on (release_id, analysis_id) drops the second and returns the stored result.
  5. t=4 min 30 s: canary error rate 2.1% against a 0.4% baseline. At 2.1% the 43.2-minute budget lasts 43.2 / 0.021 = 2,057 minutes (34 hours); at 20% weight the fleet rate is 0.2 * 2.1% = 0.42%, so 10,286 minutes (7 days). Hours, not seconds: isolate now, roll back correctly rather than fast.
  6. t=4:31 weight 0; t=4:35 revision 41 rolls out. 100 pods, cached images, about 40 s at the default 25% surge.
  7. t=9 min: all targets report weight 0, revision 41 and a clean rate, so the CAS moves ABORTING to ABORTED. A duplicate abort matches no row and returns the stored terminal state with 200.

Failure modes and how you see them

failuresignal
duplicate webhookunique violation on (release_id, analysis_id)
crash mid-calldesired != observed for over 60 s
zombie writerstale_write_rejected counter, alert on any
partial routingone cluster's weight differs for 60 s
abort during abortsecond command sees ABORTING, returns in progress

When not to build this

If one Deployment is the whole release, Kubernetes already rolls back atomically by revision and keeps 10 by default (revisionHistoryLimit); this earns its keep when traffic, workload, flags and schema move together and abort sometimes has to go forward.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you coordinate automated rollbacks across interdependent microservices during a failed rolling deployment?

Answer

First I'd clarify two things: who owns the rollback (a progressive delivery controller like Argo Rollouts or Flagger, or a human) and whether we're allowed to roll back all services at once. I'll assume Kubernetes with a controller and a service mesh, and that atomic rollback of the whole graph isn't available.

The core answer: you don't coordinate rollbacks by rolling everything back together. You make rollback a forward transition each service can perform alone, then order the few cases where it can't. That means every service must run version N-1 against version N of its neighbours in both directions: expand/contract schema changes, new fields optional, breaking payload changes behind versioned routes. If that holds, rollback is per-service and ordering is irrelevant. If it doesn't hold, no orchestrator saves you.

Assuming it holds, the sequence when a canary fails:

  1. Halt. Set spec.paused: true on the Rollout/Deployment, or let the controller abort the canary. Stop scheduling new pods.
  2. Shift traffic before killing pods. Set the canary weight in the Istio VirtualService to 0 so ingress goes to the stable ReplicaSet. Don't let pod termination be what sheds traffic.
  3. Roll back the failing service only.
  4. Re-check the dependency direction before touching anything upstream.

The ordering rule: roll back the caller before the callee when the caller depends on new behaviour; otherwise roll back the callee alone. Trace it: Service A (caller) v2 calls an endpoint that only exists in Service B v2. B's canary fails. If B rolls back to v1 first, A's v2 gets 404s on every call. So either A tolerates the missing endpoint (feature flag off, fallback path) or A rolls back first. If A only uses the v1 endpoint that B v2 still serves, B rolls back alone and A stays put. The direction of the dependency, not the order of the deploy, decides this.

Failure modes worth naming:

  • Destructive migration. B v2 dropped a column; rolling B back to v1 crash-loops on the missing column. You see readiness probes failing seconds after the rollback starts. Prevention: reject non-additive migrations in the pipeline and make the drop a separate, later deploy.
  • Queue poison. v2 published messages v1 consumers can't deserialize; rolling both back leaves those messages unprocessed. You see consumer lag climbing and DLQ depth rising. Mitigation: consumers ignore unknown fields, and messages carry a schema version in headers.
  • Drain window. SIGTERM with terminationGracePeriodSeconds (default 30s): in-flight requests to canary pods must finish or be retried. If the mesh still routes to terminating pods, you get 5xx for the length of that window.

Two alternatives I'd mention. Roll forward instead of back: ship a fix, which sidesteps the schema problem entirely if the fix is small. Or roll the whole release train back together, which is easier to reason about but slower and only works if you kept the previous train's images and config.

The thing I'd actually probe: does the rollback controller know the dependency graph, or does it just roll back whichever service's canary failed? Most controllers do the latter. So the graph knowledge has to live in the compatibility contract, not in the orchestrator.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Roll back a release with long-lived connections.

Answer

Core answer (say this first)

Rolling back the code is the easy half. The hard half is the connection population still pinned to the new version: WebSockets, gRPC streams, SSE, and HTTP keep-alive sockets that outlive the deploy. Assume the old version is still running and can take traffic; assume you can't drop sessions without user-visible cost; assume the new version wrote state the old one may not read.

So the answer is a two-phase rollback, not a flip:

  1. Stop admitting new sessions to the new version: shift edge weight to zero for it, but don't kill it.
  2. Drain what's already connected, against a deadline you chose before the incident, with a force-close policy you can defend.

The old version stays at full capacity until the last new-version connection is gone. Only then do you scale the new version down.

Mechanism

Draining works because a long-lived connection is a lease, not a request. You can't reroute it; you can only ask the peer to end it and reconnect. Every protocol has a "go away" primitive:

ProtocolPrimitiveNotes
HTTP/2, gRPCGOAWAY frame with last-stream-idClient retries streams above that id; in-flight ones finish
WebSocketClose frame, code 1001 (going away) or 1012 (service restart)App must reconnect; no built-in resume
SSEServer closes; client reconnects with Last-Event-IDResume is in the spec
HTTP/1.1 keep-aliveConnection: close on the next responseCheap, no client work

The catch: GOAWAY and close frames are advisory. A client that ignores them keeps the socket open, and your drain deadline is what actually ends it.

Trade-offs: drain vs force-close

Drain is correct when sessions carry resumable state (a cursor, a sequence number, a replay buffer) or when a mid-stream drop costs the user work. Force-close is correct when the new version is corrupting state and every extra second makes the rollback harder, then you accept the drop and pay the reconnect cost.

Deciding criteria, in order: (1) Is the new version still writing bad state? If yes, force-close now. (2) Can the client resume from a token? If yes, drain to the deadline. (3) Neither? Force-close and tell users.

Failure modes and how you see them

  • Endpoint propagation lag. In Kubernetes, SIGTERM and endpoint removal race; kube-proxy and the ingress can keep sending traffic for seconds after the pod starts shutting down. Detection: 5xx or connection resets spiking after the drain starts, not before. Fix: a preStop sleep longer than propagation, and terminationGracePeriodSeconds (default 30 s) set above your drain deadline.
  • Drain deadline shorter than the longest session. Detection: force-closed count > 0 in your drain metrics. Fix: measure p99 session lifetime before you need it.
  • Resume token incompatibility. The new version's token format may not parse in the old version. Detection: reconnect failures with 4xx on the resume endpoint. Fix: version the token, or reject-and-restart rather than half-resume.
  • Old version can't read new state. Detection: errors on read paths that only touch rows written in the last N minutes. Fix: forward-compatible schema, or a one-way migration you don't roll back.

Worked timeline

Say p99 WebSocket session is 8 minutes and the ALB deregistration delay is at its 300 s default.

  • t+0: edge weight to old version = 100%. New version stops accepting.
  • t+0 to t+5: the 300 s deregistration delay drains idle HTTP connections; long-lived ones survive it.
  • t+5: send close 1001 to remaining WebSockets; clients reconnect to the old version.
  • t+8: p99 session gone. Force-close stragglers.
  • t+8: scale the new version to zero.

If your drain deadline is 300 s and p99 is 480 s, you force-close the top 1% every time: set the deadline from the measured p99, not from the default.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Coordinate background jobs during blue-green deployment.

Answer

Core answer (first 90 seconds)

Assume blue and green share one database and one queue; only the app tier is duplicated. If each environment had its own queue and datastore, this problem mostly disappears, so I'll state that assumption up front.

The rule I'd state: at any instant exactly one environment holds the right to produce effects for a given job identity, and that right is a lease with a monotonically increasing fencing token, not a flag a human flips at 2 a.m. Read-only validation can run in both environments; anything that writes, sends, or charges runs in one.

Why a lease, not a timing window

A cutover window assumes clocks agree and nothing is in flight. A lease makes ownership expire by itself, and the fencing token makes a stale writer harmless: the old holder may still be running, but its token is lower than the current one, so the sink rejects it. Timing alone can't do that: a paused process (GC, a 40-second stop-the-world, a network partition) resumes and writes as if nothing happened.

What owns what

job classexamplepreviewcutover
singleton schedulerKubernetes CronJob, Quartzsuspended in blueresume blue, suspend green
queue consumerKafka consumer group, SQSblue on shadow topic or pausedreassign group to blue
reconciliation sweepperiodic drift fixread-only in blueenable writes
outbound callbackpayment webhookrouted to greenrepoint to blue

Lease arithmetic

Kubernetes leader election defaults are leaseDurationSeconds 15, renewDeadline 10, retryPeriod 2. A stalled leader can believe it still leads for up to 15s after its last successful renew, and a new leader can take over once the lease expires. So the overlap window is bounded by the lease duration. Set the idempotency-key TTL to at least leaseDuration plus the longest job runtime, or a redelivered job after the switch will be treated as new.

Deciding the cutover

Don't cut on a single backlog reading. Watch the trend: Kafka consumer-group lag, or SQS ApproximateNumberOfMessagesVisible, should be flat or falling for a full drain interval before you reassign. If lag is climbing, the new consumer isn't keeping up and you hold.

Failure modes and how you see them

  • Duplicate singleton: two schedulers fire. Detect by counting distinct holderIdentity per job per minute; alert when it exceeds one.
  • Split brain: old holder still writing. Detect by a fencing-token-rejection counter at the store; a nonzero rate means a stale writer is alive.
  • Partial cutover: some consumers moved, some didn't. Detect by lag growing on one side only.
  • Redelivery during switch: SQS visibility timeout (default 30s, max 12h) or Kafka max.poll.interval.ms (default 300000) expires mid-cutover and the message is processed twice. Detect by duplicate-effect count.

Trade-offs

Stop-the-world (pause everything, cut, resume) is simplest and correct, at the cost of a backlog drain. Dual-run with idempotency only works when every effect is naturally idempotent; it fails for emails and payments. Lease plus fencing costs a shared coordination store and fencing-aware sinks, and buys no downtime. Pick it when effects aren't idempotent and downtime isn't acceptable.

Rollback

Switch back only if blue's writes are readable by green's schema version and the queue protocol is unchanged; otherwise roll forward. Test duplicate scheduler, lease loss, partial cutover and recovery, but assert on the detection signals above, not on "it worked".

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Use traffic mirroring safely.

Answer

Core answer (first 90 seconds)

Mirroring earns its cost when you need evidence about a candidate's behaviour under real request shapes (cardinality, payload variety, header edge cases) that synthetic load won't reproduce, and the candidate is read-only or idempotent. Say that, then state the three constraints you'll hold: the mirror is sampled, the candidate is isolated, and no mirrored byte can reach a user or a shared datastore.

If the change writes, mirroring is the wrong tool. Use a canary with real traffic and a rollback, or a purpose-built simulator. Mirroring a payment or notification path is how you send a duplicate charge.

Mechanism

The mirror is a second upstream call the proxy makes after dispatching the real request. The client's response is already committed to the primary, so the mirrored response is discarded: that's the safety property, and it's also the failure mode: nothing in the client path tells you the mirror broke. You need the mirror's own telemetry.

Leakage happens when the mirror isn't actually a separate path: same upstream pool, same connection, or a shared response cache. Then a candidate's response can be served to a real user, or a candidate's write can be read by the primary.

Shadow state diverges because the candidate sees a copy of the request but not a copy of the side effects the primary produced. Any read-after-write in the candidate returns stale or missing data, and any write lands in a store the primary also uses.

Config

Envoy route-level mirroring, sampled:

YAML
route:
  cluster: primary
  request_mirror_policies:
    - cluster: candidate
      runtime_fraction:
        default_value: {numerator: 1, denominator: HUNDRED}  # 1%

runtime_fraction defaults to 100%: mirroring everything is the default, so set it explicitly. Istio's mirrorPercentage behaves the same way (default 100.0). NGINX's mirror directive (ngx_http_mirror_module, 1.13.4+) ignores the subrequest's response entirely, which is the behaviour you want.

Tag the copy yourself, X-Shadow: true, and strip it at the edge so it can't be replayed inward.

Arithmetic

20k rps at 1% = 200 rps to the candidate. If each mirrored request issues 3 queries at 5 ms, that's 600 qps against a 20-connection pool: 20 / 0.005 = 4,000 qps of headroom, so the pool isn't the limit. The candidate's third-party quota is. 200 rps × 86,400 s = 17.3M mirrored calls/day; a vendor plan at 1M/day will 429 by mid-morning.

Trade-offs

  • Mirror: real shapes, no user risk, but doubles downstream load and needs isolation.
  • Recorded replay (GoReplay, VPC Traffic Mirroring to a tap): repeatable, offline, but the recording ages and you must scrub PII.
  • Synthetic from the OpenAPI spec: cheapest, bounded, but misses the long tail that motivated mirroring.
  • Canary with rollback: the only honest option for writes.

Decide on the write path: read-only → mirror; writes → canary or simulator.

Failure modes

  • Duplicate side effects: candidate writes to a shared queue. Detect by diffing queue depth and row counts between primary and candidate.
  • Response leak: candidate response served to a user. Detect by asserting the mirror cluster is unreachable from the client-facing listener, and alerting on any response whose body hash matches a candidate-only marker.
  • Quota exhaustion: 429s from a vendor only the mirror consumes. Detect by tagging mirror egress and alerting on vendor 429 rate.
  • Silent mirror death: mirror cluster down, primary unaffected. Detect with a mirror success-rate SLI, not the primary's.

Stop conditions: mirror error rate > 5%, candidate p99 > 2× primary, or any leak signal. Kill the mirror, not the primary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Plan database changes across a mixed-version rollout.

Answer

Clarify first. I'd ask: which engine and version, table size, is the change additive or a rename/type change, and how long can two app versions coexist? I'll assume Postgres 15, a 400M-row orders table, 24/7 traffic, rolling deploys across 40 pods, and a change that adds a currency_code column derived from the existing currency text column.

Core answer: expand, migrate, contract. With the app and the schema moving on separate clocks.

Expand. ALTER TABLE orders ADD COLUMN currency_code text; is metadata-only on Postgres 11+ when the default is non-volatile, so it takes ACCESS EXCLUSIVE for milliseconds. Then add the constraint as NOT VALID so it doesn't scan:

SQL
ALTER TABLE orders ADD CONSTRAINT orders_currency_code_nn
  CHECK (currency_code IS NOT NULL) NOT VALID;

Deploy app version N: it writes both currency and currency_code, and reads currency. Old pods still running during the rollout write only currency, which is fine because nothing reads currency_code yet.

Migrate. Backfill in bounded batches, checkpointed, from the application side:

SQL
UPDATE orders SET currency_code = currency
WHERE id IN (
  SELECT id FROM orders
  WHERE id > $1 AND currency_code IS NULL
  ORDER BY id LIMIT 1000
)
RETURNING id;

After each batch, write max(id) to a migration_progress row and sleep 50 ms. Batches are bounded because each one holds row locks and generates WAL; a single 400M-row UPDATE would hold a transaction open for hours, bloat the table, and stall vacuum. The arithmetic: 400M / 1000 = 400k batches, at roughly 20 ms of work plus 50 ms sleep ≈ 7.8 hours. If that's too slow, raise the batch to 5000 and cut the sleep, watching replica lag.

Before each batch, read pg_stat_replication on the primary; if replay_lag on any replica exceeds 5 s, sleep 1 s and re-check. That's the guard, not a hope.

Reconcile. Before contract, SELECT count(*) FROM orders WHERE currency_code IS DISTINCT FROM currency; must be 0. Rows whose currency isn't a valid ISO code go to migration_quarantine(order_id, raw_value, reason) and are excluded from the count: that's what quarantine is for: it separates "not yet migrated" from "cannot be migrated" so the backfill can finish and a human can fix the stragglers.

Contract. After every pod runs N+1 and the rollback window closes, ALTER TABLE orders VALIDATE CONSTRAINT orders_currency_code_nn; (SHARE UPDATE EXCLUSIVE, doesn't block reads or writes), then SET NOT NULL, Postgres 12+ uses the valid CHECK constraint to skip the full scan, then drop currency.

Failure modes and how I'd see them.

  • CREATE INDEX CONCURRENTLY fails partway and leaves an INVALID index. Detect: SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;. Drop and retry; it can't run inside a transaction.
  • A long-running read transaction blocks the ACCESS EXCLUSIVE lock at contract. Set lock_timeout = '3s' and retry in a loop; detect the blocker via pg_locks joined to pg_stat_activity.
  • Backfill deadlocks with app writes (SQLSTATE 40P01). Small PK-ordered batches plus retry-on-deadlock.
  • A stale pod writes currency after contract drops it and starts throwing 500s. That's exactly why contract waits for the rollback window rather than for the deploy to go green.

Alternatives, and when I'd pick them. Big-bang, one ALTER plus one deploy, is fine under a million rows or inside a maintenance window; it's not viable at 400M with 24/7 traffic. gh-ost or pt-online-schema-change handle the DDL without a blocking lock on MySQL, but they copy the table and swap it; they don't do the dual-write or the derived-data backfill, so you still need expand/contract around them. Read-replica cutover (build the new schema on a replica, replay, promote) suits a full re-model, but you lose independent app rollback.

Rollback criteria, stated plainly. App rollback is allowed while currency still exists and is still written. Once contract runs, rollback means restoring from backup, so contract is gated on the rollback window closing (I'd use 7 days, one full business cycle) not on the deploy succeeding.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Respond when a canary corrupts data.

Answer

First 60 seconds: I’d stop the canary’s writes, not just its traffic. Scale the canary deployment to zero and flip the write-path feature flag off. Then declare the incident, preserve evidence, bound the blast radius, and repair data with an idempotent versioned backfill. Traffic rollback alone is insufficient because it doesn’t undo writes or retract events.

Assumptions: the canary writes to a shared datastore and emits events to downstream consumers. If the canary has an isolated database, drop it and restore; the hard case is shared state.

Mechanism: corruption propagates because the canary writes bad rows and publishes events. Downstream consumers read those rows or events and act: send email, update warehouse, mark shipped. Rolling traffic back stops new writes but leaves old bad state and already-emitted events. So you need compensating writes and events, not just routing.

Concrete steps:

  1. Stop writes: kubectl scale deployment checkout-canary --replicas=0. If writes go through a flag, set it false. Check for async writers: kafka-consumer-groups --bootstrap-server <broker> --group checkout-writer-v2 --describe to see lag; pause that consumer group if it’s still draining canary messages.
  2. Preserve evidence: canary version, pod IDs, request IDs, Kafka offsets, DB transaction logs. In Postgres, pg_stat_activity shows active canary sessions; pg_terminate_backend(pid) kills them if needed.
  3. Bound blast radius: query by app_version='2.3.1' and the canary’s time window. Suppose the canary was 5% of 200 pods (10 pods), ran 12 minutes, and wrote 1,200 orders; 340 are marked shipped with no payment_id, and 80 confirmation emails went out. Those are hypothetical figures for the trace below.
  4. Repair with an idempotent, versioned backfill. Do not restore from backup unless downstream hasn’t consumed the bad state; PITR loses legitimate writes after the canary started.
OptionStops new corruption?Fixes existing rows?Handles downstream?When wrong
Rollback traffic onlyYesNoNoAlways insufficient if writes occurred
PITR to before canaryYesYes, by discardingYes if downstream not consumedLoses legitimate writes; downtime
Targeted repair + compensating eventsYesYesYes if consumers idempotentIf external side effects irreversible (email sent)

Worked trace: Postgres 15, hypothetical schema. Add a repair version column, then batch-update only canary rows.

SQL
ALTER TABLE orders ADD COLUMN IF NOT EXISTS repair_version text;

WITH bad AS (
  SELECT order_id
  FROM orders
  WHERE app_version = '2.3.1'
    AND status = 'shipped'
    AND payment_id IS NULL
    AND created_at >= '2025-01-15T10:00:00Z'
    AND created_at <  '2025-01-15T10:12:00Z'
    AND repair_version IS NULL
  ORDER BY order_id
  LIMIT 100
)
UPDATE orders o
SET status = 'pending_payment',
    repair_version = 'repair-2025-01-15-01'
FROM bad
WHERE o.order_id = bad.order_id
RETURNING o.order_id;

Trace: first run selects up to 100 bad order_ids, updates them, returns those IDs. Second run with the same repair_version filter sees repair_version IS NULL false for those rows, so it selects the next 100. When no rows remain, it returns zero. Each batch runs in a transaction: crash before commit rolls back; crash after commit means rerun skips. That is idempotent per row.

Trade-offs: targeted repair is faster and preserves legitimate writes, but it requires a reliable audit of canary writes and idempotent consumers. PITR is simpler but loses legitimate orders and may take hours. If the canary wrote to a ledger, you cannot just update status; you need reversing entries. If it sent 80 emails, you cannot unsend them: send a correction or flag the account.

Failure modes: canary still writing via a queue after scale-down; check consumer lag and pause the group. Repair job double-refunds if not idempotent; use repair_version and a unique constraint. Downstream consumer not idempotent; duplicate emails. Detection: control totals. SELECT count(*) FROM orders WHERE status='shipped' AND payment_id IS NULL should return 0 after repair; reconcile with the payment provider. Rerun the scoped canary scenario only after hard invariants are in place.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design deployment recovery when rollback is unsafe.

Answer

When rollback is unsafe, the usual reasons are: a database migration already ran and new columns are populated, a protocol change is not backward-compatible, or a security fix must stay. I'd assume we have feature flags, canary deploys, and observability in place. The goal is to stop user harm, then roll forward with a minimal, verified change.

First 60 seconds: I'd halt exposure. If the change is behind a feature flag, disable it. For example, in LaunchDarkly or Unleash, you flip the flag to off, but be aware of client-side caching: many SDKs cache flag values for 30 seconds to 5 minutes, so you might need to force a refresh or wait. If it's not behind a flag, I'd isolate traffic: route users to the old version using a service mesh like Istio or Envoy, but only if the old version can still read the new data. If neither is possible, I'd consider a write pause or read-only mode. A write pause means blocking all writes at the database or API layer (for example, setting PostgreSQL to read-only with ALTER DATABASE ... SET default_transaction_read_only = on;) but that breaks any user journey that writes, so it's a last resort.

Then I'd preserve evidence: snapshot logs, metrics, and a copy of the database state. I'd determine compatibility: can old code read new data? Can new code read old data? This decides whether traffic isolation is safe.

Now the trade-offs. Feature disablement is fastest (seconds) and lowest blast radius, but only works if the feature is properly flagged and the flag evaluation isn't cached. Traffic isolation is next fastest (minutes) but requires two versions running and compatible data; it fails if the new version wrote data in a format the old version can't parse. Degraded/read-only mode stops writes but keeps reads; it's wrong if the core user journey is a write. Write pause is the most drastic: it stops all writes, causing upstream backpressure. For example, Kafka consumer lag grows, retry queues fill, and you might get a retry storm when you resume. Roll-forward is often the right answer: deploy a small fix that makes the new code compatible with the new data. But it requires a verified fix and a canary. Idempotent repair is for after the fact: fix data using a trusted source, but it's slow and risky.

A concrete failure mode: you disable a feature flag, but the flag is evaluated on the server and cached in a CDN for 5 minutes. Users still see the bug. Detection: monitor flag evaluation latency and cache hit rate; alert if the flag change hasn't propagated within 2 minutes. Operational cost: support tickets and trust damage.

Another: you roll forward with a fix, but the fix has a bug because it wasn't tested against production data. Detection: canary analysis. Deploy to 5% of traffic for 10 minutes, compare error rate and latency to baseline. If error rate increases by more than 0.5%, roll back the canary (which is safe because it's a new deploy, not a rollback of the original).

Artefact: a decision table.

OptionSpeedBlast radiusData safetyWhen wrong
Feature disablesecondslowsafeflag cached, or change not flagged
Traffic isolationminutesmediumrequires compatible dataold code can't read new data
Read-only modeminuteshighprevents writescore journey is a write
Write pausesecondsvery highprevents corruptionupstream backpressure, retry storm
Roll-forwardhourslow if canarysafe if verifiedfix not verified, or can't be small
Idempotent repairhoursmediumsafe if trusted sourceno trusted source, or not idempotent

Finally, I'd document why rollback was unsafe and add a compatibility gate: e.g., require that all schema migrations are backward-compatible for at least one deploy cycle, and that protocol changes support both versions for a window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How do maxSurge, maxUnavailable, minReadySeconds, progressDeadlineSeconds, readiness/liveness gates, and termination grace interact with capacity headroom and disruption budgets to set rollout speed and safety, and how would you tune them for a service with tight capacity or long startup times?

Answer

The 90-second answer

Two independent clocks set rollout speed. The concurrency clock is maxSurge/maxUnavailable: how many pods the controller may add above and remove below replicas at once. The per-pod clock is startup probe + readiness probe + minReadySeconds: how long a new pod takes to be counted Available. Rollout wall-clock ≈ (replicas / step size) × per-pod clock. progressDeadlineSeconds is a watchdog on the gap between progress events, not on total rollout time. terminationGracePeriodSeconds is the old-pod clock and runs in parallel with the new-pod clock, so it only extends the rollout when it exceeds the per-pod clock.

PDBs are not in the rolling-update path. The Deployment controller scales ReplicaSets directly and never calls the Eviction API, so a PDB cannot block or slow a rollout. It binds on a concurrent node drain, and that is where maxUnavailable and minAvailable collide, because the rollout has already spent the disruption budget the drain needs.

Defaults: maxSurge: 25%, maxUnavailable: 25%, minReadySeconds: 0, progressDeadlineSeconds: 600, terminationGracePeriodSeconds: 30. Percentages round up for maxSurge and down for maxUnavailable. maxSurge and maxUnavailable cannot both be 0, and progressDeadlineSeconds must be greater than minReadySeconds (API validation).

Worked trace

replicas: 10, p99 startup 45s, minReadySeconds: 30. A new pod is Ready at t=45s and Available at t=75s.

maxSurge: 1, maxUnavailable: 0: maxTotal 11, minAvailable 10.

told RSnew RSavailable
010110
4510110 (Ready, not Available)
759210
1508310

One pod per 75s cycle, 10 cycles → ~750s, capacity never below 10.

maxSurge: 0, maxUnavailable: 1: maxTotal 10, minAvailable 9. Old RS drops to 9 first, then new RS goes to 1. Same ~750s, but available oscillates 9↔10: the floor is 90% for 75s of every cycle.

Now add minAvailable: 9 to a PDB. During the second rollout, available sits at 9 for most of each cycle, so kubectl drain is denied until a new pod becomes Available. With minAvailable: 10 the drain never proceeds at all: it hangs indefinitely.

Tuning

Tight capacityLong startup (p99 90s)
maxSurge / maxUnavailable0 / 11 / 0
startup probenonefailureThreshold 18 × period 10s = 180s
readiness probeperiod 5s, failureThreshold 3period 5s, failureThreshold 3, initialDelay 0
minReadySeconds1060
progressDeadlineSeconds300600
terminationGracePeriodSeconds30120
PDBminAvailable: replicas-1minAvailable: replicas-1
YAML
startupProbe:
  httpGet: {path: /healthz, port: 8080}
  periodSeconds: 10
  failureThreshold: 18   # 180s budget > 90s p99
readinessProbe:
  httpGet: {path: /ready, port: 8080}
  periodSeconds: 5
  failureThreshold: 3
minReadySeconds: 60
progressDeadlineSeconds: 600

Failure modes

  • minReadySeconds: 0 with a shallow readiness probe. Pods enter the Service before caches and connection pools warm; p99 spikes for the first ~30s of each pod's life. Detect by slicing latency by pod age.
  • terminationGracePeriodSeconds shorter than the longest in-flight request. SIGKILL mid-request → 502s at the ingress, correlated with rollout timestamps.
  • Endpoint-removal race. The pod leaves the EndpointSlice asynchronously; kube-proxy or the ingress may still route for a few hundred ms after SIGTERM. A preStop: sleep 5 closes it, and counts against the grace period.
  • progressDeadlineSeconds too low. The rollout is marked ProgressDeadlineExceeded while pods are still starting. It does not roll back; the controller keeps trying and you must kubectl rollout undo. Check kubectl get deploy -o jsonpath='{.status.conditions}'.
  • maxSurge too high with no headroom. Pods go Pending, the rollout stalls, and the deadline fires.

The two hard cases

Tight capacity. maxSurge: 0, maxUnavailable: 1, PDB minAvailable: replicas-1. Then check the arithmetic: at 10 replicas and 60% CPU, 9 replicas is 67%. Fine. At 85%, 9 replicas is 94%, and one more failure tips it. If you cannot lose any capacity and have no headroom, run low-priority pause pods under a lower PriorityClass; the surge pod preempts one, so you pay for the slack only during rollouts.

Long startup. Size the startup probe so failureThreshold × periodSeconds exceeds p99 startup (18 × 10s = 180s for a 90s p99), set readiness initialDelaySeconds: 0 because the startup probe already gates it, and use minReadySeconds for warmup after Ready. Set progressDeadlineSeconds above startup + minReadySeconds + slack, and use maxSurge: 1/maxUnavailable: 0 so you never drop capacity while waiting.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Migrate from all-at-once releases to progressive delivery.

Answer

The 90-second answer

Before anything else I'd pin down three things: what the release unit is (one service or a fleet), whether it carries state or schema, and what SLO the service already holds. Progressive delivery means decoupling deploy from release: the new artifact runs in production, but only a slice of traffic reaches it, and a controller widens or kills that slice based on metrics. I'd migrate in three moves.

One: make the artifact immutable and the schema backward compatible. Every release is a tagged image digest, never a mutable tag, and any DB change is expand/contract: add the new column nullable, deploy code that writes both, backfill, then drop the old column in a later release. Without this, a canary running old code against a new schema is the failure you cannot roll back.

Two: put a traffic-splitting controller in front. Argo Rollouts or Flagger, with Istio, Linkerd, or Gateway API HTTPRoute weights underneath. Flagger's Canary CRD defaults to interval: 1m, stepWeight: 10, maxWeight: 50, threshold: 5: five failed checks before it rolls back.

Three: start manual, automate later. The first rollout goes 1% → 5% → 25% → 50% → 100% with a human promoting each step. Once the gates have caught a real regression, you let the controller promote.

The config

YAML
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
  name: checkout
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout
  service:
    port: 9898
  analysis:
    interval: 1m
    threshold: 5
    maxWeight: 50
    stepWeight: 10
    metrics:
      - name: request-success-rate
        thresholdRange:
          min: 99
        interval: 1m
      - name: request-duration
        thresholdRange:
          max: 500
        interval: 1m

The stages

weightholdgatepromotion
1%10m5xx < 0.5%, p99 < 500msmanual
5%10msame, plus checkout success within 2% of baselinemanual
25%15msamemanual
50%15msameauto
100%——auto

What a breach looks like

At 25%, the canary's 5xx rate is 1.8% against a 0.5% gate. Flagger's Prometheus check fails on five consecutive 1m intervals, so at minute five it sets the canary weight to 0, scales the canary Deployment down, and emits a Synced=False event. Argo Rollouts gets there differently: the AnalysisRun fails, the Rollout aborts, weight goes to 0, and the Rollout sits in Degraded until you run kubectl argo rollouts undo. Either way the primary never moved.

Failure modes I'd watch

  • Canary gets no traffic. Routing is misconfigured, so the canary's metrics are empty and look perfect. Detect by comparing achieved to configured weight: sum(rate(http_requests_total{rollout="canary"}[5m])) / sum(rate(http_requests_total[5m])) should track the configured weight within a few points. Alert if it drops below half.
  • Metrics aggregated across versions. A 5% canary with a 20% error rate moves the fleet number by 1%: under the gate. Query per-version using the label your controller adds: rollouts-pod-template-hash for Argo Rollouts, pod-template-hash for a plain Deployment.
  • Sticky sessions. A user hits canary, then primary, and sees a flipped feature. Use consistent hashing on a session cookie so a user stays on one version for the rollout.
  • Controller outage mid-rollout. Traffic freezes at the current weight: the canary keeps serving, nothing advances. Runbook: kubectl argo rollouts abort, or scale the canary to zero.
  • Stateful services. A canary that writes a new column the old version cannot read breaks the primary. Expand/contract, and keep the canary read-only against the new schema until the contract step.

Emergency fallback

Keep the all-at-once path, but gate it: it needs an incident channel and a named approver, and it is logged. Retire it per service once that service has run progressive delivery through a real regression and rolled back cleanly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Measure deployment-strategy effectiveness.

Answer

What I'd say first

"Effectiveness" isn't one number. A deployment strategy has one job: get a change to full exposure while capping the damage if it's bad, and recover cheaply when it is. So I'd measure three things: how much bad traffic got served before we noticed, how fast and how reliably we recovered, and what the strategy cost in capacity and operator attention. I'd assume a service doing ~1,000 rps with SLOs on error rate and p99, canary steps at 1/5/25/100%, and feature flags for anything user-visible.

The metric that matters most: exposure before detection

This is the integral of traffic share over time until the guardrail fires. It's the only metric that directly answers "how much damage could this strategy have done."

Worked example: a bad version at 5% canary for 20 minutes before the guardrail trips serves 0.05 × 1,000 rps × 1,200 s = 60,000 bad requests. The same bug at 100% with detection in 4 minutes serves 1,000 × 240 = 240,000. The canary bought a 4× reduction: that's the number to put in the review, not "we use canaries."

Time to sufficient evidence

Canary bake time should be set by the subtlest guardrail, not the loudest. Detecting an error-rate jump from 0.5% to 2% at 80% power needs roughly 860 requests per arm: at 5% of 1,000 rps that's about 17 seconds. Detecting a 10% relative conversion drop (3.0% → 2.7%) needs roughly 48,000 per arm, about 16 minutes at the same share. A 5-minute bake catches crashes and misses revenue regressions. That's a design decision, and it should be written down.

Guardrail quality

Precision is the share of trips that were real regressions; recall is the share of real regressions caught. Low precision means auto-rollback fires on noise and operators start ignoring it. Low recall means bad releases reach 100%. Track both, and treat a telemetry gap as fail-closed, not pass.

Recovery and cost

Rollback success rate (rollbacks that restore the last good state without a human), time from detection to SLO recovery, and roll-forward versus rollback: rollback is often impossible after a schema migration or once new code has written data. Capacity: blue/green needs 2× during cutover; Kubernetes rolling updates default to maxSurge 25% / maxUnavailable 25%; canary costs roughly the canary share. Flag debt: a flag still at 100% 30 days after rollout is a cleanup ticket.

Trade-offs

strategyexposure controlrollbackcostwrong when
canarybestredeploy~canary sharetraffic too low to reach power
blue/greennone during cutoverinstant switch2× capacityshared state or schema
rollingnoneredeploy25% surgeyou need a kill switch
flag rolloutper-cohortflip flagflag debtchange is in the data layer

If a service sees 1 rps, a canary can't reach statistical power: you're just delaying the release. Use blue/green for instant revert, or accept a flag with a manual kill switch.

Failure modes and how I'd catch them

  • Guardrail on the wrong signal: canary error rate is clean but a downstream consumer regressed. Detect by measuring the edge SLO, not just the service.
  • Unrepresentative canary: routed to one AZ or internal users. Detect by comparing canary baseline to control before promoting.
  • Rollback thrash: rollback → re-promote loops. Detect by counting cycles per release.
  • Stale flag: nobody knows what "off" means. Detect with a flag-age report.

What I wouldn't rank on

Raw deployment frequency or auto-promotion rate. They reward shipping, not safety. DORA's elite change-failure band sits around 5%; use it as a reference, not a target to game.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Review deployment strategy before production launch.

Answer

What I'd say in the first two minutes

Reviewing a deployment strategy is really one question: if this release is bad, how fast can we stop the bleeding, and how much damage lands before we do? Rolling, blue-green, canary and flags are just means to that end. So I pin three things before I look at any config: the exact artifact, the SLO in numbers, and who holds abort authority.

Assumptions I'd state out loud: Kubernetes, ~40 replicas, a Postgres schema change riding along, p99 latency SLO of 300 ms, 99.9% availability. Change any of those and the review changes.

Pick the strategy from rollback time and blast radius

StrategyRollbackCostUse when
Rollingredeploy previous image, minutesnone extrastateless, schema backward-compatible
Blue-greenflip Service selector, seconds2x capacity at cutoverneed instant rollback, migration decoupled
Canaryautomated, secondssmall extra capacityuser-facing, SLO is measurable
Flagtoggle, millisecondsflag debt, code branchesdecouple deploy from release

The deciding criterion is rollback time versus blast radius. If a bad version can corrupt data, no rollout strategy saves you: that's an expand/contract migration problem, not a deployment one.

Why canary works, and the number that decides it

Canary bounds blast radius by traffic share, and it only works if the analysis metrics are the ones users feel. Take a Flagger canary configured with stepWeight: 10, maxWeight: 50, interval: 1m, threshold: 5. That's five one-minute steps to 50%, then promotion; five consecutive failed checks trigger rollback. At 2,000 rps peak, 50% weight puts 1,000 rps on the new version, and five minutes of bad checks means up to ~300,000 requests hit it before rollback. If that number is unacceptable, you lower maxWeight or shorten interval: you don't add more dashboards.

The Kubernetes defaults that bite

A Deployment defaults to maxSurge: 25% and maxUnavailable: 25%. On 40 replicas that's 10 pods down at once. At 2,000 rps peak, 50 rps per pod, 30 healthy pods give 1,500 rps: below peak, so you saturate. For a latency-sensitive service I'd set maxUnavailable: 0 and maxSurge: 25% instead. Also: progressDeadlineSeconds defaults to 600, and when it trips the Deployment reports ProgressDeadlineExceeded but does not roll back on its own. Someone has to.

Mixed-version compatibility

During any rolling update, old and new pods serve simultaneously, so the release must be compatible with itself. Prove it, don't assume it: schema changes go expand (add nullable column) → backfill → switch reads → contract (drop) across separate releases; API changes are additive; and you run an integration test with old and new binaries side by side. Background jobs and consumers must tolerate both message shapes.

Failure modes and how I'd detect them

  • Readiness probe too shallow: pod marked ready before warmup, users see 502s. Detect by comparing readiness latency against first-request latency.
  • Missing canary metrics: a Prometheus query returning no samples is a failed check, not a pass. Alert on analysis runs with zero samples.
  • Stuck rollout: ProgressDeadlineExceeded with no automatic rollback. Alert on it explicitly.
  • Artifact drift: confirm the running image digest matches the built digest, not the tag. Tags are mutable.

What I'd reject on

I won't sign off on a completed rollout alone. I'd reject if rollback is manual and untested, if the canary has no abort authority named, if the schema change isn't expand/contract, or if the artifact can't be traced by digest to the running pods. Residual gaps get written down, not waved through.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design deployment strategy for a multi-region service.

Answer

What I'd say first

Three things decide this: is the service active-active or active-passive, what's the deployment unit (code, config, schema), and what rollback means per region. I'll assume active-active, a shared schema with per-region replicas, and a global control plane: the hard case. If it's active-passive, the answer changes: you deploy the idle region first with zero user traffic.

The strategy is one region at a time, canary inside the region, and promotion gated on evidence that only shows up after the canary has been live a while. Region order is chosen so the first region is the cheapest to lose and still representative of the rest.

Region order

Don't start with the region that hosts the control plane. If us-east-1 runs your deploy orchestrator and your global config store, a bad deploy there takes out the ability to fix every other region. Start with a small, low-traffic region that still exercises the real code paths: same payment provider, same data shape. If only one region hits a code path, it isn't a canary, it's a special case.

Inside a region

1% of pods, hold 30 minutes. Then 10%, 50%, 100%. After the region is fully on the new version, hold for one full traffic cycle, 24 hours covers the daily peak, before touching region two.

Gates, as example policy numbers:

gatethresholddetected by
5xx ratecanary ≤ 1.2× baseline over 30 minper-version error counter
p99 latency≤ 1.15× baselinehistogram split by version tag
replication lagp99 < 2 s, max < 10 spg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn()), or Aurora's AuroraGlobalDBReplicationLag
saturationCPU < 70%, connection pool < 80%host and pool metrics
businesscheckout success within 0.5% of baselinefunnel counter by version

Trade-offs

Active-active vs active-passive: passive lets you canary with no user traffic, the cheapest possible test, but it never sees the real traffic mix. Active-active tests reality but every region is live.

Blue/green per region vs progressive shift: blue/green rolls back by flipping the load balancer, seconds, but doubles capacity and doesn't test gradual load. Progressive tests load but rollback is a redeploy.

When not to use per-region sequencing: a global singleton (leader-elected writer, global lock, single Kafka partition) isn't isolated by region order. Deploy its clients compatibly first, then the singleton.

Failure modes

  • Stale control plane: two regions deploying at once, one writes config the other doesn't know. Detect with a version-skew metric; alert if more than one version is active.
  • Non-backward-compatible schema: the old region can't read new rows. Use expand/contract (add column, deploy readers, backfill, drop old) and have the canary read new-schema data on the old version.
  • Cross-region spillover: failover sends traffic to a region still on the old version. Tag requests with region and version, alert when mixed versions serve the same user.
  • Replication lag spike: new code writes more, replicas fall behind, reads go stale. Watch the lag metric and a read-your-writes probe.

Blast radius, with numbers

Five regions, roughly equal traffic. Canary at 1% in one region is 0.2% of global traffic. Deploy all five at once at 1% and you're at 1% global: sequencing cuts initial exposure 5×. If the first region is only 8% of traffic, the canary is 0.08% global.

That's the shape: cheapest region first, canary inside it, gate on lag and error budget, hold a full cycle, then move.

Curated: · Written: · Reviewed:

Difficulty: Hard