Production DeploymentVol. 16 · Part XVI
0 / 0

Shelves / Production Deployment

DP·192

Zero-Downtime Deployment

Releasing new versions while users keep working: what "zero downtime" means and what breaks it; rolling deploys in Kubernetes (maxSurge, maxUnavailable, minReadySeconds, PodDisruptionBudgets); startup, liveness and readiness probes and their failure modes; graceful shutdown from first principles — the termination sequence, the endpoint-removal race, preStop, connection draining — demonstrated with a load-balancer experiment in Go (168 failed requests to zero); graceful shutdown in Spring Boot, Go, Rust, Node and Python; backward-compatible APIs and events (tolerant readers, additive changes, versioning); database compatibility; canary releases with automated analysis in Argo Rollouts and the statistics of how long a canary must run; blue/green; feature flags and dark launches; long-lived connections, workers and front-end assets; and a release runbook.

22 topics · ~26 min read · 32-question quiz
Updated Suggest a correction

Start here: replacing the engine while the car is moving

A zero-downtime deployment replaces the running version of a service with a new one while users keep using it, with no errors and no maintenance page. It's routine at good companies and still the source of many small outages, because a deploy is the moment when old and new code, load balancers, connections and databases all have to agree.

What actually happens in a rolling deploy

With two or more copies (instances) of a service behind a load balancer, you replace them one at a time:

  1. Tell the load balancer to stop sending new requests to instance A (drain).
  2. Let A finish the requests it's already handling (graceful shutdown).
  3. Stop A, start the new version as A′, and wait until it reports ready.
  4. Repeat for the next instance.

During the deploy, old and new versions serve traffic at the same time, so every change must work alongside the previous version: APIs, message formats and database schemas (chapter 191).

Measured: three ways to restart the same service

The lab deployed version 2 of a two-instance service behind HAProxy while 20 clients sent requests continuously (about 4,600 requests in 12 seconds):

How each instance was stopped Failed requests
killed instantly (kill -9, like a crash) 194 (connection errors and 503s)
asked to stop (SIGTERM), finishing in-flight requests 166 (503s)
drained first: report "not ready", wait 2 s, then SIGTERM 0

Graceful shutdown alone wasn't enough: the load balancer kept sending new requests to the stopping instance until its health check noticed. Draining first (in Kubernetes: a readiness probe plus a short preStop delay) closed that gap. In every run, both versions answered requests during the deploy.

How deep to go in zero-downtime deployment

Volume 17 defines six mastery levels; for zero-downtime deployment they look like this:

Level You can…
L1 explain rolling, blue/green and canary deploys, probes and feature flags
L2 configure probes, graceful shutdown and a rolling deploy for a service
L3 explain connection draining, version compatibility and the interaction with load balancers
L4 find the cause of errors during deploys from load balancer and app logs
L5 design a release process with canaries, automated analysis, flags and rollback
L6 run progressive delivery across many services with SLO-based gates

What breaks during a deploy

"Zero downtime" means users don't notice a release: no failed requests, no error pages, no lost work, no latency spikes beyond SLO. A deploy replaces running processes, and every replacement is an opportunity to break something:

  • Requests in flight on a process that gets killed fail.
  • New requests routed to a process that's shutting down, or not yet ready, fail (connection refused, 502/503).
  • Incompatibility: new code can't read data written by old code (or vice versa); a new API removed a field an old client needs; a new schema broke old code (chapter 191).
  • Cold starts: new processes are slow at first (JIT warm-up, empty caches, connection pools filling), so latency spikes.
  • Bad releases: the new version has a bug, and replacing everything at once exposes every user.

The techniques split into two families: mechanics (rolling updates, probes, graceful shutdown, draining) that make a correct release invisible, and risk control (backward compatibility, canaries, blue/green, flags) that limits the damage of an incorrect one.

Rolling deploys

A rolling update replaces instances a few at a time: start new ones, wait until they're ready, shift traffic, stop old ones. Kubernetes Deployments do this natively:

YAML
apiVersion: apps/v1
kind: Deployment
metadata: { name: api, namespace: tiffinbox }
spec:
  replicas: 6
  revisionHistoryLimit: 5
  minReadySeconds: 10                 # a new pod must stay Ready 10 s before it counts as available
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%                   # up to 2 extra pods during the rollout (rounds up)
      maxUnavailable: 0               # never go below 6 available: capacity is preserved
  selector: { matchLabels: { app: api } }
  template:
    metadata: { labels: { app: api } }
    spec:
      terminationGracePeriodSeconds: 45
      topologySpreadConstraints:
        - { maxSkew: 1, topologyKey: topology.kubernetes.io/zone, whenUnsatisfiable: DoNotSchedule, labelSelector: { matchLabels: { app: api } } }
      containers:
        - name: api
          image: ghcr.io/acme/api@sha256:ab12cd34...
          ports: [{ name: http, containerPort: 8080 }, { name: mgmt, containerPort: 8081 }]
          resources:
            requests: { cpu: "500m", memory: 768Mi }
            limits: { memory: 768Mi }
          startupProbe:
            httpGet: { path: /actuator/health/liveness, port: mgmt }
            periodSeconds: 2
            failureThreshold: 60      # up to 120 s to start (JVM, migrations check, cache warm-up)
          livenessProbe:
            httpGet: { path: /actuator/health/liveness, port: mgmt }
            periodSeconds: 10
            failureThreshold: 3
          readinessProbe:
            httpGet: { path: /actuator/health/readiness, port: mgmt }
            periodSeconds: 5
            failureThreshold: 2
          lifecycle:
            preStop:
              sleep: { seconds: 10 }  # keep serving while endpoints/LBs stop routing here (see below)
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: api, namespace: tiffinbox }
spec:
  minAvailable: 4                     # voluntary disruptions (node drains, upgrades) can't take more than 2 at once
  selector: { matchLabels: { app: api } }

The knobs: maxSurge (extra pods above replicas during the rollout: faster, needs spare capacity) and maxUnavailable (pods allowed below replicas: faster, loses capacity). maxUnavailable: 0 with a surge keeps full capacity, which matters if you deploy near peak. minReadySeconds catches pods that become Ready then crash shortly after. progressDeadlineSeconds (default 600) marks a rollout as failed if it stalls; your pipeline should watch for it (kubectl rollout status) and roll back (kubectl rollout undo).

A rolling deploy implies a period where old and new versions serve simultaneously, so everything they share (database, cache, queues, API clients, sessions) must work with both. That constraint drives the rest of the chapter.

t0t1t2t3 v1v1v1v1v1v1 v1v1v1v1v1v1v2…v2… v1v1v1v1v2v2v2v2 v2v2v2v2v2v2 mixedversions available never below 6: new pods must be Ready before old ones stop
A rolling update with six replicas, maxSurge 2 and maxUnavailable 0. New pods start and must pass readiness before old pods are terminated, so available capacity never drops below six. During the transition, old and new versions serve traffic together, which is why everything they share must be compatible with both.

Probes: startup, liveness, readiness

Kubernetes asks three different questions, and conflating them causes outages:

Probe Question On failure Should check
startup Has the process finished starting? Keep waiting (until threshold), then restart Same as liveness; generous threshold for slow starts
liveness Is the process irrecoverably stuck? Restart the container Only the process itself: event loop responsive, no deadlock. Not dependencies
readiness Should this pod receive traffic right now? Remove from Service endpoints (no restart) Can serve: initialised, not shutting down, not overloaded; optionally critical local dependencies

The classic mistakes:

  • Liveness checks the database. The database blips; every pod fails liveness; Kubernetes restarts the entire fleet at once; now you have a database blip and a cold-start stampede. Liveness must be about the process only.
  • Readiness checks shared dependencies too eagerly. If every pod's readiness depends on Redis, a Redis outage removes every pod from the load balancer, turning "degraded" (could serve from Postgres) into "down". Prefer degrading inside the app; include in readiness only what makes this pod unable to serve while others could.
  • No startup probe for slow starters. A JVM that takes 40 s to start, with a liveness probe starting at 10 s, gets killed in a restart loop. Startup probes hold off liveness until the app has started.
  • Probes on the same port and thread pool as traffic. Under heavy load, probe requests queue behind real ones, time out, and healthy-but-busy pods get killed. Spring Boot can expose actuator health on a separate management port.

Spring Boot exposes the right shape out of the box (/actuator/health/liveness and /readiness, with management.endpoint.health.probes.enabled=true, automatic in Kubernetes), and flips readiness to REFUSING_TRAFFIC when shutdown starts.

Graceful shutdown from first principles

When Kubernetes terminates a pod (rollout, scale-down, node drain), two things happen in parallel:

  1. The control plane removes the pod from Service endpoints (EndpointSlices), and every consumer of that information — kube-proxy on every node, ingress controllers, service-mesh sidecars, cloud load balancers targeting pod IPs — updates eventually: typically within a second or a few, sometimes longer for external load balancers.
  2. The kubelet runs the preStop hook, then sends SIGTERM to the container. After terminationGracePeriodSeconds (default 30) from the start of termination, SIGKILL.

Because (1) is asynchronous, a process that exits promptly on SIGTERM will still receive new connections for a moment from load balancers that haven't updated, and those fail. Hence the sequence:

0 s10 s~25 s45 s LB LBs/proxies update no new traffic arrives pod preStop sleep: serving SIGTERM → drain in-flight exit 0 SIGKILL if still running preStop ≥ propagation delay; preStop + drain < grace period
The pod termination sequence. Endpoint removal and the preStop hook start at the same time. The preStop sleep keeps the process serving while load balancers stop routing to it. Then SIGTERM triggers graceful shutdown: stop accepting, finish in-flight requests, close pools, exit. Everything must complete before the grace period ends, when SIGKILL arrives.
  1. Keep serving for a few seconds after termination begins (a preStop sleep: Kubernetes 1.30+ supports lifecycle.preStop.sleep natively, so no sleep binary is needed in distroless images). Optionally fail readiness immediately too.
  2. On SIGTERM: stop accepting new connections, finish in-flight requests (with a deadline), stop consuming from queues, flush telemetry, close database pools, exit 0.
  3. Make terminationGracePeriodSeconds exceed preStop + the longest in-flight request + shutdown work.

Also close idle keep-alive connections during shutdown (HTTP/1.1 clients reuse them; Connection: close on responses during drain, or HTTP/2 GOAWAY), otherwise clients with pooled connections keep sending to the draining pod.

The experiment

To see the effect, a small Go program puts a health-checking load balancer (checks every 500 ms) in front of two backends and runs 20 concurrent clients, each making requests that take 50 ms. Mid-run, one backend is stopped in three ways: kill (close everything immediately), shutdown-only (graceful Go Shutdown, which finishes in-flight requests, but without telling the load balancer first), and drain-then-shutdown (fail readiness, wait 1.2 s for the load balancer to notice, then Shutdown):

Go
// Zero-downtime shutdown experiment (excerpt): the three ways of stopping backend b1
switch mode {
case "kill": // SIGKILL-like: close listener and all connections immediately
	b1.srv.Close()
case "shutdown-only": // graceful Shutdown, but LB not told first
	b1.srv.Shutdown(context.Background())
case "drain-then-shutdown": // fail readiness, wait for LB to notice, then graceful Shutdown
	b1.ready.Store(false)
	time.Sleep(1200 * time.Millisecond) // > health-check interval (500 ms) + timeout
	b1.srv.Shutdown(context.Background())
}
Text
kill                 ok=  764 failed=168
shutdown-only        ok=  779 failed=139
drain-then-shutdown  ok= 1242 failed=  0

(Two runs gave 168/139/0 and 170/140/0 failures.) Shutdown alone saves the in-flight requests but still fails the new ones the load balancer keeps sending until its next health check; only draining first reaches zero. In Kubernetes, the same role is played by the preStop delay covering endpoint propagation.

Graceful shutdown in each stack

# Spring Boot 3 (application.yaml): graceful shutdown is on by default since 3.4; set the drain timeout
server:
  shutdown: graceful                   # stop accepting, finish in-flight requests
spring:
  lifecycle:
    timeout-per-shutdown-phase: 25s    # max drain time; keep < terminationGracePeriodSeconds - preStop
management:
  server: { port: 8081 }               # probes on a separate port from traffic
  endpoint: { health: { probes: { enabled: true } } }
# On SIGTERM: readiness → REFUSING_TRAFFIC, web server stops accepting, in-flight complete,
# SmartLifecycle beans stop (e.g. @KafkaListener/SQS listeners stop polling), Hikari pool closes.

Backward-compatible APIs and events

During a rollout, and for long after with mobile apps that update on users' schedules, old clients talk to new servers and new clients may briefly talk to old servers (a request routed to an old pod mid-rollout). Rules:

  • Additive changes only within a version: new optional fields, new endpoints, new enum values (if clients are written to tolerate unknown values).
  • Tolerant reader (Postel's law applied with care): clients ignore unknown fields and handle unknown enum values gracefully; servers accept old request shapes.
  • Never remove or rename fields, change types or meanings, make optional request fields required, or tighten validation within a version. Do it with a new field (expand/contract for APIs), deprecation, and usage measurement before removal.
  • Versioning for real breaks: URL (/v2/), header, or media type; support N and N−1 for a published period; Deprecation and Sunset headers (RFC 9745 and RFC 8594) and usage dashboards per version.
  • Mobile apps: you can't force updates instantly; keep old API versions alive per your support policy, and have a minimum-supported-version check for real emergencies.
  • Events and messages: the same, more strictly, because events persist in queues and logs and are replayed. Use a schema registry with compatibility modes (Avro/Protobuf/JSON Schema with BACKWARD/FORWARD/FULL compatibility), add fields with defaults, and have consumers ignore unknown fields. Deploy consumers before producers when adding fields consumers must understand.
  • Contract tests (Pact, Volume 11) and breaking-change detection on the OpenAPI document (oasdiff in chapter 187's pipeline) catch violations in CI.
Java
// Tolerant reader in Java (Jackson): ignore unknown fields; map unknown enum values to a default
@JsonIgnoreProperties(ignoreUnknown = true)
record DeliveryEvent(long deliveryId, LocalDate date,
                     @JsonEnumDefaultValue State state) {   // requires READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE
    enum State { SCHEDULED, SKIPPED, LOCKED, OUT, DELIVERED, FAILED, @JsonEnumDefaultValue UNKNOWN }
}
Go
// Tolerant reader in Go: encoding/json ignores unknown fields by default (don't use DisallowUnknownFields
// on consumers); treat unknown enum strings explicitly.
type DeliveryEvent struct {
	DeliveryID int64  `json:"deliveryId"`
	Date       string `json:"date"`
	State      string `json:"state"`
}

func (e DeliveryEvent) Known() bool {
	switch e.State {
	case "scheduled", "skipped", "locked", "out", "delivered", "failed":
		return true
	}
	return false // log + skip or park; never crash the consumer on a new value
}

Database compatibility

Chapter 191 in one line: migrate the schema forward compatibly before deploying code that needs it, and remove old structure only after no running code needs it. The ordering for a typical feature:

  1. Release A: expand migration (new nullable column/table, triggers), code unchanged or writing both.
  2. Backfill job.
  3. Release B: code reads the new structure (behind a flag if risky).
  4. Release C: contract migration.

The N−1 rule: at any time, schema version S must support code versions N and N−1, so a code rollback is always safe.

Canary releases

A canary sends a small fraction of real traffic to the new version, compares its behaviour to the stable version, and either promotes gradually or aborts automatically. It turns "deploy to everyone and watch" into a controlled experiment, limiting the blast radius of a bad release to the canary's share for the canary's duration.

What to compare: error rate, latency percentiles, saturation, and business metrics (skip success rate; payments succeeded) for canary vs stable over the same period (comparing to the stable version, not to yesterday, controls for traffic changes).

Argo Rollouts replaces the Deployment with a Rollout resource that shifts traffic in steps (via the service mesh, Gateway API, or ingress for precise weights, or replica counts otherwise) and runs AnalysisTemplates against Prometheus (or Datadog, New Relic, CloudWatch) at each step:

YAML
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata: { name: api, namespace: tiffinbox }
spec:
  replicas: 6
  selector: { matchLabels: { app: api } }
  workloadRef: { apiVersion: apps/v1, kind: Deployment, name: api }   # reuse the pod template above
  strategy:
    canary:
      canaryService: api-canary
      stableService: api-stable
      trafficRouting:
        plugins:
          argoproj-labs/gatewayAPI: { httpRoute: tiffinbox-api, namespace: tiffinbox }
      analysis:
        templates: [{ templateName: api-slo }]
        startingStep: 1
        args: [{ name: service, value: api }]
      steps:
        - setWeight: 5
        - pause: { duration: 10m }
        - setWeight: 25
        - pause: { duration: 10m }
        - setWeight: 50
        - pause: { duration: 10m }
        # 100% after the last step; any failed analysis aborts and shifts traffic back to stable
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata: { name: api-slo, namespace: tiffinbox }
spec:
  args: [{ name: service }]
  metrics:
    - name: error-rate
      interval: 2m
      failureLimit: 1
      successCondition: result[0] < 0.002
      provider:
        prometheus:
          address: http://prometheus.monitoring:9090
          query: |
            sum(rate(http_server_requests_seconds_count{service="{{args.service}}-canary",status=~"5.."}[5m]))
            / sum(rate(http_server_requests_seconds_count{service="{{args.service}}-canary"}[5m]))
    - name: p95-latency
      interval: 2m
      failureLimit: 1
      successCondition: result[0] < 0.8
      provider:
        prometheus:
          address: http://prometheus.monitoring:9090
          query: |
            histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{service="{{args.service}}-canary"}[5m])))

(Flagger is the main alternative, with Flux or standalone; service meshes such as Istio and Linkerd, and Gateway API implementations, provide the weighted routing.)

How long must a canary run?

A canary is a statistical test, and a small canary on low traffic can't tell a good release from a bad one. Suppose stable has 0.1% errors and a bad release has 0.5%. Choose a threshold so a good canary is rarely failed falsely, and see how often a bad one is caught at each sample size:

Python
# How long must a canary run before its error rate is distinguishable from baseline?
from scipy.stats import binom
base_err, bad_err = 0.001, 0.005          # baseline 0.1% errors; a bad release at 0.5%
alpha = 0.01                              # chance of falsely failing a good canary
for n in (500, 1000, 2000, 4000, 8000):
    # fail the canary if errors >= k, where k is chosen so a GOOD canary fails with prob <= alpha
    k = int(binom.ppf(1 - alpha, n, base_err)) + 1
    false_fail = 1 - binom.cdf(k - 1, n, base_err)
    caught = 1 - binom.cdf(k - 1, n, bad_err)
    print(f"n={n:>5}: fail if errors >= {k:>2}; good canary falsely failed {false_fail:.3f}; bad canary caught {caught:.1%}")
rps_total, canary_share = 30, 0.10        # off-peak TiffinBox traffic, 10% canary weight
print(f"at {rps_total} rps total and {canary_share:.0%} canary weight: 4000 requests take {4000/(rps_total*canary_share)/60:.0f} min")
Text
n=  500: fail if errors >=  4; good canary falsely failed 0.002; bad canary caught 24.2%
n= 1000: fail if errors >=  5; good canary falsely failed 0.004; bad canary caught 56.0%
n= 2000: fail if errors >=  7; good canary falsely failed 0.005; bad canary caught 87.0%
n= 4000: fail if errors >= 10; good canary falsely failed 0.008; bad canary caught 99.5%
n= 8000: fail if errors >= 16; good canary falsely failed 0.008; bad canary caught 100.0%
at 30 rps total and 10% canary weight: 4000 requests take 22 min

The lesson: on low traffic a canary needs time (or a larger weight) to mean anything; 500 requests catch a 5× error regression only a quarter of the time. Fix the step durations from this arithmetic, use metrics with more signal than rare errors (latency distributions, business success rates), and supplement with synthetic traffic for paths real users rarely hit. For TiffinBox, deploy outside the 06:30–07:00 rush (too risky) but not at 03:00 (no traffic to analyse): mid-morning after 09:30 has steady traffic and an awake team.

Blue/green

Blue/green runs two complete environments: blue (live) and green (new version, fully deployed, tested with smoke tests while receiving no user traffic). Cut-over switches all traffic at once (load balancer target, Service selector, DNS); rollback switches back instantly while blue is still running.

Rolling Canary Blue/green
Extra capacity maxSurge (small) small 2× during the switch
Exposure of a bad release grows as rollout proceeds a controlled small fraction everyone at cut-over (after pre-switch tests)
Rollback speed re-roll (minutes) abort (seconds) switch back (seconds)
Mixed versions serving yes yes briefly (connection draining), or no
Good for most services high-traffic services with good metrics releases needing all-at-once switch, pre-production verification on real infra

Blue/green does not remove the database-compatibility problem: both environments share the database (copying it would lose writes), so expand/contract still applies. Argo Rollouts supports blue/green too (activeService, previewService, prePromotionAnalysis, scaleDownDelaySeconds to keep blue around for fast rollback).

Feature flags: decoupling deploy from release

Deploy puts code into production; release exposes behaviour to users. Feature flags separate them: code ships dark, then the flag enables it for internal users, then 1%, 10%, an office, everyone, with an instant kill switch and no deploy. They also enable dark launches (run the new code path in the background and compare results without showing them) and trunk-based development (incomplete work merged behind a flag).

Java
// OpenFeature (vendor-neutral flag API) in the Spring Boot API: bulk skip behind a flag with targeting
@PostMapping("/v1/offices/{officeId}/skips")
ResponseEntity<?> bulkSkip(@PathVariable long officeId, @RequestBody BulkSkip req, Principal p) {
    var ctx = new ImmutableContext(p.getName(), Map.of("officeId", new Value(officeId)));
    if (!flags.getBooleanValue("bulk-skip", false, ctx)) {      // default false: safe if the flag service is down
        return ResponseEntity.status(404).build();
    }
    return ResponseEntity.ok(skips.bulkSkip(officeId, req, p));
}

Flag hygiene: flags have owners and expiry dates; remove a release flag within weeks of reaching 100% (each flag doubles the paths to test); keep permanent operational flags (kill switches, load-shedding toggles) documented in runbooks; evaluate flags locally from a cached ruleset so the flag service isn't on every request's critical path; default to the safe value when unavailable.

The other moving parts

  • Long-lived connections (WebSockets, SSE for live delivery tracking, gRPC streams): draining can't wait hours. Send a "reconnect" message or close with a reconnect code during shutdown, and make clients reconnect with jittered backoff to the new pods.
  • Queue consumers: on SIGTERM stop polling, finish (or release with visibility timeout) in-flight messages, commit offsets, exit. Message handlers must be idempotent anyway, since a crash mid-message causes redelivery.
  • Scheduled jobs: a CronJob running at 07:00 while a deploy happens: use concurrencyPolicy: Forbid, make jobs idempotent, and freeze deploys around critical jobs.
  • Front-end assets: users have the old SPA loaded while you deploy a new one. Keep old content-hashed assets available on the CDN for days (old index.html references them; lazy-loaded chunks are requested later), keep the API backward compatible for old SPAs, and prompt a refresh when a new version is detected (a version endpoint polled occasionally).
  • Caches: new code reading cache entries written by old code. Version cache keys when the cached shape changes (menu:v2:office:12).
  • Sessions: stateless tokens (JWT) or a shared session store, never in-process sessions, so any pod can serve any user.
  • Warm-up: JVMs run slow until the JIT compiles hot paths; send synthetic warm-up requests before readiness succeeds, or use CRaC/AppCDS/GraalVM native images to shorten startup; pre-fill connection pools.
  • Configuration and secrets rolled out the same way as code (versioned, canaried), since a bad config is a bad release.

A release runbook

Markdown
# Release: api (TiffinBox)
Preconditions
- [ ] CI green on main; image signed; SBOM attached
- [ ] Migrations in this release are expand-only and already applied (or applied by the PreSync job)
- [ ] Not within freeze windows (06:15–07:15, 11:45–13:45 IST) and no open SEV-1/2 incident
- [ ] On-call engineer aware; dashboard "API canary vs stable" open
Steps
1. Merge the promotion PR (prod values → new digest); Argo CD syncs; Argo Rollouts starts the canary.
2. Watch analysis at 5% / 25% / 50% (10 min each); compare skip success rate and p95 to stable.
3. On any failed analysis, the rollout aborts automatically; confirm traffic is 100% stable.
4. After 100%: run synthetic journey checks (sign-in, view schedule, skip a test subscription, unskip).
Rollback
- During canary: `kubectl argo rollouts abort api -n tiffinbox`
- After completion: `kubectl argo rollouts undo api -n tiffinbox` (or revert the promotion commit; Argo CD syncs)
- Feature-level: turn the flag off in the flag console (no deploy)
After
- Post in #releases: version, changes, any anomalies; close the release ticket.

Lab: three rolling deploys under load

Setup. HAProxy 2.8 in front of two uvicorn/FastAPI instances on the lab machine. HAProxy health-checks GET /ready every 500 ms (fall 1, rise 2), with retries 0 so it doesn't hide failures by retrying POSTs. Each instance serves POST /skip in 50 ms and returns its version. A load generator keeps 20 concurrent clients busy for 12 s (≈ 4,600 requests). The deploy script replaces instance A, then B, with version 2, waiting for HAProxy to bring each new instance back into rotation. The only difference between runs is how each old instance is stopped:

  • kill9: kill -9 (equivalent to a crash or a hard node failure).
  • term: SIGTERM; uvicorn stops accepting connections and finishes in-flight requests.
  • drain: create a drain flag so /ready returns 503; wait 2 s; then SIGTERM (Kubernetes equivalent: readiness probe + preStop sleep + graceful shutdown).

Results

Mode 200 OK Failed Failure types Served by v1 / v2
kill9 4,554 194 171 × 503, 22 connection drops mid-request, 1 × 502 1,181 / 3,373
term 4,572 166 166 × 503 1,485 / 3,087
drain 4,579 0 — 2,242 / 2,337

(p99 latency was 57–61 ms in every run.)

What each result means

  • kill9 lost requests two ways: the 22 that were inside the instance when it died (the client saw the connection drop), and 171 sent to it afterwards, until the next health check (up to 500 ms) marked it down.
  • term saved the in-flight requests (no connection drops) but not the new ones: the instance closed its listening socket at once, and HAProxy kept routing to it until a health check failed. Graceful shutdown handles the requests you have; draining handles the ones still coming.
  • drain removed the instance from rotation before it stopped listening. The wait must exceed the load balancer's detection time (here 2 s against a 0.5 s check interval); in Kubernetes it must cover endpoint propagation to every kube-proxy, ingress and service-mesh sidecar, which is why preStop sleeps of 5–15 s are common.
  • In every mode, both versions served traffic for several seconds. That's what makes backward compatibility (APIs, events, database schema) a hard requirement for rolling deploys, not a nicety.

Retries at the load balancer (retries, option redispatch, nginx's proxy_next_upstream) can mask the failures for idempotent requests; they're a useful safety net, but must not be the only mechanism, and must not blindly retry non-idempotent POSTs.

Try it yourself

  1. Lengthen the health-check interval to 2 s and rerun term and drain (with a 1 s wait): how many errors now?
  2. Add a 5 s request to the mix and set uvicorn's graceful timeout to 2 s. What happens to long requests during a drain?
  3. Make version 2 return a new required field in its response and write a client that breaks on mixed versions.
  4. Reproduce the experiment in k3s with a readiness probe, preStop and terminationGracePeriodSeconds, using kubectl rollout restart.

Revision sheet: zero-downtime deployment

Key ideas

  • Deploys break through: killed in-flight requests, traffic to stopping instances, cold starts, incompatible versions, schema changes, cache and queue format changes, connection-pool storms.
  • Rolling (maxSurge/maxUnavailable), blue/green (switch whole environments), canary (small traffic share with automated analysis).
  • Probes: startup (slow boot), readiness (in rotation?), liveness (restart if stuck); never make liveness depend on downstream dependencies.
  • Graceful shutdown: on SIGTERM, fail readiness, wait for propagation, stop accepting, finish in-flight work, close pools; bound by a termination grace period.
  • Compatibility: N and N−1 must coexist: additive API changes, tolerant readers, versioned events, expand/contract schemas.
  • Feature flags separate deploy from release; kill switches; clean up stale flags.
  • Release runbook: pre-checks, canary with metrics gates, promotion, rollback criteria, communication.

Numbers to remember

  • Lab: kill -9 → 194 failures; SIGTERM only → 166; drain then SIGTERM → 0 (of ~4,600).
  • Drain wait > load balancer detection time (check interval × fall count, plus propagation).

Pitfalls

  • SIGTERM handled as "exit now".
  • Liveness probes that call the database (cascading restarts).
  • Breaking API or event changes in one release.
  • Relying on load-balancer retries for non-idempotent requests.
  • Flags that are never removed.

Glossary

  • Readiness / liveness / startup probe: traffic eligibility / restart signal / boot allowance.
  • preStop hook: a Kubernetes hook run before SIGTERM, often a short sleep for draining.
  • Connection draining: letting existing work finish while sending no new work.
  • Canary analysis: comparing canary and baseline metrics to decide promotion.
  • Kill switch: a flag that disables a feature instantly.