Skip to content

Deployment Strategies: Rolling, Blue-Green, Canary, Progressive Delivery, Rollbacks ​

"We define canarying as a partial and time-limited deployment of a change in a service and its evaluation. This evaluation helps us decide whether or not to proceed with the rollout." — Google, The Site Reliability Workbook, chapter "Canarying Releases"

Summary: A deployment puts new code on machines; a release exposes it to users; a rollout is how you move from one to the other. Every strategy on this page (recreate, rolling, blue-green, canary, progressive delivery, feature flags) answers the same three questions differently: how many users see the new version at once, how you notice it is bad, and how fast you get back. The answers depend less on the tool than on two pieces of discipline: the previous version must still work against the current database, and the health signal must be measured, not eyeballed. Focus: deployment vs release vs rollout; the recreate strategy and the rolling update (owned by the workloads chapter, linked here); blue-green deployment with an environment switch at a Service selector, an Ingress or a load balancer; canary releases with traffic weights, header-based and cookie-based routing through Ingress-NGINX canary annotations, Gateway API HTTPRoute backendRefs weights and service mesh splits (Istio VirtualService, Linkerd HTTPRoute, the deprecated SMI TrafficSplit); progressive delivery controllers (Argo Rollouts with the Rollout CRD, canary steps, setWeight, pause, AnalysisTemplate and AnalysisRun with Prometheus as metrics provider, promotion, abort and automatic rollback; Flagger with its Canary CRD and MetricTemplates); A/B testing versus canary; shadow traffic and dark launches; feature flags with OpenFeature, flag evaluation, targeting rules, percentage rollouts, kill switches and flag debt (LaunchDarkly, Unleash, Flagsmith, Laravel Pennant); rollback mechanics (image digest pinning, kubectl rollout undo and revision history, Helm rollback, GitOps revert, Argo Rollouts rollback windows); database-compatible releases (N-1 compatibility, expand/contract, forward-only migrations, migration ordering); release health (error rate, p99 latency, SLO-based promotion, error budget burn rate); deployment freezes and change windows; VM strategies (immutable infrastructure, AMIs, ASG instance refresh, the symlink release switch of Capistrano and Deployer); zero-downtime details for the Go service (readiness, readiness gates, preStop, connection draining) and the Laravel app (php-fpm reload, OPcache and $realpath_root, maintenance mode with artisan down --with-secret, Octane reload, config:cache/route:cache, queue:restart); post-deploy verification, synthetic monitoring, runbooks and the DORA metrics. Learning goal: Pick a strategy for a given service and justify it by blast radius, cost and rollback time; write the manifests for a blue-green switch, an Ingress or Gateway API canary and an Argo Rollouts or Flagger progressive rollout with metric gates; make the Go service and the Laravel app survive any of them without dropped requests; plan a schema change as a sequence of N-1 compatible releases; and roll back a bad release by the fastest safe path.

This chapter sits in the Delivery & Infrastructure group. How a Deployment replaces Pods (maxSurge, maxUnavailable, minReadySeconds, probes, PodDisruptionBudgets, the termination sequence) is taught in Kubernetes Workloads; this page links there instead of re-teaching it. The pipeline that builds, signs and promotes artefacts between environments is CI/CD Pipelines; Argo CD and Flux as the engine that applies Git to the cluster are GitOps with Argo CD & Flux; Helm and Kustomize, including helm rollback mechanics, are Packaging for Kubernetes; dashboards and kubectl triage during a bad rollout are Kubernetes Observability & Troubleshooting; the atomic symlink deploy script this page extends is in Shell Scripting. At the concept level, progressive delivery, feature flags and kill switches as part of the secure delivery process are owned by Secure SDLC & Incident Response; expand/contract migrations, locks and backfills are owned by Schema Migrations; load balancer algorithms and connection draining in general by Load Balancing; SLOs and error budgets by SLAs, SLOs, SLIs & Error Budgets; burn-rate alerting by Alerting That Works; SIGTERM handling in Go by OS, Processes & Signals.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why a deploy should not be a releaseWhy it exists
Fowler's bliki entries, SRE canarying, DORA, Gateway API GA, Ingress-NGINX retirementWhere it comes from
Deployment vs release vs rolloutDeployment, release, rollout
Recreate strategy; rolling update link (owned by Kubernetes Workloads)Recreate and rolling
Blue-green deployment: environment switch, Service selector switch, Ingress switch, load balancer switchBlue-green
Canary release: traffic weight, header-based routing, cookie-based routingCanary
nginx.ingress.kubernetes.io/canary-weight and the other Ingress-NGINX canary annotationsIngress-NGINX canary
Gateway API HTTPRoute and backendRefs weightGateway API
Service mesh traffic split: Istio VirtualService; Linkerd TrafficSplit HTTPRouteService mesh splits
Argo Rollouts: Rollout CRD, canary steps, setWeight, pause, AnalysisTemplate, AnalysisRun, metrics provider Prometheus, promotion, abort, automatic rollbackArgo Rollouts
Flagger and its Canary CRDFlagger
Release health, p99 latency, SLO-based promotion, error budget burn rateRelease health
A/B testing vs canary; shadow traffic; dark launchA/B, shadow, dark
Feature flags, OpenFeature, flag evaluation, targeting rules, percentage rollout, kill switch, flag debtFeature flags
Rollback: image digest pinning, kubectl rollout undo, revision history, Helm rollback, GitOps revertRollback mechanics
Database-compatible releases, N-1 compatibility, backward-compatible releases, forward-only migrations, migration ordering, expand contract linkDatabase-compatible releases
Zero-downtime: readiness gate, preStop, connection drainingZero-downtime details
Immutable infrastructure, AMI, instance refresh, symlink release switch, Capistrano, DeployerVM strategies
php-fpm reload, Laravel maintenance mode, artisan down --with-secret, Octane reload, config:cache route:cache, queue:restartLaravel zero-downtime
Deployment freeze, change windows, smoke tests, synthetic monitoring, post-deploy verification, runbook, DORA metricsFreezes, verification, runbooks
What the controllers change at each step, weight arithmetic, time budgets, knobs, messagesMechanics
CodeGo, Laravel
Ten classic problemsSolving the classic problems
Which strategy, traffic layer, controller, flag systemChoosing
From one VM to many clustersIn architecture
Commands with real or expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The strategies in one table.

StrategyWho sees the new versionCapacity costRollbackNeedsFits
RecreateEveryone, after a gap1xRedeploy old version (another gap)NothingVersions that cannot run side by side; dev environments
Rolling updateEveryone, gradually by Pod count1x + maxSurgekubectl rollout undo (another rolling update)Readiness probes, N-1 compatibilityThe default for stateless services
Blue-greenNobody, then everyone at once2x during the releaseSwitch back: one selector or LB change, secondsTwo environments, a switch, N-1 compatible databaseReleases you want to test fully in production before any user sees them
Canary (by weight)A small random share, then more1x + canary PodsWeight to 0An L7 router (Ingress, Gateway, mesh) or replica ratiosHigh-traffic services where metrics show regressions quickly
Progressive deliveryCanary steps driven by metrics1x + canary (stable kept at 100 % by default with traffic routing)Automatic abort on failed analysisA controller (Argo Rollouts, Flagger) + PrometheusMany services, many deploys a day, no human watching every one
Feature flagWhoever the targeting rules choose1xFlag off, no deployA flag system (OpenFeature + provider)Separating release from deploy; per-user targeting; kill switches
A/B testA fixed split, sticky per user, for days1x + variantEnd the experimentFlags or header/cookie routing + analyticsProduct questions, not release safety
Shadow / dark launchNobody (responses discarded or hidden)Extra load on the new versionStop mirroringMesh or Gateway mirroring, or a flagLoad and correctness of a new backend before release

Where the traffic decision is made.

LayerObject and fieldSplit by weightBy header / cookieMirroringStatus in 2026
Kubernetes Servicespec.selectorOnly by replica ratioNoNoCore; blue-green switch point
Ingress-NGINXSecond Ingress with nginx.ingress.kubernetes.io/canary-*canary-weight (of canary-weight-total, default 100)canary-by-header, canary-by-cookieNoProject retired in March 2026; Ingress API frozen
Gateway APIHTTPRoute.spec.rules[].backendRefs[].weightProportional weightsmatches.headersRequestMirror filter (extended support)GA since v1.0 (31 Oct 2023); v1.7.0 on 29 Oct 2026
IstioVirtualService.spec.http[].route[].weight + DestinationRule subsetsYesmatch.headersmirror + mirrorPercentageSupports Gateway API too
LinkerdHTTPRoute (policy.linkerd.io/v1beta2 or Gateway API)backendRefs weightsmatches.headersNoSMI TrafficSplit deprecated
Cloud LB (ALB, NLB, Cloud Load Balancing)Target groups / backend services, weightedYesALB listener rulesVariesAlso the VM blue-green switch

The fastest way back, in order.

You haveFastest rollbackTimeWhat it does not undo
A feature flag around the changeTurn the flag offSecondsSchema changes, data written by the new path
A canary still in progresskubectl argo rollouts abort / Flagger rollbackSecondsThe Rollout spec in Git still says N+1
Blue-green with the old slot still upPatch the selector back / switch the LBSecondsSame as above
A VM symlink layoutPoint current at the previous release, reload php-fpmSecondsMigrations already run
A plain Deploymentkubectl rollout undo (pod template only)One rolling updateConfigMaps, Secrets, replicas, other objects
Helmhelm rollback RELEASE [REVISION]One upgradeData, CRDs, hooks' side effects
GitOps (Argo CD, Flux)git revert of the image bump, let the controller syncOne sync + rolloutNothing in the cluster that Git does not describe
A destructive migrationRoll forward with a fixA releaseIt was the mistake: prevent it with expand/contract
Bad release in production: fastest safe way back, in orderSLO burn / errors after a deploy1. Is the change behind a feature flag?yesflag off / kill switch: seconds, no deployno2. Is a canary still in progress?yesabort: weight 0, stable already scaledno3. Did the release make the schemaunusable for the previous version?yesroll FORWARD (hotfix); code rollbackwould break. Prevent with expand/contractno4. Is the previous version still running?yesswitch back: selector, LB, symlinkno5. Redeploy the previous DIGEST: git revert in the GitOps repo (Argo CD / Flux sync),helm rollback RELEASE REV, kubectl rollout undo, Capistrano/Deployer rollback, ASG rollbackThen: freeze further deploys of this service, open the incident, and write the follow-up (why did analysis not catch it?).

Why it exists ​

Most outages are self-inflicted: a change went out and something broke. Google's SRE workbook frames canarying as the answer to exactly that: send the change to a small part of production first, compare it with the rest, and only then continue. Every other strategy on this page is a variation on the same trade: spend something (capacity, time, an extra component) to make a bad release smaller, more visible and faster to undo.

The second idea is that deploying and releasing are different acts. If the only way to show users a feature is to deploy code, then every deploy is a release and every rollback is a deploy. Separate them (dark code behind a flag, a new version receiving no traffic yet, a green environment that is live but unrouted) and both get cheaper: deploys become boring and frequent, releases become a configuration change that can be reversed in seconds.

Simpler choiceRicher choiceWhat you buyWhat you pay
RecreateRolling updateNo downtimeTwo versions run at once: they must share the database and the API
Rolling updateBlue-greenTest the full new environment before any user sees it; instant switch backDouble capacity during the release; the switch is all-or-nothing
Rolling updateCanary by weightA bad version hurts 5 % of requests, not 100 %An L7 router; metrics good enough to compare 5 % against 95 %
Manual canaryProgressive delivery controllerMetric-gated steps and automatic abort, every deploy, at 3 a.m.A controller, CRDs, Prometheus queries you must trust
Deploy = releaseFeature flagsRelease and rollback without a deploy; per-user targetingA flag service on the request path; flag debt
kubectl rollout undoGitOps revertGit and cluster agree after the rollbackA pipeline step between the decision and the effect
Mutable serversImmutable images (AMIs, container digests)The rollback target is a known artefactImage builds per release

The analogy used through this page: a restaurant changing its menu. A recreate deploy closes the restaurant for an afternoon and reopens with the new menu. A rolling update swaps cooks one at a time; for an hour, some tables get old dishes and some new, so the kitchen (the database) must stock ingredients for both. Blue-green builds a second kitchen next door, cooks a full test service there, then turns the sign at the door; if the new kitchen fails, turn the sign back. A canary gives the new dish to one table in twenty and watches their faces; progressive delivery has a waiter counting complaints and pulling the dish automatically. A feature flag puts the new dish on the menu for staff only. A dark launch cooks the dish for every order but throws it away, just to see whether the kitchen keeps up. And expand/contract is the rule that you never remove an ingredient while any cook still uses it.

Three common misunderstandings, up front ​

  1. "Rolling back is the safe default." Only if the previous version can still run. Kubernetes documents that kubectl rollout undo rolls back "only the Deployment's Pod template part"; it does not touch the database. If the release dropped or renamed a column, the old code fails on the new schema and the right move is a fix forward. See Database-compatible releases.
  2. "A canary at 10 % means 10 % of users." Ingress-NGINX's canary-weight is "percent of random requests"; a user's next request may land on the other version. Gateway API weights are per request too. Per-user stickiness needs a cookie, a header or a flag keyed by user. See Canary.
  3. "Argo Rollouts' rollback fixes Git." Its FAQ: "Argo Rollouts doesn't read/write anything to Git." After an abort the cluster runs the old version while Git still declares the new one; someone must revert or fix the commit. See Rollback mechanics.

Where it comes from ​

WhenWhat happenedSource
2006Joshua Kerievsky documents the refactoring strategy later called parallel change (expand, migrate, contract)Fowler, ParallelChange
1 Mar 2010Fowler's BlueGreenDeployment bliki entry; the name came from "some foggy combination of Daniel Terhorst-North and Jez Humble"martinfowler.com
29 Oct 2010FeatureToggle bliki entry ("flag" and "toggle" both in use)martinfowler.com
13 May 2014ParallelChange bliki entrymartinfowler.com
25 Jun 2014CanaryRelease bliki entry (Danilo Sato): roll out "to a small subset of users before rolling it out to the entire infrastructure"martinfowler.com
2014DORA's first study starts from four variables: deployment frequency, lead time for changes, mean time to recover, change fail ratedora.dev metrics history
Kubernetes v1.14Pod readiness gates (readinessGates) reach stableKubernetes pod lifecycle docs
3 Oct 2023CNCF archives the Service Mesh Interface (SMI) project, whose TrafficSplit Linkerd and Argo Rollouts supportedSMI README
2023DORA renames MTTR to failed deployment recovery timedora.dev metrics history
31 Oct 2023Gateway API v1.0 GA (HTTPRoute with weights is standard)Kubernetes blog
2024DORA adds a fifth metric, deployment rework ratedora.dev metrics history
11 Nov 2025Kubernetes SIG Network announces the retirement of Ingress NGINX; best-effort maintenance until March 2026Kubernetes blog
Kubernetes v1.34The sleep lifecycle action (preStop.sleep.seconds) is stableFeature gate PodLifecycleSleepAction
2026Argo Rollouts v1.10.2 (4 Nov), v1.11.0-rc1 (5 Nov); Flagger v1.45.0 (1 Sep); Gateway API v1.7.0 (29 Oct)GitHub releases

Two lineages meet here. The continuous delivery lineage (Humble and Farley's book, Fowler's bliki, the Flickr-era "deploy many times a day" talks) treats deployment as a routine, automated, reversible operation and invented the vocabulary: blue-green, canary, feature toggles, dark launching, parallel change. The SRE lineage (Google's release engineering and canarying chapters) adds measurement: a canary is only as good as its comparison against a control and its absolute SLO checks. Kubernetes gave both a common substrate: Deployments made rolling updates the default; Ingress, then the Gateway API and service meshes made traffic weights a field in YAML; Argo Rollouts and Flagger turned "deploy, watch dashboards, decide" into a controller loop. The DORA research made the outcome measurable with four (now five) delivery metrics.

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.

Deployment, release and rollout Must-know ​

In plain words: Deploying is installing the new version somewhere it could run. Releasing is letting users reach it. The rollout is the path between the two: how many users, in which order, with which checks.

Common misunderstanding: "Deployment vs release is just wording." It is a design choice. Fowler's dark launching entry describes calling new back-end code "from existing users without the users being able to tell it's being called": deployed, not released. A green environment that passes smoke tests but receives no traffic is deployed and unreleased. A feature flag at 0 % is the same thing inside one binary.

Definition: In this chapter, deployment = an artefact (image digest, AMI, release directory) running in production infrastructure; release = production traffic or users reaching the new behaviour; rollout = the controlled progression of a release (all at once, by Pod count, by traffic weight, by user cohort), ending in promotion (new version becomes the stable one) or rollback (previous version serves again). Kubernetes uses "rollout" for a Deployment's Pod replacement (kubectl rollout status|undo|history); Argo Rollouts names its CRD after it.

text
Release 1.5.0 of orders-api, decoupled
1  CI builds and signs ghcr.io/acme/orders-api@sha256:d1...       (artefact)
2  GitOps commit sets the digest; Argo CD syncs the Rollout          (deployment starts)
3  Canary Pods run 1.5.0; HTTPRoute weight 0 -> 5 %                  (deployment done, release begins)
4  new-checkout flag still 0 %: the new checkout code is deployed and dark
5  analysis passes at 5, 20, 50 %; weight 100 %                      (promotion: 1.5.0 is stable)
6  product turns new-checkout on for staff, then 5 %, then 100 %     (release of the feature)
7  next release removes the flag and the old code path               (flag debt paid)

Real scenarios:

  • A marketing launch on Tuesday 10:00: the code was deployed last week behind a flag; the launch is a flag change, with no deploy freeze needed.
  • A payment provider integration is deployed to all Pods but enabled for one merchant (targeting rule) until the reconciliation report matches.
  • A rollback "of the release" means flipping the flag; a rollback "of the deployment" means changing the running artefact.
  • A mobile backend must keep old API versions alive because releases to app stores lag deployments by weeks: release and deploy timelines are separate by nature.
ToolWhat it calls deploy / release
Kubernetes Deployment"rollout" = Pod template change; no notion of traffic release
Argo Rollouts / FlaggerRollout steps or canary analysis = release by traffic share
Helm"release" = an installed chart instance with revisions (deployment, in this page's terms)
LaunchDarkly / Unleash / Flagsmith / OpenFeatureRelease by targeting and percentage, no deploy
GitHub Actions / GitLab environments"deployment" job to an environment, with protection rules
DORA"deployment frequency" counts production deployments

Fix / how to use it: make "deployed but not released" a normal state. Ship every change dark (flag off, weight 0, or an idle slot), verify it in production, then release in steps. Keep the vocabulary straight in runbooks: "roll back the flag" and "roll back the image" are different procedures with different blast radius.

Recreate strategy and the rolling update Must-know ​

In plain words: Recreate stops everything, then starts the new version. Rolling replaces Pods a few at a time, so both versions serve for a while.

Common misunderstanding: "Recreate is for amateurs." It is the honest choice when two versions must never run together (a singleton that holds an exclusive lock, a schema change that is not N-1 compatible, a dev environment with one replica), and Kubernetes documents what it does guarantee.

Definition: .spec.strategy.type "can be "Recreate" or "RollingUpdate". "RollingUpdate" is the default value." With Recreate, "All existing Pods are killed before new ones are created"; the guarantee is only for upgrades: "If you manually delete a Pod, the lifecycle is controlled by the ReplicaSet and the replacement will be created immediately". The rolling update, with maxSurge, maxUnavailable, minReadySeconds, progressDeadlineSeconds and readiness probes, is the rolling update link target of this page: Kubernetes Workloads → Deployments. Kubernetes' own comparison table rates rolling update with "None" downtime and "Low — gradual rollout" risk, Recreate with downtime, best for "Incompatible versions", and canary "Lowest — small traffic percentage".

text
Recreate, 4 replicas, 1.4.2 -> 1.5.0
T0  4 x 1.4.2 Ready
T1  scale old ReplicaSet to 0; Pods Terminating (preStop, SIGTERM, drain)
T2  all old Pods gone                                   <- no Pod serves: downtime starts
T3  new ReplicaSet 4 x 1.5.0 created, pulling, starting
T4  readiness passes                                    <- downtime ends
Rolling (maxSurge 25 %, maxUnavailable 0): T0..Tn always >= 4 Ready, mixed versions

Real scenarios:

  • A queue consumer that must be the only one processing a partition: Recreate, accepting a short pause in consumption.
  • A Laravel scheduler Deployment with one replica: Recreate avoids two schedulers overlapping during an update.
  • A web service: rolling, with readiness gating so a broken image never receives traffic and the rollout stalls at the first new Pod.
  • An API whose response format changed incompatibly: neither; ship both formats first (N-1), then roll.
PlatformRecreate equivalentRolling equivalent
Kubernetes Deploymentstrategy.type: RecreateRollingUpdate (default)
Kubernetes StatefulSetRecreate update strategy ("deletes all of the StatefulSet's Pods before creating new Pods"; alpha, feature gate StatefulSetRecreateStrategy). OnDelete is different: the controller "will not automatically update the Pods" until you delete themRollingUpdate with partition
Argo Rollouts(use a Deployment)canary without steps behaves like a rolling update
AWS ASGReplace all instancesInstance refresh, Rolling strategy
Docker Compose / single VMdocker compose up -d (stop, start)Several hosts behind an LB, one at a time

Fix: default to rolling with readiness probes and maxUnavailable: 0; choose Recreate deliberately and write down why; when you reach for Recreate because versions are incompatible, first ask whether an expand step would make them compatible.

Blue-green deployment: environment switch at the Service, Ingress or load balancer Must-know ​

In plain words: Run two complete copies of production. One (blue) serves users. Deploy to the other (green), test it, then flip the switch that decides which copy users reach. Keep blue running so you can flip back.

Common misunderstanding: "Blue-green avoids database problems because the environments are separate." Fowler's original entry says the opposite: "Databases can often be a challenge with this technique". Almost always both colours share one database, so the schema must serve both versions: "first apply a database refactoring to change the schema to support both the new and old version of the application, deploy that, check everything is working fine so you have a rollback point, then deploy the new version of the application."

Definition: Fowler: "you have two production environments, as identical as possible. At any time one of them, let's say blue for the example, is live." After testing green, "you switch the router so that all incoming requests go to the green environment"; rollback: "if anything goes wrong you switch the router back to your blue environment." The environment switch can sit at three layers: a Service selector switch (Kubernetes: change spec.selector from slot: blue to slot: green), an Ingress switch or Gateway route change (point the backend at the other Service), or a load balancer switch (move a listener or weighted target group, change DNS). Argo Rollouts automates the selector variant: it injects "a unique hash of the ReplicaSet" into the active and preview Services' selectors and switches the active one on promotion.

Blue-green: two full environments, one switch, the same switch backGateway / Ingress / LBService orders-api (live)selector: app=orders-api, slot=blue -> slot=greenbefore: 100 %after patch: 100 %Deployment orders-api-blueimage 1.4.2@sha256:11... 4 Pods Readyafter the switch: idle, kept running= the rollback target (seconds away)Deployment orders-api-greenimage 1.5.0@sha256:00... 4 Pods Readytested BEFORE it gets trafficthrough orders-api-previewService orders-api-previewsmoke tests, testersOne shared databaseschema must work for 1.4.2 AND 1.5.0 (expand first)Cost: 2x capacity during the release. Switch: 1 PATCH, endpoints follow in seconds. Rollback: the same PATCH with slot=blue.
text
Blue-green with scripts/blue-green-switch.sh
1  green Deployment rolled out with 1.5.0 (all replicas Ready); live Service selects slot=blue
2  patch orders-api-preview -> slot=green; smoke test PREVIEW_URL/version == 1.5.0
3  patch orders-api selector -> slot=green (one API call); EndpointSlices update
4  kube-proxy / Gateway converge: a few seconds where old and new both answer
5  verify LIVE_URL: 20 requests must report 1.5.0 (5 grace requests); else patch back to blue, exit 5
6  blue stays up (scaleDownDelaySeconds in Argo Rollouts, default 30 s) as the instant rollback target

Real scenarios:

  • A Laravel shop with strict "no mixed versions" rules (session format changed): blue-green avoids requests bouncing between versions, but needs session compatibility anyway for users mid-checkout at the switch.
  • An API whose new version needs a warm cache: green warms up against shadow traffic before the switch.
  • AWS ALB behind Argo Rollouts blue-green: its docs warn "ALB Ingress with Rollouts blue-green strategy is not supported without a chance of downtime" because the controller may leave the target group briefly empty; use pod readiness gates and the AWS Load Balancer Controller's guidance.
  • A VM fleet: two Auto Scaling groups, the ALB listener's weighted target groups move 0/100 to 100/0.
ProductSwitch pointNotes
Plain KubernetesService spec.selector patchSimple; propagation takes seconds; script it with checks
Argo Rollouts blueGreenactiveService / previewService selectorsautoPromotionEnabled (default true), prePromotionAnalysis, postPromotionAnalysis, previewReplicaCount, scaleDownDelaySeconds (default 30)
Flagger Blue/GreenGenerated Services; "no service mesh or ingress controller is required"Analysis by iterations instead of weights
Gateway APIHTTPRoute backendRefs 100/0 -> 0/100Same object as canary; atomic per route
AWS ALB / NLBListener rule or weighted target groupsDeregistration delay drains old targets
DNSRecord switchTTL and resolver caching make it slow and uneven: last resort

Fix: script the switch with pre-checks (target fully rolled out, smoke test on preview), make the switch a single API call, verify through the real public path, and keep the old colour scaled up until the release has bedded down. Budget the 2x capacity, or use previewReplicaCount to keep green small until promotion.

Canary release: traffic weight, header-based and cookie-based routing Must-know ​

In plain words: Send a small share of real traffic to the new version, compare it with the old, and increase the share step by step while it behaves.

Common misunderstanding: "Two Deployments behind one Service is a canary." It is a coarse one: Kubernetes documents that pattern ("By adjusting the replica counts, you control the traffic ratio between stable and canary Pods"), but the ratio is only as fine as your replica count (1 of 10 Pods = 10 %, never 1 %), and kube-proxy spreads connections, not requests. Fine-grained weights, header or cookie routing need an L7 router.

Definition: Danilo Sato's CanaryRelease entry on martinfowler.com: the change is rolled out "to a small subset of users before rolling it out to the entire infrastructure". The SRE workbook adds the measurement: the part receiving the change is "the canary," and the remainder of the service is "the control"; compare them and also "use absolute measures, such as defined SLOs". Routing options: traffic weight (random share of requests), header-based routing (requests carrying X-Canary: always go to the canary: testers, synthetic checks), cookie-based routing (a cookie pins a browser to one side: internal users, beta programme). Argo Rollouts' traffic-management page lists the same three techniques: "Raw percentages", "Header-based routing", and "Mirrored traffic".

text
Canary by weight through an HTTPRoute, 10 000 requests/min
1  weights 100/0: stable only
2  weights 95/5: about 500 req/min hit 1.5.0; error rate compared with stable over 5 min
3  testers send X-Canary: always and always reach 1.5.0 (header rule wins over weights)
4  weights 80/20, 50/50: comparison continues; p99 latency of canary checked against 300 ms
5  weights 0/100: canary is the new stable; old Pods scale down
abort at any step: weights 100/0, canary Pods kept for debugging or scaled down

Real scenarios:

  • A Go service at 2 000 req/s: 5 % gives 100 req/s, enough for a success-rate comparison within minutes.
  • A low-traffic admin API at 2 req/min: a weight canary tells you nothing; use header routing with synthetic checks, or blue-green with a smoke suite.
  • A browser app where a user hopping between versions breaks the UI (asset hashes): cookie routing or session affinity, not per-request weights.
  • A canary that looks fine because it only received cache hits: compare per-endpoint, not only global error rate.
RouterWeightHeaderCookie
Kubernetes Service (replica ratio)CoarseNoNo
Ingress-NGINXcanary-weightcanary-by-header (+ -value, -pattern)canary-by-cookie
Gateway API HTTPRoutebackendRefs[].weightmatches[].headersHeader match on Cookie (implementation-specific)
Istio VirtualServiceroute[].weightmatch[].headersHeader match on cookie (regex)
Linkerd HTTPRoutebackendRefs[].weightmatches[].headersHeader match
Argo Rollouts / FlaggerDrive the abovesetHeaderRoute (Istio, plugins) / Flagger A/B matchFlagger A/B with cookie match

Fix: pick the routing key by what must be sticky: requests (weight), testers (header), users (cookie or flag). Make the canary big enough in requests per minute for the comparison you rely on, and make every response say which version served it (the Go service sets X-App-Version).

Ingress-NGINX canary annotations Important ​

In plain words: Ingress-NGINX lets a second Ingress for the same host and path act as "the canary" of the first. Annotations on the second one decide which requests go there.

Common misunderstanding: "You can stack several canaries." The annotation docs list one known limitation: "Currently a maximum of one canary ingress can be applied per Ingress rule." And the second Ingress inherits almost everything: "when you mark an ingress as canary, then all the other non-canary annotations will be ignored (inherited from the corresponding main ingress)" except load-balance, upstream-hash-by and session-affinity annotations.

Definition: After nginx.ingress.kubernetes.io/canary: "true": canary-by-header (value always routes to the canary, never never does, anything else falls through), canary-by-header-value and canary-by-header-pattern (custom value, PCRE match), canary-by-cookie (same always/never semantics on a cookie), nginx.ingress.kubernetes.io/canary-weight ("percent of random requests that should be routed to the service specified in the canary Ingress") and canary-weight-total ("If unspecified, it defaults to 100"). "Canary rules are evaluated in order of precedence. Precedence is as follows: canary-by-header -> canary-by-cookie -> canary-weight". With session affinity, affinity-canary-behavior: sticky (default) keeps canary users on the canary.

Status (verified 2026-11-29): the Kubernetes blog of 11 November 2025 announced the retirement: "Best-effort maintenance will continue until March 2026. Afterward, there will be no further releases, no bugfixes, and no updates to resolve any security vulnerabilities". The repository README now says ingress-nginx "was an Ingress controller". The Ingress API itself stays ("The Kubernetes project has no plans to remove Ingress from Kubernetes") but is frozen, and Kubernetes "recommends using Gateway instead of Ingress". Existing clusters still run these annotations; new designs should use the Gateway API, and the Gateway API docs include a "Migrating from Ingress-NGINX" guide.

yaml
# Ingress-NGINX canary: a second Ingress for the same host and path, marked
# canary, sends a share of requests to the canary Service. Precedence is
# canary-by-header -> canary-by-cookie -> canary-weight.
# NOTE: the Ingress-NGINX project was retired in March 2026 (no further
# releases or security fixes); new setups should use the Gateway API file.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: shop-web
  namespace: shop
spec:
  ingressClassName: nginx
  rules:
    - host: shop.example
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: shop-web-stable
                port:
                  number: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: shop-web-canary
  namespace: shop
  annotations:
    nginx.ingress.kubernetes.io/canary: "true"
    # Testers send `X-Canary: always` (or `never`) to force a side.
    nginx.ingress.kubernetes.io/canary-by-header: "X-Canary"
    # A cookie named `canary` with value `always` pins a browser to the canary.
    nginx.ingress.kubernetes.io/canary-by-cookie: "canary"
    # Everyone else: 10 % of requests, chosen at random per request.
    nginx.ingress.kubernetes.io/canary-weight: "10"
spec:
  ingressClassName: nginx
  rules:
    - host: shop.example
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: shop-web-canary
                port:
                  number: 80
text
Request routing with the two Ingresses above
1  GET / with header X-Canary: always        -> canary (header rule, highest precedence)
2  GET / with header X-Canary: never         -> stable, even if the cookie says always
3  GET / with cookie canary=always           -> canary
4  GET / with neither                        -> canary with probability 10/100, else stable
5  change canary-weight to "0"               -> only header/cookie traffic reaches the canary
6  delete the canary Ingress                 -> everything to stable (the rollback)

Real scenarios:

  • QA tests the canary from the public internet with a browser extension that sets X-Canary: always.
  • Staff get a canary=always cookie from an internal page and dogfood for a day before any weight.
  • Argo Rollouts with trafficRouting.nginx creates and edits the canary Ingress itself (stableIngress names the main one).
  • A cluster still on Ingress-NGINX after March 2026: keep the canary pattern working, but plan the migration; security fixes no longer arrive.
AnnotationValuesEffect
canary"true"Marks this Ingress as the canary of the main one
canary-by-headerheader namealways -> canary, never -> stable
canary-by-header-valuestringCustom value instead of always
canary-by-header-patternPCRERegex match; ignored if -value set
canary-by-cookiecookie namealways / never
canary-weightinteger stringShare of random requests
canary-weight-totalinteger stringDenominator, default 100
affinity-canary-behaviorsticky / legacySession-affinity users stay on their side

Fix: use header and cookie rules for testers, weight for the rest; manage the canary Ingress from a controller (Argo Rollouts, Flagger with provider: nginx) rather than by hand; for anything new, write the HTTPRoute below instead.

Gateway API HTTPRoute: backendRefs weight and header matches Must-know ​

In plain words: In the Gateway API, one HTTPRoute rule can list several backends with weights. Change the numbers and the split changes. Add a rule matching a header and testers go straight to the new version.

Common misunderstanding: "Weights are percentages." The Gateway API guide: "weight indicates a proportional split of traffic (rather than percentage) and so the sum of all the weights within a single route rule is the denominator for all of the backends." Weight defaults to 1. The guide adds that a single backend "implicitly receives 100% of the traffic", but the HTTPRoute CRD is more precise: "If only one backend is specified and it has a weight greater than 0, 100% of the traffic is forwarded to that backend. If weight is set to 0, no traffic should be forwarded for this entry." A lone backend at weight 0 is therefore not a 100 % route.

Definition: HTTPRoute.spec.rules[].backendRefs[] "accepts a list of backends that a route rule will send traffic to. The relative weights of these backends define the split of traffic between them." Routing precedence sends the most specific match first, which is why a header rule (X-Canary: always) next to a weighted catch-all works as "testers always, everyone else 10 %". The same object does blue-green (100/0 to 0/100) and, with the RequestMirror filter (extended support), mirroring. Controllers that write the weights for you: the Argo Rollouts Gateway API plugin (argoproj-labs/gatewayAPI) and Flagger's Gateway API provider.

yaml
# Gateway API canary by hand (no controller): header rule for testers first,
# then a 90/10 weighted split for everyone else. Weights are proportional:
# 90 and 10 out of a total of 100. Promote by editing the weights in Git
# (90/10 -> 50/50 -> 0/100); roll back by setting them to 100/0.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: orders-api
  namespace: shop
spec:
  parentRefs:
    - name: public
      namespace: gateway
  hostnames:
    - api.shop.example
  rules:
    - matches:
        - headers:
            - name: X-Canary
              value: always
      backendRefs:
        - name: orders-api-v2
          port: 80
    - matches:
        - path:
            type: PathPrefix
            value: /
      backendRefs:
        - name: orders-api-v1
          port: 80
          weight: 90
        - name: orders-api-v2
          port: 80
          weight: 10
text
Hand-driven Gateway API canary in a GitOps repo
1  PR: add orders-api-v2 Deployment + Service; HTTPRoute header rule only    (dark, testers only)
2  PR: weights 90/10                                                          (canary)
3  PR: weights 50/50, then 0/100                                              (promotion)
4  PR: remove v1 backendRef and Deployment                                    (cleanup)
rollback at 2 or 3: revert the PR -> Argo CD syncs -> weights 100/0 within one sync

Real scenarios:

  • Teams migrating off Ingress-NGINX map canary-weight to backendRefs weights and canary-by-header to a header match.
  • A shared Gateway owned by the platform team; application teams own only their HTTPRoutes (role-oriented API).
  • Argo CD fights Argo Rollouts over the weights: the plugin docs tell Argo CD users to "Configure Argo CD to ignore the weights that the plugin writes" with ignoreDifferences.
  • A rule whose weights are all 0 has nowhere to send traffic (the CRD: "If weight is set to 0, no traffic should be forwarded for this entry"); the chapter's validator rejects it.
ImplementationWeighted backendRefsHeader matchMirror
Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, Kong, Traefik, GKE GatewayCoreCoreExtended (RequestMirror)
Linkerd (mesh, east-west)Yes (policy.linkerd.io or gateway.networking.k8s.io HTTPRoute)YesNo
Argo Rollouts pluginWrites weights during stepssetHeaderRoute (header-based routing support announced by the Argo project)See the plugin docs
Flagger provider: gatewayapiGenerates the HTTPRouteA/B testing matchBlue/Green mirroring

Fix: use integer weights that sum to 100 so humans read them as percentages; put header rules first for testers; let a controller write the weights during a rollout and tell your GitOps tool to ignore that field.

Service mesh traffic split: Istio VirtualService, Linkerd HTTPRoute and TrafficSplit Important ​

In plain words: Inside the cluster, a service mesh's sidecar (or ambient proxy) sits in front of every call, so it can split east-west traffic (service to service) the way an Ingress splits north-south traffic.

Common misunderstanding: "SMI TrafficSplit is the portable way." SMI is archived ("This project is ARCHIVED"), and Linkerd's docs warn: "TrafficSplit functionality and the linkerd-smi extension are deprecated and will be removed in a future release", recommending dynamic request routing with HTTPRoute instead. The portable API today is the Gateway API's HTTPRoute, which both Istio and Linkerd implement.

Definition: Istio: a DestinationRule defines subsets by Pod labels; a VirtualService routes to subsets with weight, matches headers, and can mirror traffic with mirrorPercentage; mirrored requests are "fire and forget", the responses are discarded, and the Host header gets -shadow appended. Linkerd: an HTTPRoute (policy.linkerd.io/v1beta2 or the Gateway API group) whose parentRefs point at a Service and whose backendRefs carry weights; header matches route tester traffic. The Linkerd TrafficSplit HTTPRoute migration in one line: replace each SMI TrafficSplit with an HTTPRoute that has the same backends and weights.

yaml
# Istio: subsets by pod label in a DestinationRule, weights and a mirror in a
# VirtualService. Mirrored requests are "fire and forget": responses from v2
# are discarded, and their Host header gets a -shadow suffix.
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
  name: orders-api
  namespace: shop
spec:
  host: orders-api.shop.svc.cluster.local
  subsets:
    - name: v1
      labels:
        version: v1
    - name: v2
      labels:
        version: v2
---
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: orders-api
  namespace: shop
spec:
  hosts:
    - orders-api.shop.svc.cluster.local
  http:
    - name: testers
      match:
        - headers:
            x-canary:
              exact: always
      route:
        - destination:
            host: orders-api.shop.svc.cluster.local
            subset: v2
    - name: split
      route:
        - destination:
            host: orders-api.shop.svc.cluster.local
            subset: v1
          weight: 95
        - destination:
            host: orders-api.shop.svc.cluster.local
            subset: v2
          weight: 5
      # Shadow 20 % of v1-bound traffic to v2 as well (dark traffic).
      mirror:
        host: orders-api.shop.svc.cluster.local
        subset: v2
      mirrorPercentage:
        value: 20.0
text
East-west canary of orders-api called by checkout-service (Istio)
1  checkout-service -> orders-api.shop.svc: sidecar applies the VirtualService
2  x-canary: always set by the caller's test harness -> subset v2
3  otherwise 95 % v1, 5 % v2 by weight
4  20 % of requests also mirrored to v2; v2's responses discarded
5  Argo Rollouts trafficRouting.istio rewrites the weights; Flagger does the same with provider: istio

Real scenarios:

  • A Go gRPC service called only by other services: no Ingress involved, so the mesh is the only place to split.
  • A team on Linkerd with old TrafficSplit objects: migrate them to HTTPRoute before the SMI extension is removed.
  • Shadowing a rewritten pricing service with production calls for a week, comparing logs offline.
  • Istio's own traffic-shifting task now shows both a VirtualService and an HTTPRoute version of the same 50/50 split.
MeshObjectWeight fieldStatus
IstioVirtualService + DestinationRule (networking.istio.io/v1)http[].route[].weightSupported; Gateway API also supported
IstioHTTPRoute (Gateway API)backendRefs[].weightSupported
LinkerdHTTPRoutebackendRefs[].weightRecommended
LinkerdSMI TrafficSplitbackends[].weightDeprecated (SMI archived)

Fix: use the mesh for east-west canaries and mirroring; prefer HTTPRoute where your mesh supports it; let the progressive delivery controller own the weights.

Progressive delivery with Argo Rollouts: Rollout CRD, steps, analysis, promotion, abort Must-know ​

In plain words: Argo Rollouts is a controller with a Deployment-like resource (Rollout) whose update strategy is a list of steps: send 5 %, wait, check metrics, send 20 %... If a check fails, it sends everyone back to the old version on its own.

Common misunderstanding: "The canary weight is the number of canary Pods." Without traffic routing it is approximated by Pods ("if a Rollout has 10 Replicas and 10% for the first setWeight step, the controller will scale the new desired ReplicaSet to 1 replicas and the old stable ReplicaSet to 9"; 41 % of 10 becomes 4 Pods). With traffic routing the router enforces the exact weight, and "the Stable ReplicaSet owned by the Rollout remains fully scaled up as the Rollout progresses through the Canary steps" unless dynamicStableScale: true.

Definition: "Argo Rollouts is a Kubernetes controller and set of CRDs which provide advanced deployment capabilities such as blue-green, canary, canary analysis, experimentation, and progressive delivery features to Kubernetes." The Rollout CRD "acts as a drop-in replacement for a Deployment resource". Canary steps: setWeight ("the percentage of traffic that should be sent to the canary"), pause (with duration, or {} to wait until kubectl argo rollouts promote), analysis (inline, blocking), setCanaryScale, setHeaderRoute, setMirrorRoute, experiment. An AnalysisTemplate "defines how to perform a canary analysis, such as the metrics which it should perform, its frequency, and the values which are considered successful or failed"; an AnalysisRun "is an instantiation of an AnalysisTemplate"; runs end "Successful, Failed, or Inconclusive, and the result of the run affect if the Rollout's update will continue, abort, or pause, respectively". With metrics provider Prometheus each measurement runs a PromQL query and evaluates successCondition (and optional failureCondition); failureLimit defaults to 0 ("no failures are tolerated"). Promotion happens when steps complete (or promote, promote --full); abort "stops progressing the current rollout and reverts all steps. The previous ReplicaSet will be active." A failed analysis performs that abort automatically: automatic rollback, "setting the canary weight back to zero, and the Rollout would be considered in a Degraded".

Canary analysis loop: weight, wait, measure, decidesetWeight N %5 -> 20 -> 50 -> 100pauseduration: 5m (or {})AnalysisRun / Flagger checkPrometheus: success rate of the canaryp99 latency, every intervalsuccessConditionmet?yesnext stepor 100 %: promotenofailed measurements> failureLimit / threshold?yesabort: weight -> 0, stable serves allRollout Degraded / Canary Failed; alertfix forward or revert the Git changeno: measure againArgo Rollouts: Successful continues, Failed aborts, Inconclusive pauses for a human (kubectl argo rollouts promote / abort).Flagger: minimum time to promote = interval x (maxWeight / stepWeight); time to roll back = interval x threshold.

The chapter's Rollout for the Go service (Gateway API plugin, background analysis from step 2, one inline analysis) and its templates are in Go; the essential part:

yaml
strategy:
  canary:
    canaryService: orders-api-canary
    stableService: orders-api-stable
    trafficRouting:
      plugins:
        argoproj-labs/gatewayAPI:
          httpRoute: orders-api
    analysis:                      # background, from step index 2; templates have no count,
                                   # so they measure until the rollout ends
      startingStep: 2
      templates: [{templateName: http-success-rate}, {templateName: http-latency-p99}]
    steps:
      - setWeight: 5
      - pause: {duration: 2m}
      - setWeight: 20
      - pause: {duration: 5m}
      - analysis: {templates: [{templateName: http-success-rate-gate}]}   # finite: count 5
      - setWeight: 50
      - pause: {duration: 10m}
      - setWeight: 100
text
kubectl argo rollouts get rollout orders-api --watch   (expected, not run: state transitions)
1  image bumped in Git, Argo CD syncs the Rollout: new ReplicaSet created, canary Pods Ready
2  step 0 setWeight 5: plugin sets HTTPRoute weights 95/5
3  step 1 pause 2m; step 2 setWeight 20 -> background AnalysisRun starts (success rate + p99, every 1m)
4  step 4 inline analysis (http-success-rate-gate): 5 measurements, 1 per minute; blocks; the background run continues
5  measurement 3 fails (success 0.991 < 0.995), 4 fails, 5 fails -> failureLimit 2 exceeded -> AnalysisRun Failed
6  Rollout aborts: weights 100/0, status Degraded; abortScaleDownDelaySeconds 30 then canary scaled down
7  Git still says 1.5.0: revert the commit (or push a fix); the next sync starts a new rollout

Real scenarios:

  • Fifty services deploy 10 times a day each; nobody watches dashboards; analysis gates every one.
  • A rollout pauses {} at 50 % over a weekend; Monday the owner promotes after reviewing business metrics.
  • An emergency fix: kubectl argo rollouts promote orders-api --full skips "analysis, pauses, and steps".
  • A rollback to a version still inside rollbackWindow.revisions skips all steps instead of re-running a 30-minute canary.
FeatureField / commandDefault / note
Traffic providerstrafficRouting: nginx, istio, alb, smi, traefik, apisix, ambassador, appMesh, pluginsGateway API through the argoproj-labs/gatewayAPI plugin
Background analysisstrategy.canary.analysis + startingStepRuns until the rollout ends
Inline analysissteps[].analysisBlocks the step
Blue-greenstrategy.blueGreen.activeService/previewServiceautoPromotionEnabled true, scaleDownDelaySeconds 30
Abort / retrykubectl argo rollouts abort / retry rolloutAbort keeps spec.template at the new version
Promotekubectl argo rollouts promote [--full]--full skips everything
Undokubectl argo rollouts undoLike kubectl rollout undo for Rollouts
Rollback windowspec.rollbackWindow.revisionsSince v1.4; skip steps for recent revisions
Gitnone"Argo Rollouts doesn't read/write anything to Git"

Fix: start with two metrics you already trust (success rate and p99 of the canary only), short steps, failureLimit small; treat "no data" as failure (len(result) > 0 && ...) so an unrouted canary cannot pass; add ignoreDifferences in Argo CD for the fields the controller writes; and write the "revert in Git after an abort" step into the runbook.

Flagger: Canary CRD, MetricTemplates, webhooks Important ​

In plain words: Flagger keeps your ordinary Deployment and builds the canary machinery around it: a primary copy, Services, routes, and an analysis loop that shifts traffic step by step.

Common misunderstanding: "Flagger replaces the Deployment like Argo Rollouts does." It does not: "The primary deployment is considered the stable release of your app, by default all traffic is routed to this version and the target deployment is scaled to zero." You keep editing the original Deployment; Flagger detects the change ("including secrets and configmaps") and runs the analysis before copying it to <name>-primary.

Definition: "Flagger is a progressive delivery tool that automates the release process for applications running on Kubernetes." The Canary CRD (flagger.app/v1beta1) references a targetRef (Deployment or DaemonSet), an optional autoscalerRef, a service block (Flagger creates <name>, <name>-primary and <name>-canary ClusterIP Services), a provider (Istio, Linkerd, NGINX, Contour, Gloo, Skipper, Traefik, Kuma, Gateway API, APISIX, Knative, App Mesh) and an analysis block: interval, threshold ("max number of failed metric checks before rollback"), maxWeight, stepWeight, metrics (builtin request-success-rate and request-duration, or MetricTemplate references with thresholdRange), and webhooks (confirm-rollout, pre-rollout, rollout, confirm-traffic-increase, confirm-promotion, post-rollout, rollback, event; load tests run as rollout webhooks). Timing is arithmetic: the minimum time to promote is interval * (maxWeight / stepWeight); the time to roll back is interval * threshold. Strategies: canary, A/B testing ("HTTP headers and cookies traffic routing"), blue/green ("no service mesh or ingress controller is required"), blue/green mirroring.

text
Flagger canary for shop-web (interval 1m, stepWeight 10, maxWeight 50, threshold 5)
1  edit Deployment shop-web image -> Flagger: "New revision detected"
2  pre-rollout webhook: curl /up on shop-web-canary must pass, else no traffic at all
3  weight 10 % -> check error-rate < 1 %, request-duration p99 < 500 ms -> pass
4  weight 20, 30, 40, 50 % (one minute each, load-test webhook generating traffic)
5  promotion: copy target spec to shop-web-primary, route 100 % to primary, scale target to 0
failure path: 5 failed checks -> weight 0, canary scaled to 0, Canary status Failed (5 min worst case)

Real scenarios:

  • A Flux-based platform: Flagger is part of the Flux family and reacts to Deployments Flux applies.
  • Laravel shop-web (Nginx + php-fpm in one Pod) canaried through the Gateway API with the Nginx request metrics.
  • skipAnalysis: true in an emergency: "Flagger checks if the canary deployment is healthy and promotes it without analysing it".
  • A config-only change (ConfigMap edit) triggers a canary too: good for feature-flag files, surprising if you did not expect it.
Argo RolloutsFlagger
Workload objectReplaces Deployment with Rollout (or workloadRef)Keeps Deployment; generates -primary
StepsExplicit list (setWeight, pause, analysis, ...)stepWeight/maxWeight or stepWeights list, iterations for A/B
MetricsAnalysisTemplate providers: Prometheus, Datadog, New Relic, Wavefront, CloudWatch, Graphite, InfluxDB, SkyWalking, Kayenta, web, job, pluginBuiltins + MetricTemplate types: Prometheus, Datadog, CloudWatch, New Relic, Graphite, Dynatrace, InfluxDB, Stackdriver, Splunk, Azure Monitor, Keptn, external metrics
Manual gatespause: {} + promoteconfirm-rollout / confirm-promotion webhooks
UIArgo Rollouts dashboard, Argo CD extensionGrafana dashboards, alerts
EcosystemArgo CDFlux

Fix: choose by ecosystem and by whether you can change the workload kind; with Flagger, mind that the target Deployment is scaled to zero, so HPAs and dashboards should look at -primary.

Release health: error rate, p99 latency, SLO-based promotion, error budget burn rate Must-know ​

In plain words: "Is the new version healthy?" must be a query, not a feeling. Measure the canary's error rate and tail latency, compare them with a threshold and with the stable version, and connect both to the service's SLO.

Common misunderstanding: "Average latency is fine to gate on." Averages hide the slow tail that users feel; gate on p99 latency (or p95) of the canary. And "canary vs stable" alone is not enough: the SRE workbook warns that "Canarying is an A/B comparison, and it's possible that both A and B can change in tandem", so also use absolute SLO thresholds.

Definition: Release health = the set of service level indicators evaluated during and after a rollout: success rate (non-5xx share), p99 latency, saturation (CPU throttling, queue depth), and business signals (orders per minute). SLO-based promotion = promote only if the canary's SLIs stay inside the SLO and do not burn error budget faster than allowed. Error budget burn rate is "how fast, relative to the SLO, the service consumes the error budget": for a 99.9 % SLO, burn rate 1 = 0.1 % errors (budget lasts 30 days), 10 = 1 % (3 days). The workbook's paging starting points are "2% budget consumption in one hour and 5% budget consumption in six hours". A canary that would page at full traffic should not be promoted; SLAs, SLOs, SLIs & Error Budgets and Alerting That Works own the theory.

text
Turning an SLO into AnalysisTemplate thresholds (orders-api, SLO 99.9 % success, p99 < 300 ms)
1  budget = 0.1 % errors over 30 days
2  canary gets 5 % of traffic for 5 minutes; a 10x burn rate (1 % errors) must fail the step
3  successCondition: result[0] >= 0.995  (0.5 % errors = burn rate 5: fail before it pages)
4  p99 latency gate: result[0] <= 0.300 seconds
5  no data at all (canary unrouted, metric renamed): len(result) > 0 required -> Failed
6  promotion after 50 % for 10 min only if the stable service is not already burning budget

Real scenarios:

  • An abort because of a CPU-heavy JSON change: success rate fine, p99 up from 180 to 450 ms.
  • A false abort: a downstream outage hit stable and canary alike; the comparison was fine, the absolute check failed. Pausing the rollout (Inconclusive) is better than promoting into an incident.
  • A metric renamed in the new version (http_requests_total to http_server_requests_total): the canary "has no errors" because it has no series; require data.
  • Low-traffic services: replace weight analysis by a synthetic load webhook (Flagger's load tester, an Argo Rollouts job metric).
SignalQuery shape (Prometheus)Typical gate
Success ratesum(rate(..{code!~"5.."}[2m])) / sum(rate(..[2m]))>= 0.99-0.999 by SLO
p99 latencyhistogram_quantile(0.99, sum by (le) (rate(.._bucket[2m])))<= SLO latency threshold
Error budget burnerrors / (1 - SLO) over a window< 10 (never promote a page)
SaturationCPU throttling, memory, queue lagWithin baseline +X %
Businessorders/min, payment successWithin baseline band
Pod healthrestarts, readiness flapsZero restarts

Fix: derive thresholds from the SLO, gate on canary-only series with enough traffic, require data, add one business metric, and keep the same queries on the dashboard humans use during an incident.

A/B testing, shadow traffic and dark launch Important ​

In plain words: A canary asks "is the new version broken?". An A/B test asks "do users prefer B?". Shadow traffic copies real requests to the new version and throws its answers away. A dark launch runs new code for real users without showing them the result.

Common misunderstanding: "A canary is an A/B test with a small B." A canary is short, per request, and decided by operational metrics; an A/B test is long, sticky per user, sized for statistical power and decided by product metrics. Mixing them gives bad answers to both questions.

Definition: A/B testing: a fixed split of users (sticky by user ID via a flag or a cookie) between variants, measured on conversion or engagement; Flagger's A/B strategy routes by "HTTP headers and cookies". Shadow traffic (mirroring): a copy of each request is sent to the new version; the client only sees the primary response (Istio: mirrored requests are "fire and forget"; Gateway API's RequestMirror filter; Argo Rollouts' "Mirrored traffic where all the traffic is copied and sent to the new version in parallel (but the response is ignored)"). Dark launch (Fowler): "taking a new or changed back-end behavior and calling it from existing users without the users being able to tell it's being called", to "assess the additional load and performance impacts upon the system before making a public announcement".

text
Shadowing a rewritten recommendations backend
1  VirtualService: 100 % to v1, mirror 20 % to v2 (mirrorPercentage 20)
2  v2 receives requests with Host "recommendations-shadow"; its responses are discarded
3  compare v2 logs/metrics offline: latency, error rate, result diff against v1
4  side effects: v2 must NOT write orders, send e-mails or charge cards (use a read-only mode)
5  when diff and load look right: canary v2 for real, with v1 as control

Real scenarios:

  • Checkout button colour: A/B test via feature flag variants for two weeks, not a canary.
  • A new search engine: shadow 10 % of queries for a week, compare top-10 overlap.
  • Dark-launching recommendations: the checkout calls the new engine and ignores the result (Fowler's toaster and steak knives example).
  • A mirrored POST that charges a card twice: why shadow targets need side-effect isolation.
TechniqueUsers affectedDecided byTools
CanarySmall share, per requestError rate, latencyArgo Rollouts, Flagger, HTTPRoute weights
A/B testFixed share, sticky per userProduct metrics, significanceFlags (LaunchDarkly experiments, Unleash variants, Flagsmith multivariate), Flagger A/B
Shadow trafficNone (responses discarded)Load, diff of outputsIstio mirror, Gateway RequestMirror, Argo Rollouts setMirrorRoute
Dark launchNone visiblyLoad, latency of the new callFeature flag around the call

Fix: name the question first; use canaries for safety, A/B for product, shadow and dark launch for load and correctness; give mirrored backends a no-side-effects mode.

Feature flags: OpenFeature, flag evaluation, targeting rules, percentage rollout, kill switch, flag debt Must-know ​

In plain words: A feature flag is an if whose condition lives outside the code. The code for both paths is deployed; a flag service decides, per request or per user, which path runs, and you can change that decision without deploying.

Common misunderstanding: "Flags replace deployment strategies." They complement them. A flag protects the code it wraps; it does nothing for a bad dependency upgrade, a memory leak, a broken migration or a crash at start-up, which only a canary, blue-green or rolling update with readiness can catch. And every flag is debt: Fowler's article says "Savvy teams view their Feature Toggles as inventory which comes with a carrying cost, and work to keep that inventory as low as possible."

Definition: OpenFeature "is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool" (a CNCF incubating project). The application calls an OpenFeature client; a provider (flagd, LaunchDarkly, Unleash, Flagsmith, GitLab's Unleash-compatible API, an in-memory provider in tests) does the flag evaluation against an evaluation context whose targeting key identifies the user. The specification makes failure safe: "Flag evaluation calls must always return the default value in the event of abnormal execution", and client creation "MUST NOT throw". Targeting rules match context attributes (plan, country, e-mail domain). A percentage rollout hashes the targeting key into buckets so the same user always gets the same answer: LaunchDarkly hashes context key, kind, flag key and a salt into "100,000 buckets"; Unleash "uses a normalized MurmurHash of a user's unique ID" with the flag name as default groupId, "so the same user can fall inside the rollout for one flag and outside it for another". A kill switch is a permanent operational flag; LaunchDarkly: "permanent boolean flags with two variations", used "to quickly turn off functionality when needed". Fowler's categories: release, experiment, ops and permissioning toggles. Flag debt: Unleash marks flags "potentially stale automatically once they pass their expected lifetime".

text
Flag evaluation in the Go service (flags.Service.NewCheckout), one request
1  handler builds EvaluationContext{targetingKey: "u-7", plan: "pro", country: "NL"}
2  client.Boolean(ctx, "new-checkout", false, evalCtx)       default false = old path
3  provider: deny rule country=DE? no. allow rule plan=internal? no.
4  percentage: Bucket("new-checkout", "u-7") = fnv32a(...) % 100000 = 61234 >= 5 % of 100000 -> off
5  result false, reason SPLIT, variant off; logged as flag=new-checkout value=false reason=SPLIT variant=off
6  provider unreachable instead: OpenFeature returns the default false with reason ERROR (never panics)

The Go code and its seven tests (missing flag, disabled flag, rule order, stickiness and monotonic growth from 10 % to 50 %, missing targeting key, kill switch flipped at runtime, independent buckets per flag) are in Go; the Laravel side uses Pennant for the release flag and a cache-backed kill switch, in Laravel.

Real scenarios:

  • A new checkout behind new-checkout: staff first (targeting rule), then 1 %, 5 %, 25 %, 100 % over a week, then the flag and the old code are deleted.
  • The recommendations service melts during a sale: on-call flips the recommendations kill switch; checkout keeps working without the widget.
  • A flag service outage: every evaluation returns its coded default; the release flag falls back to the old path, the kill switch to "on". Choosing those defaults is a design decision per flag.
  • Three years later: 400 flags, nobody knows which are safe to remove. Expiry dates, owners and stale-flag reports prevent it.
ProductModelPercentage rolloutNotes
OpenFeatureVendor-neutral API + providersProvider-dependent (flagd "fractional" evaluation)Go SDK github.com/open-feature/go-sdk v1.17.1 used here; PHP SDK exists
LaunchDarklySaaS, SDK evaluates locally from a stream100 000 buckets from a hash of context key and flagKill switch flag template; experiments
UnleashOpen source / hosted; activation strategiesGradual rollout, MurmurHash stickinessStale-flag detection; GitLab feature flags are "based on Unleash"
FlagsmithOpen source / hosted; identities, traits, segmentsPercentage split segmentsSegments evaluated server-side in remote evaluation mode
Laravel PennantIn-app, database or array driverLottery::odds(...), result STORED per scopeNot hash-based: raising odds affects only unresolved users
GitLab feature flagsUnleash-compatible APIPercent rollout strategiesBuilt into GitLab projects

Fix: put every flag behind one small wrapper (one file of keys, typed accessors, defaults chosen per flag), log evaluations with reason, give release flags an owner and an expiry, and delete the flag and the dead branch in the release after 100 %.

Rollback mechanics: digests, kubectl rollout undo, revision history, Helm rollback, GitOps revert Must-know ​

In plain words: Rolling back means running exactly the bytes that ran before. That only works if you recorded which bytes those were (a digest, not a tag) and if the tool that applies changes agrees with your rollback.

Common misunderstanding: "kubectl rollout undo restores everything from the last release." Kubernetes: "the new revision is created if and only if the Deployment's Pod template (.spec.template) is changed"; "when you roll back to an earlier revision, only the Deployment's Pod template part is rolled back." ConfigMaps, Secrets, Services and replica counts stay as they are. And under GitOps the undo is temporary: the controller re-applies what Git says.

Definition: Image digest pinning: deploying name@sha256:... (containerd and every OCI runtime pull the exact manifest) so a rollback target cannot have moved; tags are for humans. Revision history: a Deployment keeps old ReplicaSets, "By default, 10 old ReplicaSets will be kept" (revisionHistoryLimit); "once an old ReplicaSet is deleted, you lose the ability to rollback to that revision"; kubectl rollout history lists revisions with CHANGE-CAUSE from the kubernetes.io/change-cause annotation; kubectl rollout undo deployment/x [--to-revision=N]. Helm rollback: helm rollback <RELEASE> [REVISION]; "If this argument is omitted or set to 0, it will roll back to the previous release" (history limited by --history-max, default 10). GitOps revert: revert the commit that bumped the digest; Argo CD or Flux syncs the previous state. Argo CD's own argocd app rollback "cannot be performed against an application with automated sync enabled". Argo Rollouts: abort leaves spec.template at the new version ("If the Rollout leaves the aborted state, it will try to go to the new version"); rollbackWindow.revisions lets a re-applied older spec skip steps.

text
GitOps rollback of orders-api 1.5.0 -> 1.4.2 (Argo CD auto-sync + Argo Rollouts)
1  analysis fails at 20 %: Rollout aborts, cluster serves 1.4.2, app Degraded, Git still says 1.5.0
2  on-call: git revert <bump commit> in the env repo -> digest back to sha256:11... (1.4.2)
3  Argo CD syncs: Rollout spec.template now equals the stable ReplicaSet
4  controller: moving back to the stable ReplicaSet -> no new canary needed; status Healthy
5  without step 2: Argo CD syncs do nothing (Git and the live Rollout both say 1.5.0), the app stays Degraded on 1.4.2,
   and `kubectl argo rollouts retry rollout orders-api` (or any new revision) would start the bad 1.5.0 canary again

Real scenarios:

  • image: orders-api:1.4 re-pushed by a hotfix pipeline: "rolling back to 1.4" deploys different code. Digests prevent it.
  • A Helm upgrade changed a Secret and the image: helm rollback restores both (Helm stores the whole rendered release), kubectl rollout undo only the image.
  • revisionHistoryLimit: 0 to "save etcd space": the Deployment can no longer roll back at all.
  • An on-call runs kubectl rollout undo on an Argo CD-managed app with self-heal: Argo CD reverts the undo within a sync.
ToolRollback commandWhat it restoresKeeps
Deploymentkubectl rollout undo [--to-revision=N]Pod templateEverything else
Argo Rolloutskubectl argo rollouts abort / undoTraffic to stable / previous templateGit unchanged
Helmhelm rollback RELEASE [REV]All rendered manifests of that revisionData, CRD changes, hook side effects
Argo CDgit revert (or argocd app rollback without auto-sync)Git-described stateOut-of-Git objects
Fluxgit revert; Flagger rollback for canariesGit-described state
AWS ASGInstance refresh rollback (manual or auto_rollback on alarm)Previous launch templateData on instances
Capistrano / Deployerdeploy:rollback / dep rollback (symlink to previous release)CodeMigrations

Fix: deploy digests and record them in Git; keep revisionHistoryLimit and --history-max at a few releases; under GitOps the rollback is a Git operation (even when a controller already reverted the traffic); rehearse rollback on staging like Capistrano's docs advise ("test your rollback procedure before trying it for the first time in a time of crisis").

N-1 compatible releases: rename orders.addr to orders.shipping_addresstime / releasesR1 expandADD COLUMNshipping_address NULLcode: uses addrR0 still worksR2 dual-writewrite both columnsbackfill job (batches)read: addrR1 still worksR3 switch readsread new columnstill write both(often behind a flag)R2 still worksR4 contractstop writing addrnext release: DROP addronly after R3 can nolonger come backRule: migrations run BEFORE the new code (expand) or one release AFTER it (contract),never "rename in place". Rollback of any single step = previous code on the current schema.Mechanics of each migration (locks, batching, online DDL) live in Schema Migrations; this page owns their order relative to the rollout.

Database-compatible releases: N-1 compatibility, expand/contract, forward-only migrations, migration ordering Must-know ​

In plain words: During any rollout, old and new code run at the same time against one database, and after a rollback the old code runs against whatever schema the new release left behind. So each release's schema must work for the version before it.

Common misunderstanding: "Run migrate:rollback when you roll back the code." Down migrations are rarely tested, often destroy data (a dropped column's contents are gone) and race with the new code still running. The safe pattern is forward-only migrations that never break the previous release.

Definition: N-1 compatibility: release N works with schema N and N-1; schema N works with code N and N-1. Backward-compatible releases follow from it: additive changes first, removals later. Expand/contract (parallel change: "expand, migrate, and contract"; the expand contract link for locks, backfills and online DDL is Schema Migrations): expand the schema (add column, add table, add nullable field), deploy code that writes both and reads the old, backfill, switch reads, stop writing the old, and only in a later release contract (drop). Forward-only migrations: no down migrations in production; a mistake is fixed with a new migration. Migration ordering: expand migrations run before the new code takes traffic (the old code ignores the new column); contract migrations run one release after the code stopped using the old structure. Database-compatible releases are what makes rolling, canary and blue-green safe; without them only Recreate (with downtime) is honest.

text
Rename orders.addr -> shipping_address, four releases, each one rollback-safe
R1  migrate (before switch): ADD COLUMN shipping_address NULL     code: reads/writes addr
R2  code: writes addr AND shipping_address; backfill job in batches
R3  code: reads shipping_address (behind a flag), still writes both
R4  code: stops writing addr; R5 migration: DROP COLUMN addr (R3 can no longer come back)
roll back R3 -> R2: fine (both columns written).  "rename in place" in one release: R(N-1) crashes

Real scenarios:

  • A NOT NULL column added without a default: old Pods' inserts fail during the rolling update.
  • An enum value added in R2 and used immediately: R1 Pods reading that row crash on an unknown value; ship the reader first.
  • Blue-green on a shared database: the switch is instant, the schema still has to serve both colours (Fowler: "separate the deployment of schema changes from application upgrades").
  • A Laravel migration in a deploy.sh that runs after the symlink switch: for a few seconds new code queries a column that does not exist yet. The chapter's script migrates before the switch.
ChangeExpand step (release N)Contract step (N+1 or later)
Add columnNullable or with defaultMake NOT NULL after backfill
Rename columnAdd new, dual-write, backfillDrop old
Drop columnStop reading and writing itDrop it
Change typeNew column + dual-writeDrop old
Add enum value / statusReaders tolerate it firstWriters start using it
Split tableNew table, dual-writeRemove old columns
Add indexA non-blocking index build (see Schema Migrations)n/a

Fix: review every migration for "does release N-1 still work?"; run expand migrations as a pre-switch step (Laravel deploy.sh, an Argo CD PreSync hook Job, a Helm pre-upgrade hook), never down migrations in production, and contract only after the rollback window has passed.

Zero-downtime details: readiness, readiness gate, preStop, connection draining Must-know ​

In plain words: A Pod that is about to stop must first leave the load balancer's list, then finish what it is doing, then exit. A Pod that just started must not get traffic until it can serve it. Every strategy above relies on both.

Common misunderstanding: "SIGTERM means stop accepting requests now." When the Pod starts terminating, the endpoint removal and the SIGTERM happen at about the same time; kube-proxy, Ingress controllers and cloud load balancers learn about the removal a little later. An app that closes its listener instantly drops requests routed during that gap.

Definition: Readiness probe: the kubelet's check that puts a Pod into Service endpoints. Readiness gate: extra conditions in spec.readinessGates; a Pod is ready only when "All containers in the Pod are ready" and "All conditions specified in readinessGates are True" (stable since Kubernetes v1.14). The AWS Load Balancer Controller uses one so that a rolling update does not terminate old Pods "until the newly created pods are »Healthy« in the ALB/NLB target group". preStop: a hook that "must complete before the TERM signal to stop the container can be sent"; the grace period "applies to the total time it takes for both the PreStop hook to execute and for the Container to stop normally"; the sleep action (stable in v1.34) needs no shell in the image. Connection draining: keep serving in-flight and late-routed requests, then close (Go http.Server.Shutdown "works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle"); load balancers have the same idea as deregistration delay. The full termination sequence is in Kubernetes Workloads.

text
Pod of orders-api terminating (preStop sleep 5, DrainDelay 5 s, ShutdownTimeout 15 s, grace 30 s)
T+0   Pod marked Terminating; endpoint removal starts; preStop sleep 5 s begins (grace clock starts)
T+5   SIGTERM -> signal.NotifyContext cancels -> /readyz returns 503
T+5..10  DrainDelay: still serving requests that were already routed here
T+10  srv.Shutdown: listener closed, idle conns closed, wait for in-flight (<= 15 s)
T+25  worst case Shutdown returns context.DeadlineExceeded; process exits; SIGKILL would come at T+30

Real scenarios:

  • 502s at every deploy behind an ALB: no readiness gate, so old targets were drained before new ones were healthy in the target group.
  • 502s for a second at every scale-down: no preStop delay; the app exited before the Ingress controller reloaded its upstreams.
  • A Go test in this chapter that waited 5 s in Shutdown: Go's Transport had pre-dialled a spare connection that never sent a request; net/http treats such StateNew connections as idle only after 5 s ("Issue 22682"). Keep ShutdownTimeout above 5 s in production.
  • php-fpm stopped with SIGTERM: FPM's fpm_events.c handles SIGTERM as "Terminating ..." and SIGQUIT as "Finishing ..." (graceful), which is why its image uses STOPSIGNAL SIGQUIT.
MechanismWherePurpose
readinessProbeContainerOnly ready Pods receive traffic
readinessGatesPod specExternal conditions (LB target healthy)
minReadySecondsDeploymentPod must stay ready N seconds before counting
lifecycle.preStop.sleepContainerWait for endpoint removal before SIGTERM
terminationGracePeriodSecondsPod (default 30)Budget for preStop + shutdown
App drain (Shutdown, FPM SIGQUIT, Octane graceful)ProcessFinish in-flight work
Deregistration delayCloud LB target groupLB-side draining

Fix: readiness that fails on SIGTERM, a preStop sleep of a few seconds, an application drain with a timeout, and a grace period larger than their sum; on AWS, readiness gates from the load balancer controller.

VM strategies: immutable infrastructure, AMIs, instance refresh, symlink release switch, Capistrano and Deployer Important ​

In plain words: Without Kubernetes the same strategies exist. Either bake a new machine image per release and replace machines (immutable), or keep machines and switch a current symlink between release directories (mutable but atomic).

Common misunderstanding: "Symlink deploys are zero-downtime by themselves." The switch is atomic; the processes are not: php-fpm workers and OPcache keep the old paths until reloaded, queue workers keep the old code in memory until restarted, and a migration that runs after the switch leaves a gap. See Laravel zero-downtime.

Definition: Immutable infrastructure: servers are never changed after launch; a release is a new image (an AMI built by Packer) and a replacement of instances (Fowler's ImmutableServer). Instance refresh (EC2 Auto Scaling): "Terminates instances and launches new ones in batches"; with minimum healthy percentage 100 it will "Launch the new instances first before terminating the old ones"; checkpoints "Pause the instance refresh after a certain percentage of replacements"; auto rollback "reverses what was deployed if the instance refresh fails for some reason or if any CloudWatch alarms you specify go into the ALARM state". Terraform drives it with an instance_refresh block. Symlink release switch: Capistrano's layout, "current is a symlink pointing to the latest release. This symlink is updated at the end of a successful deployment. If the deployment fails in any step the current symlink still points to the old release."; Deployer's deploy:symlink uses mv -T when available ("Use mv -T if available"), i.e. an atomic rename(2) of a new link over the old one. The shell implementation is Shell Scripting → deploy.sh.

hcl
# Immutable VM releases: Packer bakes an AMI per version, Terraform points the
# launch template at it, and the Auto Scaling group replaces instances with an
# instance refresh (rolling, checkpoints, automatic rollback on alarm).
# Argument names from the AWS provider's aws_autoscaling_group docs; not applied here.

variable "release_ami_id" {
  description = "AMI built by Packer for this release (one AMI per version, never patched in place)"
  type        = string
}

resource "aws_launch_template" "orders_api" {
  name_prefix   = "orders-api-"
  image_id      = var.release_ami_id
  instance_type = "t4g.small"
}

resource "aws_autoscaling_group" "orders_api" {
  name                = "orders-api"
  min_size            = 4
  max_size            = 8
  desired_capacity    = 4
  vpc_zone_identifier = var.private_subnet_ids
  target_group_arns   = [var.target_group_arn]
  health_check_type   = "ELB"

  launch_template {
    id = aws_launch_template.orders_api.id
    # "$Latest" would not start a refresh; latest_version does.
    version = aws_launch_template.orders_api.latest_version
  }

  instance_refresh {
    strategy = "Rolling"
    preferences {
      min_healthy_percentage = 100 # launch new instances before terminating old ones
      max_healthy_percentage = 150
      instance_warmup        = 120
      checkpoint_percentages = [25, 100] # pause after the first quarter: a VM canary
      checkpoint_delay       = 600
      skip_matching          = true
      auto_rollback          = true
      alarm_specification {
        alarms = [aws_cloudwatch_metric_alarm.orders_5xx.alarm_name]
      }
    }
  }
}

variable "private_subnet_ids" { type = list(string) }
variable "target_group_arn" { type = string }

resource "aws_cloudwatch_metric_alarm" "orders_5xx" {
  alarm_name          = "orders-api-target-5xx"
  namespace           = "AWS/ApplicationELB"
  metric_name         = "HTTPCode_Target_5XX_Count"
  statistic           = "Sum"
  period              = 60
  evaluation_periods  = 3
  threshold           = 20
  comparison_operator = "GreaterThanThreshold"
}
text
Immutable VM release with instance refresh (checkpoint 25 %, min healthy 100 %)
1  Packer bakes ami-orders-1.5.0; Terraform sets launch template image_id -> new latest_version
2  instance refresh starts: launch 1 new instance before terminating 1 old (4 desired)
3  new instance passes ELB health check, warms up 120 s
4  checkpoint at 25 %: wait 600 s, 1 of 4 instances on 1.5.0 = a VM canary
5  alarm orders-api-target-5xx fires -> auto rollback: replace refreshed instances with the old template
6  no alarm -> continue to 100 %

Real scenarios:

  • A Go binary on four EC2 instances: AMI per release, instance refresh with a 25 % checkpoint.
  • A Laravel app on two Forge-style VMs: Deployer or the chapter's deploy.sh, symlink switch, php-fpm reload.
  • Blue-green on VMs: two Auto Scaling groups behind weighted ALB target groups.
  • version = "$Latest" in the Terraform launch template block: the provider docs warn that "A refresh will not start" with it; use latest_version.
ApproachRollbackSpeedFits
AMI + instance refreshRefresh to the previous template (auto on alarm)Minutes (boot time)Go binaries, stateless fleets
Two ASGs + LB weightsShift weights backSecondsBlue-green on VMs
Symlink releases (Capistrano, Deployer, deploy.sh)Symlink to previous, reloadSecondsPHP and Ruby apps on long-lived VMs
In-place package upgradeReinstall old packageMinutes, riskyAvoid

Fix: prefer immutable images for anything you can rebuild cheaply; for PHP on VMs use the release-directory layout with an atomic switch and the reload steps below; keep at least the previous release on disk.

Laravel zero-downtime: php-fpm reload, maintenance mode, Octane reload, caches, queue:restart Important ​

In plain words: A Laravel deploy is a file switch plus four kinds of long-lived state that must notice it: php-fpm workers with OPcache, cached config and routes, Octane workers holding the app in memory, and queue workers.

Common misunderstanding: "php artisan down is how Laravel deploys safely." Maintenance mode returns 503 for everyone; Laravel's docs say it "requires your application to have several seconds of downtime" and point to zero-downtime alternatives. Use it only for the rare release that cannot be made N-1 compatible.

Definition: php-fpm reload: the FPM master handles SIGUSR2 as "Reloading in progress ..." (graceful: new workers with the new config and a fresh OPcache); systemctl reload sends it through the unit. Without a reload, OPcache with opcache.validate_timestamps=0 serves old bytecode until "restarting the Web server"; Nginx's $realpath_root ("with all symbolic links resolved to real paths") in SCRIPT_FILENAME makes every request name the real release directory. Laravel maintenance mode: php artisan down (503), --refresh, --retry, --secret and artisan down --with-secret ("If you would like Laravel to generate the secret token for you"), --render="errors::503" (pre-rendered "before any of your application's dependencies have loaded"), and the cache driver for multi-server (APP_MAINTENANCE_DRIVER=cache); "While your application is in maintenance mode, no queued jobs will be handled." Octane reload: "You may gracefully restart the Octane server's application workers using the octane:reload command", typically "after deployment so that your newly deployed code is loaded into memory". Caches: config:cache route:cache view and event caches, all via php artisan optimize; once config is cached, "the env function will only return external, system level environment variables". Queue workers: "long-lived processes and store the booted application state in memory"; php artisan queue:restart makes them "gracefully exit after they finish processing their current job", and Supervisor (or systemd) restarts them; Laravel 13's php artisan reload terminates queue workers, Reverb and Octane in one command.

text
deploy.sh 1.1.0 (traced by tests/laravel-deploy-test.sh with stub binaries, real ln/mv)
1  composer install into releases/1.1.0                         current=1.0.0
2  php releases/1.1.0/artisan migrate --force                   current=1.0.0  (expand only)
3  php releases/1.1.0/artisan optimize                          current=1.0.0  (caches in the new dir)
4  ln -sfn releases/1.1.0 current.new; mv -T current.new current (atomic)
5  systemctl reload php8.4-fpm                                  current=1.1.0
6  php current/artisan queue:restart                            current=1.1.0
7  curl /up and /version == 1.1.0; on failure: switch back, reload, exit 5 (no migrate:rollback)
   (with --maintenance: no switch back; back into maintenance, exit 6 for a human)

Real scenarios:

  • 500s for a minute after each deploy: config:cache ran in the live directory before the new code was in place.
  • Queue jobs fail with "class not found" after a deploy: workers still on the old release; queue:restart was missing.
  • Octane serving the old routes: no octane:reload.
  • A destructive migration that cannot be split: --maintenance wraps it in down --render=... --retry=60 --with-secret / up and accepts the downtime openly. In that mode the script never switches the code back after a failure, because the previous release cannot run on the new schema: a failed smoke test puts the app back into maintenance (exit 6), and any failure between down and up leaves it down with a loud message (exit 7, an EXIT trap). A human then fixes forward, or restores the database before any code rollback.
StateSurvives a symlink switch?Refresh with
php-fpm workers + OPcacheYes (old bytecode, old paths)systemctl reload php-fpm (SIGUSR2); $realpath_root in Nginx
Config / route / view / event cachesPer release directory (bootstrap/cache)php artisan optimize in the new release before the switch
Octane workersYes (app in memory)php artisan octane:reload
Queue workersYes (booted app in memory)php artisan queue:restart + Supervisor
Scheduler (cron schedule:run)Starts fresh each minuteNothing
Sessions, cache, filesShared (shared/, Redis)Must stay compatible across versions

Fix: build, migrate (expand) and cache in the new release while the old one serves; switch atomically; reload php-fpm or Octane; restart queue workers; smoke-test; on failure switch back without touching the database.

Deployment freeze, change windows, post-deploy verification, runbooks and DORA metrics Good to know ​

In plain words: Rules about when to deploy, checks right after a deploy, written steps for when it goes wrong, and four or five numbers that tell you whether the whole process is getting better.

Common misunderstanding: "Freezes make production safer." They stop deploys, not risk: changes pile up and the first deploy after the freeze is the riskiest of the year. Freeze the risky things (schema changes, infrastructure), keep small flag-guarded deploys possible, and keep the emergency path.

Definition: Deployment freeze / change windows: periods when deploys are blocked or allowed (Argo CD sync windows "where syncs will either be blocked or allowed"; GitLab's deploy freeze, during which "GitLab blocks all deployments"; GitHub Actions environment protection with required reviewers and a wait timer). Post-deploy verification: smoke tests (a few critical requests against the new version, before and right after it takes traffic: the Go smoke package, Flagger pre-rollout webhooks, Argo Rollouts prePromotionAnalysis) and synthetic monitoring (the same journeys running continuously from outside, so a regression shows up even with no user traffic). A runbook is the written procedure for a deploy and its rollback: who decides, which command, which dashboard. DORA metrics: deployment frequency, change lead time ("from committed to version control to deployed in production"), change failure rate (DORA's current wording: change fail rate, "deployments that require immediate intervention"), failed deployment recovery time (formerly MTTR, renamed in 2023) and, since 2024, deployment rework rate.

text
Runbook: orders-api release (excerpt)
1  pre: freeze calendar clear? schema change reviewed for N-1? flag default chosen?
2  merge -> CI builds digest -> env repo PR -> Argo CD sync -> Rollout steps start
3  watch: Rollout status, canary success rate, p99, checkout synthetic check
4  abort criteria: analysis Failed, synthetic check red twice, on-call judgement
5  rollback: flag off | kubectl argo rollouts abort | git revert of the bump commit
6  post: smoke suite green on stable; annotate the deploy on dashboards; close the change

Real scenarios:

  • Black Friday: Argo CD deny window for infrastructure apps, application flags still adjustable.
  • A synthetic checkout every minute catches a broken payment redirect at 03:00 with zero real traffic.
  • A team measures change failure rate per strategy: rolling deploys without analysis fail more often than progressive ones; the data justifies the controller.
  • A runbook that says "roll back" without saying how under GitOps: the on-call runs kubectl rollout undo, Argo CD reverts it.
Metric (DORA)MeasuresImproved by
Deployment frequencyThroughputSmall batches, automation, flags
Change lead timeThroughputFast CI, fewer manual gates
Change fail rateInstabilityCanary analysis, N-1 discipline, tests
Failed deployment recovery time (ex-MTTR)Throughput / recoveryFast rollback paths, flags, runbooks
Deployment rework rateInstabilityFewer hotfix deploys

Fix: encode freezes as tool configuration (sync windows, deploy freezes, environment rules) with a documented break-glass path; make smoke tests part of every strategy; keep a runbook per service; and measure the DORA metrics before and after changing strategies.

Mechanics ​

What each controller changes, step by step ​

MomentArgo Rollouts canary (Gateway API plugin)Flagger canary (Gateway API)Plain blue-green script
Spec change detectedNew ReplicaSet (canary), stable RS untouchedTarget Deployment scaled up from 0Green Deployment rolled out by you
Before trafficCanary Pods Ready; canaryService selector gets the new pod-template hashpre-rollout webhooksrollout status, preview smoke test
Each stepHTTPRoute backendRefs weights rewritten; AnalysisRun created or continuedWeight += stepWeight; metrics and webhooks checked each interval(none: one switch)
SuccessStable RS = canary RS; weights 0/100 then stable label moves; old RS scaled downSpec copied to -primary; target scaled to 0Live Service selector patched; verify N requests
FailureAbort: weights 100/0; Degraded; canary scaled down after abortScaleDownDelaySecondsWeight 0; canary scaled to 0; FailedSelector patched back; exit 5
GitUntouchedUntouchedUntouched (script)

Weight arithmetic ​

  • Argo Rollouts without traffic routing: replicas approximate the weight, "finding the whole number with the smallest delta, rounding up the calculation if the deltas are equals": 10 replicas, setWeight: 41 gives 4 canary and 6 stable Pods.
  • Argo Rollouts with traffic routing: the router gets the exact weight; the canary RS has ceil(weight x replicas) Pods by default ("The new ReplicaSet's replica count is equal to the latest SetWeight step percentage multiplied by the total replica count"), the stable RS stays at 100 % unless dynamicStableScale. Beware setCanaryScale with explicit values: the docs' example sends "90% of traffic to only be served by 10% of pods".
  • Ingress-NGINX: share = canary-weight / canary-weight-total (default total 100).
  • Gateway API: share of backend i = weight_i / sum(weights); unspecified weight = 1; a single backend gets 100 % only if its weight is greater than 0 (weight 0 forwards nothing, per the HTTPRoute CRD).
  • Flagger: steps stepWeight, 2 x stepWeight, ... maxWeight; minimum promotion time interval x (maxWeight / stepWeight) (1 m x 50/10 = 5 m here); rollback after interval x threshold (1 m x 5 = 5 m).
  • Percentage flags: bucket = hash(flag, user) mod 100000; on if bucket < percent x 1000. Raising the percentage only adds users (the Go test checks that every 10 % user stays in the 50 % cohort).

Time budgets ​

BudgetFormulaChapter values
Pod shutdownpreStop + drain delay + shutdown timeout < terminationGracePeriodSeconds5 + 5 + 15 = 25 < 30
Go Shutdown floor> 5 s if clients pre-dial (StateNew rule)15 s
Canary duration (Argo)sum of pauses + analysis time2 + 5 + 5 + 10 = 22 min
Canary abort latency (Argo)interval x (failureLimit + 1)1 m x 3 = 3 min
Blue-green rollback windowscaleDownDelaySeconds (or keep old slot)60 s (Argo), unlimited (script)
ASG VM canarywarmup + checkpoint delay120 s + 600 s

Knobs ​

KnobWhereDefaultNotes
strategy.typeDeploymentRollingUpdateRecreate kills all Pods first
revisionHistoryLimitDeployment / Rollout100 disables rollback
scaleDownDelaySecondsRollout blueGreen30Old RS kept after switch
autoPromotionEnabledRollout blueGreentruefalse = wait for promote
abortScaleDownDelaySecondsRollout canary(controller default)Keep canary up after abort for debugging
failureLimit / consecutiveSuccessLimitAnalysisTemplate metric0 / 0 (disabled)-1 disables failureLimit
count / intervalAnalysisTemplate metricno interval: one measurement; interval without count: measures until the run is stoppedBackground templates: no count (guards every stage); inline / post-promotion templates: a finite count so the step can complete
progressDeadlineSecondsFlagger Canary600Rollback if no progress
analysis.intervalFlaggernone: required by the CRD (with threshold and stepWeight, stepWeights or iterations)One check per interval; the chapter sets 1m
canary-weight-totalIngress-NGINX100Finer weights with 1000
backendRefs[].weightHTTPRoute1Proportional
mirrorPercentageIstio100 % if absentFraction of mirrored traffic
--history-maxHelm10Revisions kept per release
min_healthy_percentage / checkpoint_delayASG instance refresh(AWS default) / 3600100 = launch before terminate
opcache.validate_timestampsphp.ini10 in production: reload FPM on deploy
process_control_timeoutphp-fpm0Time children have to react to master signals

Statuses and messages you will actually see ​

WhereMessage / statusMeaningAction
Argo RolloutsRollout Degraded (aborted)Analysis failed or manual abortFix or revert in Git
Argo RolloutsPaused (CanaryPauseStep)pause: {} reachedkubectl argo rollouts promote
Argo RolloutsAnalysisRun InconclusiveNeither success nor failure condition metHuman decides: promote or abort
Argo CDApplication OutOfSync on HTTPRoute weightsController wrote weights Git does not haveignoreDifferences
Argo CD"Rollback cannot be performed against an application with automated sync enabled."argocd app rollback with auto-syncRevert in Git
FlaggerCanary status Failed after the failed-checks thresholdthreshold exceeded (docs: "halt advancement if any metric is under the specified threshold", then roll back)Inspect metrics, fix, re-deploy
KubernetesProgressing=False, ProgressDeadlineExceededRolling update stuckkubectl rollout undo or fix
php-fpmReloading in progress ... (NOTICE)SIGUSR2 receivedExpected on deploy
LaravelHTTP 503 from every routeMaintenance mode left onphp artisan up
Gocontext deadline exceeded from ShutdownIn-flight requests outlived the timeoutRaise timeout or fix slow handler

Go ​

The Go service is the orders API from earlier chapters, reduced to what deployment strategies need from the application: flags through OpenFeature with safe defaults, a readiness endpoint that turns off before shutdown, a bounded drain, and a version stamp on every response.

Before ​

Flags read from environment variables (a change needs a redeploy, and every Pod reads them at start-up only) and a shutdown that drops in-flight requests:

go
// Before: release = deploy, and every deploy drops requests.
func main() {
	newCheckout := os.Getenv("NEW_CHECKOUT") == "true" // flip = new rollout of every Pod
	http.HandleFunc("/checkout", func(w http.ResponseWriter, r *http.Request) {
		if newCheckout {
			checkoutV2(w, r)
			return
		}
		checkoutV1(w, r)
	})
	http.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) })
	// No readiness, no signal handling: SIGTERM kills the process mid-request,
	// and Pods keep receiving traffic until the endpoint update arrives.
	log.Fatal(http.ListenAndServe(":8080", nil))
}

After ​

Flags: OpenFeature client per domain, a release flag with default false and a kill switch with default true, an in-memory targeting evaluator (deny rule, allow rule, sticky percentage) used by tests and local runs:

go
// Package flags evaluates the orders service's feature flags through the
// OpenFeature API, so the code never imports a vendor SDK directly: the
// provider (flagd, LaunchDarkly, Unleash, Flagsmith, or the in-memory one in
// tests) is chosen once at start-up.
//
// Two kinds of flag are used, and they need opposite defaults:
//
//   - a release flag ("new-checkout") hides unfinished code; when the flag
//     system is unreachable the safe answer is the OLD path, so the default is false;
//   - a kill switch ("recommendations") keeps a working but expensive feature
//     on; when the flag system is unreachable the feature should keep working,
//     so the default is true, and operators flip it to false in an incident.
package flags

import (
	"context"
	"hash/fnv"
	"strconv"

	"github.com/open-feature/go-sdk/openfeature"
	"github.com/open-feature/go-sdk/openfeature/memprovider"
)

// Flag keys used by the service. Keep them in one place so flag debt is greppable.
const (
	NewCheckout     = "new-checkout"    // release flag, remove after 100 % + one release
	Recommendations = "recommendations" // kill switch, permanent
)

// Buckets is the size of the hash space used for percentage rollouts.
// 100,000 buckets give 0.001 % resolution (LaunchDarkly documents the same count).
const Buckets = 100_000

// Bucket maps (flag key, targeting key) to a stable number in [0, Buckets).
// Hashing the flag key together with the user means a user who is in the first
// 10 % of one flag is not automatically in the first 10 % of every other flag
// (Unleash does the same with its groupId, which defaults to the flag name).
func Bucket(flagKey, targetingKey string) int {
	h := fnv.New32a()
	_, _ = h.Write([]byte(flagKey))
	_, _ = h.Write([]byte{0}) // separator: "ab"+"c" must differ from "a"+"bc"
	_, _ = h.Write([]byte(targetingKey))
	return int(h.Sum32() % Buckets)
}

// Rollout describes a release flag's targeting: rules first, then a percentage.
type Rollout struct {
	// Percent of targeting keys (0-100) that get the "on" variant.
	Percent float64
	// AllowPlans always get "on" (a targeting rule on the "plan" attribute).
	AllowPlans []string
	// DenyCountries never get "on" (for example, legal review still pending).
	DenyCountries []string
}

// Evaluator returns an in-memory ContextEvaluator implementing r. Real providers
// evaluate equivalent rules on their side; this one exists so that tests and
// local runs exercise the same targeting semantics without a network.
func (r Rollout) Evaluator(flagKey string) memprovider.ContextEvaluator {
	fn := func(_ memprovider.InMemoryFlag, fc openfeature.FlattenedContext) (any, openfeature.ProviderResolutionDetail) {
		country, _ := fc["country"].(string)
		for _, c := range r.DenyCountries {
			if c == country {
				return false, openfeature.ProviderResolutionDetail{Reason: openfeature.TargetingMatchReason, Variant: "off"}
			}
		}
		plan, _ := fc["plan"].(string)
		for _, p := range r.AllowPlans {
			if p == plan {
				return true, openfeature.ProviderResolutionDetail{Reason: openfeature.TargetingMatchReason, Variant: "on"}
			}
		}
		key, _ := fc[openfeature.TargetingKey].(string)
		if key == "" {
			// No stable identity: a percentage rollout would flip per request.
			return false, openfeature.ProviderResolutionDetail{
				Reason:          openfeature.ErrorReason,
				ResolutionError: openfeature.NewTargetingKeyMissingResolutionError("percentage rollout needs a targeting key"),
			}
		}
		on := float64(Bucket(flagKey, key)) < r.Percent/100*Buckets
		v := "off"
		if on {
			v = "on"
		}
		return on, openfeature.ProviderResolutionDetail{Reason: openfeature.SplitReason, Variant: v}
	}
	return &fn
}

// User is what the HTTP layer knows about the caller.
type User struct {
	ID      string
	Plan    string
	Country string
}

// Service wraps one OpenFeature client. It is safe for concurrent use.
type Service struct {
	client *openfeature.Client
}

// New returns a Service bound to the provider registered for domain
// (openfeature.SetNamedProviderAndWait). Creating a client never fails: per the
// specification, client creation "MUST NOT throw".
func New(domain string) *Service {
	return &Service{client: openfeature.NewClient(domain)}
}

func evalContext(u User) openfeature.EvaluationContext {
	return openfeature.NewEvaluationContext(u.ID, map[string]any{
		"plan":    u.Plan,
		"country": u.Country,
	})
}

// NewCheckout reports whether u gets the new checkout. On any provider error
// (not ready, flag missing, timeout) OpenFeature returns the default, false.
func (s *Service) NewCheckout(ctx context.Context, u User) bool {
	return s.client.Boolean(ctx, NewCheckout, false, evalContext(u))
}

// NewCheckoutDetails is the same evaluation with the reason and error code,
// for logs and the /debug/flags endpoint.
func (s *Service) NewCheckoutDetails(ctx context.Context, u User) openfeature.BooleanEvaluationDetails {
	d, _ := s.client.BooleanValueDetails(ctx, NewCheckout, false, evalContext(u))
	return d
}

// RecommendationsOn is the kill switch. Default true: if the flag system is down,
// keep the feature; operators turn it off by setting the flag to false.
func (s *Service) RecommendationsOn(ctx context.Context) bool {
	return s.client.Boolean(ctx, Recommendations, true, openfeature.NewTargetlessEvaluationContext(nil))
}

// Describe renders an evaluation for a log line: flag=new-checkout value=true reason=SPLIT variant=on.
func Describe(flag string, d openfeature.BooleanEvaluationDetails) string {
	s := "flag=" + flag + " value=" + strconv.FormatBool(d.Value) + " reason=" + string(d.Reason)
	if d.Variant != "" {
		s += " variant=" + d.Variant
	}
	if d.ErrorCode != "" {
		s += " error=" + string(d.ErrorCode)
	}
	return s
}
go
package flags

import (
	"context"
	"fmt"
	"strings"
	"testing"

	"github.com/open-feature/go-sdk/openfeature"
	"github.com/open-feature/go-sdk/openfeature/memprovider"
)

// register installs an in-memory provider under a test-specific domain, so
// tests do not share the global default provider.
func register(t *testing.T, flags map[string]memprovider.InMemoryFlag) *Service {
	t.Helper()
	domain := t.Name()
	if err := openfeature.SetNamedProviderAndWait(domain, memprovider.NewInMemoryProvider(flags)); err != nil {
		t.Fatalf("set provider: %v", err)
	}
	return New(domain)
}

func boolFlag(key string, on bool) memprovider.InMemoryFlag {
	v := "off"
	if on {
		v = "on"
	}
	return memprovider.InMemoryFlag{
		Key: key, State: memprovider.Enabled, DefaultVariant: v,
		Variants: map[string]any{"on": true, "off": false},
	}
}

func rolloutFlag(key string, r Rollout) memprovider.InMemoryFlag {
	f := boolFlag(key, false)
	f.ContextEvaluator = r.Evaluator(key)
	return f
}

func TestMissingFlagFallsBackToDefaults(t *testing.T) {
	s := register(t, map[string]memprovider.InMemoryFlag{})
	ctx := context.Background()
	u := User{ID: "u-1"}
	if s.NewCheckout(ctx, u) {
		t.Fatal("release flag must default to false (old path) when the flag is missing")
	}
	if !s.RecommendationsOn(ctx) {
		t.Fatal("kill switch must default to true (feature stays on) when the flag is missing")
	}
	d := s.NewCheckoutDetails(ctx, u)
	if d.Reason != openfeature.ErrorReason || d.ErrorCode != openfeature.FlagNotFoundCode {
		t.Fatalf("details = %+v, want ERROR / FLAG_NOT_FOUND", d.ResolutionDetail)
	}
	if got := Describe(NewCheckout, d); !strings.Contains(got, "error=FLAG_NOT_FOUND") {
		t.Fatalf("Describe = %q", got)
	}
}

func TestDisabledFlagReturnsDefault(t *testing.T) {
	f := boolFlag(NewCheckout, true)
	f.State = memprovider.Disabled
	s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: f})
	if s.NewCheckout(context.Background(), User{ID: "u-1"}) {
		t.Fatal("a disabled flag must evaluate to the caller's default")
	}
}

func TestTargetingRulesBeforePercentage(t *testing.T) {
	r := Rollout{Percent: 0, AllowPlans: []string{"internal"}, DenyCountries: []string{"DE"}}
	s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: rolloutFlag(NewCheckout, r)})
	ctx := context.Background()
	cases := []struct {
		u    User
		want bool
	}{
		{User{ID: "staff-1", Plan: "internal", Country: "NL"}, true},  // allow rule
		{User{ID: "staff-2", Plan: "internal", Country: "DE"}, false}, // deny rule wins
		{User{ID: "cust-1", Plan: "pro", Country: "NL"}, false},       // 0 % rollout
	}
	for _, c := range cases {
		if got := s.NewCheckout(ctx, c.u); got != c.want {
			t.Errorf("%+v: got %v, want %v", c.u, got, c.want)
		}
	}
	if d := s.NewCheckoutDetails(ctx, cases[0].u); d.Reason != openfeature.TargetingMatchReason {
		t.Errorf("reason = %s, want TARGETING_MATCH", d.Reason)
	}
}

func TestPercentageRolloutIsStickyAndMonotonic(t *testing.T) {
	ctx := context.Background()
	const users = 20_000
	on := func(percent float64) map[string]bool {
		s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: rolloutFlag(NewCheckout, Rollout{Percent: percent})})
		m := make(map[string]bool, users)
		for i := range users {
			id := fmt.Sprintf("user-%d", i)
			if s.NewCheckout(ctx, User{ID: id}) {
				m[id] = true
			}
		}
		return m
	}
	ten := on(10)
	if n := len(ten); n < users*9/100 || n > users*11/100 {
		t.Fatalf("10%% rollout enabled %d of %d users", n, users)
	}
	again := on(10)
	for id := range ten {
		if !again[id] {
			t.Fatalf("%s flipped between two evaluations at the same percentage", id)
		}
	}
	fifty := on(50)
	for id := range ten {
		if !fifty[id] {
			t.Fatalf("%s was in the 10%% cohort but not in the 50%% one: raising a rollout must only add users", id)
		}
	}
	t.Logf("10%%: %d users, 50%%: %d users of %d", len(ten), len(fifty), users)
}

func TestPercentageRolloutNeedsTargetingKey(t *testing.T) {
	s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: rolloutFlag(NewCheckout, Rollout{Percent: 100})})
	d := s.NewCheckoutDetails(context.Background(), User{})
	if d.Value || d.ErrorCode != openfeature.TargetingKeyMissingCode {
		t.Fatalf("got value=%v code=%s, want false / TARGETING_KEY_MISSING", d.Value, d.ErrorCode)
	}
}

func TestKillSwitchFlipsWithoutRestart(t *testing.T) {
	s := register(t, map[string]memprovider.InMemoryFlag{Recommendations: boolFlag(Recommendations, true)})
	ctx := context.Background()
	if !s.RecommendationsOn(ctx) {
		t.Fatal("kill switch should start on")
	}
	// Incident: an operator flips the flag. The same Service (same client) sees it.
	if err := openfeature.SetNamedProviderAndWait(t.Name(), memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{
		Recommendations: boolFlag(Recommendations, false),
	})); err != nil {
		t.Fatal(err)
	}
	if s.RecommendationsOn(ctx) {
		t.Fatal("kill switch did not take effect for the running client")
	}
}

func TestBucketSpreadsAcrossFlags(t *testing.T) {
	same := 0
	for i := range 1000 {
		id := fmt.Sprintf("user-%d", i)
		if (Bucket("flag-a", id) < Buckets/10) == (Bucket("flag-b", id) < Buckets/10) {
			same++
		}
	}
	// Independent 10 % cohorts agree for about 82 % of users (0.9*0.9 + 0.1*0.1);
	// identical cohorts would agree for 100 %.
	if same > 900 {
		t.Fatalf("cohorts of two flags agree for %d/1000 users: buckets are not independent", same)
	}
}

Server: /healthz, /readyz (503 while draining), /version, X-App-Version on every response, and Serve implementing readiness off -> drain delay -> bounded Shutdown:

go
// Package server is the orders API's HTTP side as far as deployments care:
// readiness that turns off before shutdown, a drain delay so load balancers and
// kube-proxy stop sending new connections, a bounded graceful Shutdown, and a
// /version endpoint that post-deploy smoke tests and blue-green scripts read.
package server

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net"
	"net/http"
	"sync/atomic"
	"time"

	"academy/deployment-strategies/flags"
)

// Config holds the timings that must agree with the Pod spec:
// DrainDelay + ShutdownTimeout < terminationGracePeriodSeconds.
type Config struct {
	Version         string
	DrainDelay      time.Duration // keep serving after readiness fails (endpoint propagation)
	ShutdownTimeout time.Duration // bound on in-flight requests after the drain delay
}

// API is the application handler set.
type API struct {
	cfg   Config
	flags *flags.Service
	ready atomic.Bool
	log   *slog.Logger
}

// New returns an API that is not ready until Serve has its listener running.
func New(cfg Config, f *flags.Service, log *slog.Logger) *API {
	return &API{cfg: cfg, flags: f, log: log}
}

// Ready reports the readiness the /readyz probe returns.
func (a *API) Ready() bool { return a.ready.Load() }

// Handler wires the routes (Go 1.22+ method patterns).
func (a *API) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK) // liveness: the process works; never tied to dependencies
	})
	mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
		if !a.ready.Load() {
			http.Error(w, "draining", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})
	mux.HandleFunc("GET /version", func(w http.ResponseWriter, _ *http.Request) {
		writeJSON(w, map[string]string{"version": a.cfg.Version})
	})
	mux.HandleFunc("POST /checkout", a.checkout)
	return a.withVersion(mux)
}

// withVersion stamps every response, so a canary analysis or a curl loop can
// count which version answered.
func (a *API) withVersion(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-App-Version", a.cfg.Version)
		next.ServeHTTP(w, r)
	})
}

func (a *API) checkout(w http.ResponseWriter, r *http.Request) {
	u := flags.User{ID: r.Header.Get("X-User-ID"), Plan: r.Header.Get("X-Plan"), Country: r.Header.Get("X-Country")}
	flow := "v1"
	if a.flags.NewCheckout(r.Context(), u) {
		flow = "v2" // new code path, shipped dark until the flag turns on
	}
	resp := map[string]any{"flow": flow}
	if a.flags.RecommendationsOn(r.Context()) {
		resp["recommendations"] = []string{"sku-42"} // the expensive call the kill switch can stop
	}
	writeJSON(w, resp)
}

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(v)
}

// Serve runs h on ln until ctx is cancelled (SIGTERM in main), then:
//  1. readiness -> 503, so the endpoint is removed from Services and LB target groups;
//  2. keep serving for DrainDelay (requests already routed here still succeed);
//  3. srv.Shutdown: close listeners, wait for in-flight requests up to ShutdownTimeout.
//
// With a preStop sleep in the Pod spec, step 2 can be 0: Kubernetes waits before SIGTERM.
func Serve(ctx context.Context, ln net.Listener, a *API, h http.Handler) error {
	srv := &http.Server{Handler: h, ReadHeaderTimeout: 5 * time.Second}
	errc := make(chan error, 1)
	go func() { errc <- srv.Serve(ln) }()
	a.ready.Store(true)
	a.log.Info("serving", "addr", ln.Addr().String(), "version", a.cfg.Version)

	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	a.ready.Store(false)
	a.log.Info("draining", "delay", a.cfg.DrainDelay)
	time.Sleep(a.cfg.DrainDelay)

	sctx, cancel := context.WithTimeout(context.Background(), a.cfg.ShutdownTimeout)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		return err // context.DeadlineExceeded: requests were still running
	}
	if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	a.log.Info("stopped")
	return nil
}
go
package server

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"log/slog"
	"net"
	"net/http"
	"strings"
	"testing"
	"time"

	"academy/deployment-strategies/flags"

	"github.com/open-feature/go-sdk/openfeature"
	"github.com/open-feature/go-sdk/openfeature/memprovider"
)

func newAPI(t *testing.T, cfg Config, fl map[string]memprovider.InMemoryFlag) *API {
	t.Helper()
	if err := openfeature.SetNamedProviderAndWait(t.Name(), memprovider.NewInMemoryProvider(fl)); err != nil {
		t.Fatal(err)
	}
	return New(cfg, flags.New(t.Name()), slog.New(slog.NewTextHandler(io.Discard, nil)))
}

func listen(t *testing.T) net.Listener {
	t.Helper()
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	return ln
}

// probe uses one connection per request. With keep-alive, Go's Transport may
// dial a spare connection that never carries a request; Server.Shutdown waits
// for such StateNew connections until they are 5 s old (net/http, issue 22682),
// which would make a short ShutdownTimeout expire in this test.
var probe = &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}

func status(t *testing.T, url string) int {
	t.Helper()
	resp, err := probe.Get(url)
	if err != nil {
		t.Fatalf("GET %s: %v", url, err)
	}
	_ = resp.Body.Close()
	return resp.StatusCode
}

func waitReady(t *testing.T, base string) {
	t.Helper()
	for range 100 {
		if resp, err := probe.Get(base + "/readyz"); err == nil {
			_ = resp.Body.Close()
			if resp.StatusCode == http.StatusOK {
				return
			}
		}
		time.Sleep(10 * time.Millisecond)
	}
	t.Fatal("server never became ready")
}

func TestCheckoutFollowsFlagsAndStampsVersion(t *testing.T) {
	on := memprovider.InMemoryFlag{Key: flags.NewCheckout, State: memprovider.Enabled, DefaultVariant: "on",
		Variants: map[string]any{"on": true, "off": false}}
	killed := memprovider.InMemoryFlag{Key: flags.Recommendations, State: memprovider.Enabled, DefaultVariant: "off",
		Variants: map[string]any{"on": true, "off": false}}
	a := newAPI(t, Config{Version: "1.5.0"}, map[string]memprovider.InMemoryFlag{flags.NewCheckout: on, flags.Recommendations: killed})
	ln := listen(t)
	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan error, 1)
	go func() { done <- Serve(ctx, ln, a, a.Handler()) }()
	base := "http://" + ln.Addr().String()
	waitReady(t, base)

	req, _ := http.NewRequest(http.MethodPost, base+"/checkout", strings.NewReader("{}"))
	req.Header.Set("X-User-ID", "u-7")
	resp, err := probe.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	var body map[string]any
	_ = json.NewDecoder(resp.Body).Decode(&body)
	_ = resp.Body.Close()
	if body["flow"] != "v2" {
		t.Errorf("flow = %v, want v2 (release flag on)", body["flow"])
	}
	if _, ok := body["recommendations"]; ok {
		t.Error("recommendations present although the kill switch is off")
	}
	if v := resp.Header.Get("X-App-Version"); v != "1.5.0" {
		t.Errorf("X-App-Version = %q", v)
	}
	cancel()
	if err := <-done; err != nil {
		t.Fatalf("Serve: %v", err)
	}
}

// The drain sequence a rolling update, a blue-green switch or a canary abort relies on.
func TestDrainFailsReadinessThenFinishesInFlight(t *testing.T) {
	a := newAPI(t, Config{Version: "1.4.2", DrainDelay: 300 * time.Millisecond, ShutdownTimeout: 2 * time.Second}, nil)
	slowStarted := make(chan struct{})
	mux := http.NewServeMux()
	mux.Handle("/", a.Handler())
	mux.HandleFunc("GET /slow", func(w http.ResponseWriter, _ *http.Request) {
		close(slowStarted)
		time.Sleep(500 * time.Millisecond) // longer than DrainDelay: finishes during Shutdown
		w.WriteHeader(http.StatusOK)
	})
	ln := listen(t)
	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan error, 1)
	go func() { done <- Serve(ctx, ln, a, mux) }()
	base := "http://" + ln.Addr().String()
	waitReady(t, base)

	slow := make(chan int, 1)
	go func() {
		resp, err := probe.Get(base + "/slow")
		if err != nil {
			slow <- -1
			return
		}
		_ = resp.Body.Close()
		slow <- resp.StatusCode
	}()
	<-slowStarted
	cancel() // SIGTERM

	time.Sleep(50 * time.Millisecond)
	if a.Ready() {
		t.Fatal("still ready after SIGTERM")
	}
	// During the drain delay the server still answers: readiness 503, work 200.
	if got := status(t, base+"/readyz"); got != http.StatusServiceUnavailable {
		t.Fatalf("/readyz during drain = %d, want 503", got)
	}
	if got := status(t, base+"/version"); got != http.StatusOK {
		t.Fatalf("/version during drain = %d, want 200 (late-routed requests must still succeed)", got)
	}
	if got := <-slow; got != http.StatusOK {
		t.Fatalf("in-flight request got %d, want 200", got)
	}
	if err := <-done; err != nil {
		t.Fatalf("Serve returned %v", err)
	}
	if _, err := probe.Get(base + "/healthz"); err == nil {
		t.Fatal("listener still open after Shutdown")
	}
}

func TestShutdownTimeoutReportsStuckRequests(t *testing.T) {
	a := newAPI(t, Config{Version: "1.4.2", DrainDelay: 0, ShutdownTimeout: 100 * time.Millisecond}, nil)
	started := make(chan struct{})
	release := make(chan struct{})
	mux := http.NewServeMux()
	mux.HandleFunc("GET /stuck", func(w http.ResponseWriter, _ *http.Request) {
		close(started)
		<-release
	})
	ln := listen(t)
	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan error, 1)
	go func() { done <- Serve(ctx, ln, a, mux) }()
	go func() {
		if resp, err := probe.Get("http://" + ln.Addr().String() + "/stuck"); err == nil {
			_ = resp.Body.Close()
		}
	}()
	<-started
	cancel()
	err := <-done
	close(release)
	if !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("Serve = %v, want context.DeadlineExceeded", err)
	}
}

Post-deploy verification used by pipelines and the blue-green script's checks (Check for one release, VersionMix to confirm a weight took effect):

go
// Package smoke is the post-deploy verification the pipeline runs against a
// new release before (blue-green preview) and after (canary, rolling) it takes
// traffic: is it ready, is it the version we meant to ship, and which versions
// are answering behind the shared hostname.
package smoke

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
)

// Check fails unless base answers /readyz with 200 and /version with want.
func Check(ctx context.Context, c *http.Client, base, want string) error {
	var errs []error
	if code, err := get(ctx, c, base+"/readyz", nil); err != nil {
		errs = append(errs, err)
	} else if code != http.StatusOK {
		errs = append(errs, fmt.Errorf("readyz: status %d", code))
	}
	var v struct {
		Version string `json:"version"`
	}
	if code, err := get(ctx, c, base+"/version", &v); err != nil {
		errs = append(errs, err)
	} else if code != http.StatusOK || v.Version != want {
		errs = append(errs, fmt.Errorf("version: status %d, got %q, want %q", code, v.Version, want))
	}
	return errors.Join(errs...)
}

// VersionMix sends n requests and counts the X-App-Version header, which shows
// whether a weight change (canary 10 %, blue-green 0/100) really took effect.
func VersionMix(ctx context.Context, c *http.Client, url string, n int) (map[string]int, error) {
	mix := map[string]int{}
	for range n {
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
		if err != nil {
			return nil, err
		}
		resp, err := c.Do(req)
		if err != nil {
			return mix, err
		}
		_ = resp.Body.Close()
		mix[resp.Header.Get("X-App-Version")]++
	}
	return mix, nil
}

func get(ctx context.Context, c *http.Client, url string, into any) (int, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return 0, err
	}
	resp, err := c.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	if into != nil && resp.StatusCode == http.StatusOK {
		if err := json.NewDecoder(resp.Body).Decode(into); err != nil {
			return resp.StatusCode, fmt.Errorf("%s: %w", url, err)
		}
	}
	return resp.StatusCode, nil
}
go
package smoke

import (
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync/atomic"
	"testing"
)

func fake(version string, ready bool) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-App-Version", version)
		switch r.URL.Path {
		case "/readyz":
			if !ready {
				w.WriteHeader(http.StatusServiceUnavailable)
			}
		case "/version":
			_, _ = w.Write([]byte(`{"version":"` + version + `"}`))
		}
	}))
}

func TestCheck(t *testing.T) {
	ctx := context.Background()
	good := fake("1.5.0", true)
	defer good.Close()
	if err := Check(ctx, good.Client(), good.URL, "1.5.0"); err != nil {
		t.Fatalf("healthy release failed: %v", err)
	}
	if err := Check(ctx, good.Client(), good.URL, "1.6.0"); err == nil || !strings.Contains(err.Error(), `want "1.6.0"`) {
		t.Fatalf("wrong version not reported: %v", err)
	}
	notReady := fake("1.5.0", false)
	defer notReady.Close()
	if err := Check(ctx, notReady.Client(), notReady.URL, "1.5.0"); err == nil || !strings.Contains(err.Error(), "readyz: status 503") {
		t.Fatalf("unready release not reported: %v", err)
	}
}

func TestVersionMix(t *testing.T) {
	// A stand-in for a weighted route: every 10th request goes to the canary.
	var n atomic.Int64
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		v := "1.4.2"
		if n.Add(1)%10 == 0 {
			v = "1.5.0"
		}
		w.Header().Set("X-App-Version", v)
	}))
	defer srv.Close()
	mix, err := VersionMix(context.Background(), srv.Client(), srv.URL, 200)
	if err != nil {
		t.Fatal(err)
	}
	if mix["1.5.0"] != 20 || mix["1.4.2"] != 180 {
		t.Fatalf("mix = %v, want 180/20", mix)
	}
}
go
// Command orders-api wires flags, server and signals. Version is stamped at
// build time: go build -ldflags "-X main.version=1.5.0".
package main

import (
	"context"
	"log/slog"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"

	"academy/deployment-strategies/flags"
	"academy/deployment-strategies/server"

	"github.com/open-feature/go-sdk/openfeature"
	"github.com/open-feature/go-sdk/openfeature/memprovider"
)

var version = "dev"

func main() {
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	// Production registers a networked provider (flagd, LaunchDarkly, Unleash,
	// Flagsmith) here. The in-memory provider keeps this example self-contained:
	// new-checkout off, recommendations on.
	if err := openfeature.SetNamedProviderAndWait("orders", memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{
		flags.NewCheckout: {Key: flags.NewCheckout, State: memprovider.Enabled, DefaultVariant: "off",
			Variants:         map[string]any{"on": true, "off": false},
			ContextEvaluator: flags.Rollout{Percent: 5, AllowPlans: []string{"internal"}}.Evaluator(flags.NewCheckout)},
		flags.Recommendations: {Key: flags.Recommendations, State: memprovider.Enabled, DefaultVariant: "on",
			Variants: map[string]any{"on": true, "off": false}},
	})); err != nil {
		log.Error("flag provider", "err", err)
		os.Exit(1)
	}
	defer openfeature.Shutdown()

	addr := ":" + envOr("PORT", "8080")
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		log.Error("listen", "err", err)
		os.Exit(1)
	}
	// Pod spec: preStop sleep 5s, terminationGracePeriodSeconds 30.
	// Budget: 5 (preStop) + 5 (DrainDelay) + 15 (ShutdownTimeout) = 25 < 30.
	api := server.New(server.Config{Version: version, DrainDelay: 5 * time.Second, ShutdownTimeout: 15 * time.Second},
		flags.New("orders"), log)
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()
	if err := server.Serve(ctx, ln, api, api.Handler()); err != nil {
		log.Error("serve", "err", err)
		os.Exit(1)
	}
}

func envOr(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}
text
module academy/deployment-strategies

go 1.24.0

require github.com/open-feature/go-sdk v1.17.1

require (
	github.com/go-logr/logr v1.4.3 // indirect
	go.uber.org/mock v0.6.0 // indirect
)

The Rollout, its Services and HTTPRoute (Gateway API plugin, background plus inline analysis, digest-pinned image, readiness, preStop sleep):

yaml
# Argo Rollouts canary for the Go orders API, traffic split by the Gateway API
# plugin (argoproj-labs/gatewayAPI) on an HTTPRoute. The controller rewrites
# the backendRefs weights below; Git keeps 100/0 so Argo CD must ignore them
# (spec.ignoreDifferences on the HTTPRoute, see the chapter).
# Validated offline against the Rollout CRD schema (check-manifests.rb); not applied.
apiVersion: v1
kind: Service
metadata:
  name: orders-api-stable
  namespace: shop
spec:
  selector:
    app: orders-api            # the controller adds rollouts-pod-template-hash
  ports:
    - name: http
      port: 80
      targetPort: http
---
apiVersion: v1
kind: Service
metadata:
  name: orders-api-canary
  namespace: shop
spec:
  selector:
    app: orders-api
  ports:
    - name: http
      port: 80
      targetPort: http
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: orders-api
  namespace: shop
spec:
  parentRefs:
    - name: public
      namespace: gateway
  hostnames:
    - api.shop.example
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /
      backendRefs:
        - name: orders-api-stable
          port: 80
          weight: 100
        - name: orders-api-canary
          port: 80
          weight: 0
---
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: orders-api
  namespace: shop
spec:
  replicas: 10
  revisionHistoryLimit: 5           # old ReplicaSets kept for `kubectl argo rollouts undo`
  selector:
    matchLabels:
      app: orders-api
  template:
    metadata:
      labels:
        app: orders-api
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: orders-api
          # Deploy by digest; CI writes it into Git. The tag is for humans only.
          image: ghcr.io/acme/orders-api:1.5.0@sha256:0000000000000000000000000000000000000000000000000000000000000000
          ports:
            - name: http
              containerPort: 8080
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
            periodSeconds: 2
            failureThreshold: 1
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
            periodSeconds: 10
          lifecycle:
            preStop:
              sleep:
                seconds: 5          # endpoint removal propagates before SIGTERM (Kubernetes 1.34+ GA)
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
  strategy:
    canary:
      canaryService: orders-api-canary
      stableService: orders-api-stable
      maxSurge: "25%"
      maxUnavailable: 0
      abortScaleDownDelaySeconds: 30
      trafficRouting:
        plugins:
          argoproj-labs/gatewayAPI:
            httpRoute: orders-api
            namespace: shop
      # Background analysis: runs from step 2 until the rollout ends (its
      # templates have no count); exceeding failureLimit on either metric
      # abort the rollout and send all traffic to stable.
      analysis:
        startingStep: 2
        templates:
          - templateName: http-success-rate
          - templateName: http-latency-p99
        args:
          - name: service
            value: orders-api-canary
      steps:
        - setWeight: 5
        - pause: {duration: 2m}
        - setWeight: 20
        - pause: {duration: 5m}
        # Inline analysis: blocks here until the five-measurement gate completes.
        # The background analysis above keeps running through the 50 % stage.
        - analysis:
            templates:
              - templateName: http-success-rate-gate
            args:
              - name: service
                value: orders-api-canary
        - setWeight: 50
        - pause: {duration: 10m}
        - setWeight: 100

The AnalysisTemplates: unbounded success rate and p99 for the background run (no count, so the 50 % stage is still guarded), a finite five-measurement success-rate gate for the inline step and post-promotion, and a smoke-test job metric:

yaml
# Prometheus-backed AnalysisTemplates used by both Rollouts in this chapter.
# Metric names assume the Go service exports http_requests_total{service,code}
# and http_request_duration_seconds_bucket{service} (OpenTelemetry or
# promhttp naming); adjust the label names to your instrumentation.
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: http-success-rate
  namespace: shop
spec:
  args:
    - name: service
  metrics:
    - name: success-rate
      interval: 1m            # no count: measures every minute until the rollout ends
      successCondition: len(result) > 0 && result[0] >= 0.995   # no data = failed
      failureLimit: 2         # third failed measurement -> AnalysisRun Failed -> abort
      provider:
        prometheus:
          address: http://prometheus.monitoring.svc:9090
          query: |
            sum(rate(http_requests_total{service="{{args.service}}",code!~"5.."}[2m]))
            /
            sum(rate(http_requests_total{service="{{args.service}}"}[2m]))
---
# Finite gate for inline steps and post-promotion checks: five measurements,
# one per minute, then the run completes (Successful or Failed). A background
# analysis must NOT use a finite count, or the later stages run unguarded.
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: http-success-rate-gate
  namespace: shop
spec:
  args:
    - name: service
  metrics:
    - name: success-rate
      interval: 1m
      count: 5
      successCondition: len(result) > 0 && result[0] >= 0.995
      failureLimit: 2
      provider:
        prometheus:
          address: http://prometheus.monitoring.svc:9090
          query: |
            sum(rate(http_requests_total{service="{{args.service}}",code!~"5.."}[2m]))
            /
            sum(rate(http_requests_total{service="{{args.service}}"}[2m]))
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: http-latency-p99
  namespace: shop
spec:
  args:
    - name: service
  metrics:
    - name: latency-p99
      interval: 1m
      successCondition: len(result) > 0 && result[0] <= 0.300    # seconds; no data = failed
      failureLimit: 3
      provider:
        prometheus:
          address: http://prometheus.monitoring.svc:9090
          query: |
            histogram_quantile(0.99,
              sum by (le) (rate(http_request_duration_seconds_bucket{service="{{args.service}}"}[2m])))
---
# Smoke test as a metric: a Kubernetes Job that runs the Go smoke checker
# against the preview Service. Exit 0 = Successful, non-zero = Failed.
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: smoke-test
  namespace: shop
spec:
  args:
    - name: base-url
    - name: version
  metrics:
    - name: smoke
      provider:
        job:
          spec:
            backoffLimit: 0
            template:
              spec:
                restartPolicy: Never
                containers:
                  - name: smoke
                    image: ghcr.io/acme/orders-smoke:1.0.0
                    args: ["--base", "{{args.base-url}}", "--version", "{{args.version}}"]

The same service as an Argo Rollouts blue-green (preview Service, pre-promotion smoke test, manual promotion, post-promotion analysis):

yaml
# Argo Rollouts blue-green for the same service: the controller switches the
# active Service's selector (rollouts-pod-template-hash) after the smoke test
# on the preview Service passes and a human promotes.
apiVersion: v1
kind: Service
metadata:
  name: orders-api-active
  namespace: shop
spec:
  selector:
    app: orders-api-bg
  ports:
    - name: http
      port: 80
      targetPort: http
---
apiVersion: v1
kind: Service
metadata:
  name: orders-api-preview
  namespace: shop
spec:
  selector:
    app: orders-api-bg
  ports:
    - name: http
      port: 80
      targetPort: http
---
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: orders-api-bg
  namespace: shop
spec:
  replicas: 6
  revisionHistoryLimit: 3
  selector:
    matchLabels:
      app: orders-api-bg
  template:
    metadata:
      labels:
        app: orders-api-bg
    spec:
      containers:
        - name: orders-api
          image: ghcr.io/acme/orders-api:1.5.0@sha256:0000000000000000000000000000000000000000000000000000000000000000
          ports:
            - name: http
              containerPort: 8080
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
  strategy:
    blueGreen:
      activeService: orders-api-active
      previewService: orders-api-preview
      previewReplicaCount: 2          # small green stack while it is tested
      autoPromotionEnabled: false     # a human (or the pipeline) runs `promote`
      scaleDownDelaySeconds: 60       # keep blue for iptables propagation and fast rollback
      prePromotionAnalysis:
        templates:
          - templateName: smoke-test
        args:
          - name: base-url
            value: http://orders-api-preview.shop.svc
          - name: version
            value: "1.5.0"
      postPromotionAnalysis:
        templates:
          - templateName: http-success-rate-gate   # finite: must complete to finish the update
        args:
          - name: service
            value: orders-api-active

Plain-Kubernetes blue-green without a controller, and the switch script with its checks and rollback:

yaml
# Plain-Kubernetes blue-green: two complete Deployments, one Service whose
# selector names the live slot, one preview Service for the idle slot.
# The switch is a single selector patch (scripts/blue-green-switch.sh);
# rollback is the same patch with the old slot.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api-blue
  namespace: shop
  labels:
    app: orders-api
    slot: blue
spec:
  replicas: 4
  selector:
    matchLabels:
      app: orders-api
      slot: blue
  template:
    metadata:
      labels:
        app: orders-api
        slot: blue
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: orders-api
          image: ghcr.io/acme/orders-api:1.4.2@sha256:1111111111111111111111111111111111111111111111111111111111111111
          ports:
            - name: http
              containerPort: 8080
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
            periodSeconds: 2
          lifecycle:
            preStop:
              sleep:
                seconds: 5
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api-green
  namespace: shop
  labels:
    app: orders-api
    slot: green
spec:
  replicas: 4
  selector:
    matchLabels:
      app: orders-api
      slot: green
  template:
    metadata:
      labels:
        app: orders-api
        slot: green
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: orders-api
          image: ghcr.io/acme/orders-api:1.5.0@sha256:0000000000000000000000000000000000000000000000000000000000000000
          ports:
            - name: http
              containerPort: 8080
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
            periodSeconds: 2
          lifecycle:
            preStop:
              sleep:
                seconds: 5
---
# Live traffic: whatever slot this selector names.
apiVersion: v1
kind: Service
metadata:
  name: orders-api
  namespace: shop
  annotations:
    deploy.acme.io/previous-slot: green
spec:
  selector:
    app: orders-api
    slot: blue
  ports:
    - name: http
      port: 80
      targetPort: http
---
# Smoke tests and internal testers reach the idle slot here.
apiVersion: v1
kind: Service
metadata:
  name: orders-api-preview
  namespace: shop
spec:
  selector:
    app: orders-api
    slot: green
  ports:
    - name: http
      port: 80
      targetPort: http
bash
#!/usr/bin/env bash
# blue-green-switch.sh: move live traffic of a Kubernetes Service from one slot
# (Deployment <app>-blue / <app>-green) to the other by patching the Service
# selector, with checks before and a verified rollback after.
#
#   blue-green-switch.sh [--dry-run] [-n NAMESPACE] APP TARGET_SLOT EXPECTED_VERSION
#
# Environment:
#   PREVIEW_URL  base URL that reaches <APP>-preview (in-cluster DNS or a port-forward)
#   LIVE_URL     base URL that reaches <APP> through the real path (Gateway, LB)
#   VERIFY_N     requests sent after the switch to confirm the new version (default 20)
#   VERIFY_GRACE leading requests allowed to see the old slot while routing converges (default 5)
# Exit codes: 0 switched or already live, 2 usage, 3 target not ready,
#             4 smoke test failed (nothing switched), 5 verification failed (rolled back).
set -euo pipefail

NS=default
DRY_RUN=0
VERIFY_N=${VERIFY_N:-20}

usage() { echo "usage: ${0##*/} [--dry-run] [-n NAMESPACE] APP TARGET_SLOT EXPECTED_VERSION" >&2; exit 2; }
log()   { printf '%s switch: %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
run()   { if [ "$DRY_RUN" = 1 ]; then { printf 'DRY-RUN:'; printf ' %q' "$@"; printf '\n'; } >&2; else "$@"; fi; }

while [ "$#" -gt 0 ]; do
  case $1 in
    --dry-run) DRY_RUN=1; shift ;;
    -n) NS=${2:?}; shift 2 ;;
    -h|--help) usage ;;
    -*) echo "unknown option: $1" >&2; usage ;;
    *) break ;;
  esac
done
[ "$#" -eq 3 ] || usage
APP=$1 TARGET=$2 VERSION=$3
case $TARGET in blue|green) ;; *) echo "slot must be blue or green" >&2; exit 2 ;; esac
: "${PREVIEW_URL:?set PREVIEW_URL}" "${LIVE_URL:?set LIVE_URL}"

k() { kubectl -n "$NS" "$@"; }
version_at() { curl --fail --silent --show-error --max-time 3 "$1/version" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'; }
selector_patch() { printf '{"metadata":{"annotations":{"deploy.acme.io/previous-slot":"%s"}},"spec":{"selector":{"app":"%s","slot":"%s"}}}' "$2" "$APP" "$1"; }

# 1. Where is live traffic now? Idempotent: nothing to do if TARGET is already live.
CURRENT=$(k get service "$APP" -o jsonpath='{.spec.selector.slot}')
if [ "$CURRENT" = "$TARGET" ]; then
  log "$APP already serves slot $TARGET; nothing to do"
  exit 0
fi
log "live slot: $CURRENT, target: $TARGET, expected version: $VERSION"

# 2. The target Deployment must be fully rolled out (all replicas Ready).
if ! k rollout status "deployment/$APP-$TARGET" --timeout=180s >&2; then
  log "deployment $APP-$TARGET is not ready; aborting before any switch"; exit 3
fi

# 3. Point the preview Service at the target slot and smoke-test it.
run kubectl -n "$NS" patch service "$APP-preview" --type=merge -p "$(printf '{"spec":{"selector":{"app":"%s","slot":"%s"}}}' "$APP" "$TARGET")" >&2
if [ "$DRY_RUN" = 0 ]; then
  got=""
  for _ in 1 2 3 4 5; do got=$(version_at "$PREVIEW_URL" || true); [ "$got" = "$VERSION" ] && break; sleep 1; done
  if [ "$got" != "$VERSION" ]; then log "smoke test: preview answers '${got:-nothing}', want $VERSION; not switching"; exit 4; fi
  log "smoke test passed on preview ($got)"
fi

# 4. The switch: one PATCH of the live Service's selector. Endpoints follow within seconds.
run kubectl -n "$NS" patch service "$APP" --type=merge -p "$(selector_patch "$TARGET" "$CURRENT")" >&2
[ "$DRY_RUN" = 1 ] && { log "DRY-RUN: would verify $VERIFY_N requests on $LIVE_URL"; exit 0; }

# 5. Verify through the real path; roll back to the previous slot on failure.
#    The first GRACE requests may still see the old slot while kube-proxy and the LB
#    converge; after that any mismatch rolls back. Whatever VERIFY_N is, the LAST
#    answer must be the new version, so a short or fully failing check cannot pass.
GRACE=${VERIFY_GRACE:-5}
rollback() {
  log "$1; rolling back to $CURRENT"
  k patch service "$APP" --type=merge -p "$(selector_patch "$CURRENT" "$TARGET")" >&2
  exit 5
}
ok=0 got=""
for i in $(seq 1 "$VERIFY_N"); do
  got=$(version_at "$LIVE_URL" || true)
  if [ "$got" = "$VERSION" ]; then ok=$((ok + 1))
  elif [ "$i" -gt "$GRACE" ]; then rollback "request $i answered '${got:-error}'"
  fi
  sleep "${VERIFY_SLEEP:-0.5}"
done
if [ "$ok" -eq 0 ] || [ "$got" != "$VERSION" ]; then
  rollback "verification ended with '${got:-error}' ($ok/$VERIFY_N requests on $VERSION)"
fi
log "switched $APP to $TARGET ($ok/$VERIFY_N requests on $VERSION); $APP-$CURRENT kept for rollback"
bash
#!/usr/bin/env bash
# Runs scripts/blue-green-switch.sh against stub `kubectl` and `curl` programs
# on PATH (no cluster): the stubs keep Service selectors in files and answer
# /version according to which slot a Service points at.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
SCRIPT="$HERE/../scripts/blue-green-switch.sh"
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
mkdir -p "$T/bin" "$T/state"
export STATE="$T/state" PATH="$T/bin:$PATH" PREVIEW_URL=http://preview LIVE_URL=http://live VERIFY_SLEEP=0 VERIFY_N=10

cat > "$T/bin/kubectl" <<'EOF'
#!/usr/bin/env bash
# stub: kubectl -n NS <verb> ...
shift 2
echo "kubectl $*" >> "$STATE/calls"
case $1 in
  get)    cat "$STATE/svc-$3" ;;
  rollout) d=${3#deployment/}; [ "$(cat "$STATE/ready-$d" 2>/dev/null)" = yes ] && echo "deployment \"$d\" successfully rolled out" ;;
  patch)  slot=$(printf '%s' "$6" | sed -n 's/.*"slot":"\([a-z]*\)".*/\1/p'); printf '%s' "$slot" > "$STATE/svc-$3"; echo "service/$3 patched" ;;
esac
EOF
cat > "$T/bin/curl" <<'EOF'
#!/usr/bin/env bash
# stub: last argument is the URL; preview -> orders-api-preview, live -> orders-api
url=${!#}
case $url in http://preview/*) svc=orders-api-preview ;; http://live/*) svc=orders-api ;; esac
slot=$(cat "$STATE/svc-$svc")
if [ "$svc" = orders-api ] && [ -f "$STATE/live-broken-$slot" ]; then echo "curl: (22) 502" >&2; exit 22; fi
printf '{"version":"%s"}\n' "$(cat "$STATE/version-$slot")"
EOF
chmod +x "$T/bin/kubectl" "$T/bin/curl"

reset() {
  rm -f "$STATE"/*
  printf blue  > "$STATE/svc-orders-api"; printf blue > "$STATE/svc-orders-api-preview"
  printf 1.4.2 > "$STATE/version-blue";  printf 1.5.0 > "$STATE/version-green"
  echo yes > "$STATE/ready-orders-api-blue"; echo yes > "$STATE/ready-orders-api-green"
}
pass=0; fail=0
check() { if eval "$2"; then echo "ok   - $1"; pass=$((pass+1)); else echo "FAIL - $1"; fail=$((fail+1)); fi; }

reset
out=$("$SCRIPT" --dry-run -n shop orders-api green 1.5.0 2>&1); rc=$?
check "dry run exits 0 and prints the selector patch" '[ $rc = 0 ] && grep -q "DRY-RUN: kubectl -n shop patch service orders-api" <<<"$out"'
check "dry run leaves live traffic on blue" '[ "$(cat $STATE/svc-orders-api)" = blue ]'

reset
"$SCRIPT" -n shop orders-api green 1.5.0 2>"$T/log"; rc=$?
check "switch to green exits 0" '[ $rc = 0 ]'
check "live Service now selects green" '[ "$(cat $STATE/svc-orders-api)" = green ]'
check "preview was patched before live" '[ "$(grep -n "patch service orders-api-preview" $STATE/calls | cut -d: -f1)" -lt "$(grep -n "patch service orders-api " $STATE/calls | cut -d: -f1)" ]'
sed 's/^[0-9:]* /  log: /' "$T/log"

out=$("$SCRIPT" -n shop orders-api green 1.5.0 2>&1); rc=$?
check "second run is a no-op (idempotent)" '[ $rc = 0 ] && grep -q "already serves slot green" <<<"$out"'

reset; echo no > "$STATE/ready-orders-api-green"
set +e; "$SCRIPT" -n shop orders-api green 1.5.0 2>/dev/null; rc=$?; set -e
check "unready green aborts with 3 and switches nothing" '[ $rc = 3 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'

reset; printf 1.4.9 > "$STATE/version-green"
set +e; "$SCRIPT" -n shop orders-api green 1.5.0 2>/dev/null; rc=$?; set -e
check "wrong version on preview aborts with 4 before the switch" '[ $rc = 4 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'

reset; touch "$STATE/live-broken-green"
set +e; "$SCRIPT" -n shop orders-api green 1.5.0 2>"$T/log"; rc=$?; set -e
check "failing live path after the switch rolls back with 5" '[ $rc = 5 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'
grep -E "rolling back" "$T/log" | sed 's/^[0-9:]* /  log: /'

reset; touch "$STATE/live-broken-green"
set +e; VERIFY_N=3 "$SCRIPT" -n shop orders-api green 1.5.0 2>"$T/log"; rc=$?; set -e
check "VERIFY_N=3 with a failing live path still rolls back with 5" '[ $rc = 5 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'
grep -E "rolling back" "$T/log" | sed 's/^[0-9:]* /  log: /'

echo "$pass passed, $fail failed"
[ "$fail" = 0 ]

Every manifest on this page is checked offline by a schema validator against the Kubernetes OpenAPI v3 documents and the projects' own CRDs (Rollout, AnalysisTemplate, Canary, MetricTemplate, HTTPRoute, VirtualService, DestinationRule), plus cross-object rules (referenced Services, templates and routes exist):

ruby
#!/usr/bin/env ruby
# Offline schema check for the chapter's manifests (no cluster, no kubectl apply):
#  1. every file parses as YAML (multi-document);
#  2. every object is validated against the schema the API server would use:
#     - core kinds (Deployment, Service, Ingress) against Kubernetes' published
#       OpenAPI v3 documents (api/openapi-spec/v3 in kubernetes/kubernetes);
#     - CRDs (Rollout, AnalysisTemplate, Canary, MetricTemplate, HTTPRoute,
#       VirtualService, DestinationRule) against the openAPIV3Schema in the
#       projects' own CRD manifests;
#     checking unknown fields, required fields, basic types and enums;
#  3. a few cross-object rules the schemas cannot express.
# Usage: ruby check-manifests.rb <saved-sources-dir> <manifest files...>
require 'yaml'
require 'json'

src, *files = ARGV
$errors = []
def err(m); $errors << m; end

# ---- schema registry -------------------------------------------------------
SCHEMAS = {}   # "group/version Kind" => [schema, resolver]
OPENAPI = {}   # component name => schema (core)

%w[k8s-openapi-apps-v1 k8s-openapi-core-v1 k8s-openapi-networking-v1].each do |n|
  doc = JSON.parse(File.read(File.join(src, "#{n}.txt")))
  doc['components']['schemas'].each do |name, s|
    OPENAPI[name] = s
    (s['x-kubernetes-group-version-kind'] || []).each do |gvk|
      gv = gvk['group'].to_s.empty? ? gvk['version'] : "#{gvk['group']}/#{gvk['version']}"
      SCHEMAS["#{gv} #{gvk['kind']}"] = s
    end
  end
end

%w[argo-rollouts-crd argo-rollouts-analysis-crd flagger-crd gwapi-httproute-crd istio-crds].each do |n|
  YAML.load_stream(File.read(File.join(src, "#{n}.txt"))).compact.each do |crd|
    next unless crd['kind'] == 'CustomResourceDefinition'
    g = crd['spec']['group']; k = crd['spec']['names']['kind']
    crd['spec']['versions'].each do |v|
      s = v.dig('schema', 'openAPIV3Schema') || crd.dig('spec', 'validation', 'openAPIV3Schema')
      SCHEMAS["#{g}/#{v['name']} #{k}"] = s if s
    end
  end
end

def resolve(s)
  loop do
    if s['$ref']
      s = OPENAPI.fetch(s['$ref'].sub('#/components/schemas/', ''))
    elsif s['allOf'] && s['allOf'].size == 1 && s.keys.all? { |k| %w[allOf default description].include?(k) }
      s = s['allOf'][0]
    else
      return s
    end
  end
end

def type_ok?(v, s)
  return true if s['x-kubernetes-int-or-string'] && (v.is_a?(Integer) || v.is_a?(String))
  case s['type']
  when 'string'  then v.is_a?(String)
  when 'integer' then v.is_a?(Integer)
  when 'number'  then v.is_a?(Numeric)
  when 'boolean' then v == true || v == false
  when 'array'   then v.is_a?(Array)
  when 'object'  then v.is_a?(Hash)
  else true
  end
end

def validate(v, s, path, file, root = false)
  s = resolve(s)
  return if s['x-kubernetes-preserve-unknown-fields'] && !s['properties']
  unless type_ok?(v, s)
    return err("#{file}: #{path}: expected #{s['type'] || 'int-or-string'}, got #{v.class}")
  end
  err("#{file}: #{path}: #{v.inspect} not in #{s['enum']}") if s['enum'] && !s['enum'].include?(v)
  if v.is_a?(Hash)
    props = s['properties'] || {}
    (s['required'] || []).each { |r| err("#{file}: #{path}: missing required '#{r}'") unless v.key?(r) }
    v.each do |k, val|
      next if root && %w[apiVersion kind metadata].include?(k) && !props[k] # Istio CRDs list only spec/status
      if props[k] then validate(val, props[k], "#{path}.#{k}", file)
      elsif s['additionalProperties'].is_a?(Hash) then validate(val, s['additionalProperties'], "#{path}.#{k}", file)
      elsif s['additionalProperties'] == true || s['x-kubernetes-preserve-unknown-fields'] then next
      elsif !props.empty? then err("#{file}: #{path}: unknown field '#{k}'")
      end
    end
  elsif v.is_a?(Array) && s['items']
    v.each_with_index { |x, i| validate(x, s['items'], "#{path}[#{i}]", file) }
  end
end

# ---- validate ----------------------------------------------------------------
objects = []
files.each do |f|
  begin
    docs = YAML.load_stream(File.read(f)).compact
  rescue Psych::SyntaxError => e
    err("#{f}: YAML: #{e.message}"); next
  end
  docs.each do |d|
    key = "#{d['apiVersion']} #{d['kind']}"
    s = SCHEMAS[key]
    if s.nil? then err("#{f}: no schema for #{key}") else validate(d, s, d['kind'], f, true) end
    objects << [f, d]
  end
end

# ---- cross-object rules --------------------------------------------------------
by = ->(kind, name) { objects.map(&:last).find { |o| o['kind'] == kind && o.dig('metadata', 'name') == name } }
objects.each do |f, d|
  case d['kind']
  when 'Rollout'
    sel = d.dig('spec', 'selector', 'matchLabels') || {}
    lab = d.dig('spec', 'template', 'metadata', 'labels') || {}
    err("#{f}: Rollout selector not a subset of template labels") unless sel.all? { |k, v| lab[k] == v }
    c = d.dig('spec', 'strategy', 'canary') || {}
    %w[canaryService stableService].each { |k| err("#{f}: #{k} #{c[k]} not defined") if c[k] && !by.('Service', c[k]) }
    b = d.dig('spec', 'strategy', 'blueGreen') || {}
    %w[activeService previewService].each { |k| err("#{f}: #{k} #{b[k]} not defined") if b[k] && !by.('Service', b[k]) }
    refs = (c.dig('analysis', 'templates') || []) + (c['steps'] || []).flat_map { |st| st.dig('analysis', 'templates') || [] } +
           (b.dig('prePromotionAnalysis', 'templates') || []) + (b.dig('postPromotionAnalysis', 'templates') || [])
    refs.each { |t| err("#{f}: AnalysisTemplate #{t['templateName']} not defined") unless by.('AnalysisTemplate', t['templateName']) }
    route = c.dig('trafficRouting', 'plugins', 'argoproj-labs/gatewayAPI', 'httpRoute')
    err("#{f}: HTTPRoute #{route} not defined") if route && !by.('HTTPRoute', route)
    ps = d.dig('spec', 'template', 'spec') || {}
    grace = ps['terminationGracePeriodSeconds'] || 30
    (ps['containers'] || []).each do |ct|
      sl = ct.dig('lifecycle', 'preStop', 'sleep', 'seconds')
      err("#{f}: preStop sleep #{sl}s >= grace #{grace}s") if sl && sl >= grace
    end
  when 'Deployment'
    sel = d.dig('spec', 'selector', 'matchLabels') || {}
    lab = d.dig('spec', 'template', 'metadata', 'labels') || {}
    err("#{f}: Deployment selector not a subset of template labels") unless sel.all? { |k, v| lab[k] == v }
  when 'HTTPRoute'
    (d.dig('spec', 'rules') || []).each do |r|
      w = (r['backendRefs'] || []).map { |b| b['weight'] || 1 }.grep(Integer)
      err("#{f}: HTTPRoute rule with all weights 0 sends 500s") if !w.empty? && w.sum.zero?
    end
  when 'Ingress'
    an = d.dig('metadata', 'annotations') || {}
    if an['nginx.ingress.kubernetes.io/canary'] == 'true'
      w = an['nginx.ingress.kubernetes.io/canary-weight']
      err("#{f}: canary-weight must be a quoted integer string") if w && w !~ /\A\d+\z/
      host = d.dig('spec', 'rules', 0, 'host')
      main = objects.map(&:last).find { |o| o['kind'] == 'Ingress' && o != d && o.dig('spec', 'rules', 0, 'host') == host }
      err("#{f}: canary Ingress has no main Ingress for host #{host}") unless main
    end
  when 'Canary'
    (d.dig('spec', 'analysis', 'metrics') || []).each do |m|
      ref = m.dig('templateRef', 'name')
      err("#{f}: MetricTemplate #{ref} not defined") if ref && !by.('MetricTemplate', ref)
    end
  end
end

puts "#{files.size} files, #{objects.size} objects, #{SCHEMAS.size} schemas loaded"
if $errors.empty? then puts 'manifests ok' else puts $errors; exit 1 end

The Go angle ​

  • One wrapper, typed defaults. flags.Service is the only place that knows flag keys and defaults; handlers call NewCheckout(ctx, user). That is where flag debt is visible (grep flags.NewCheckout) and where the default per flag is decided: release flags fail closed (old path), kill switches fail open.
  • OpenFeature in Go. openfeature.SetNamedProviderAndWait(domain, provider) registers a provider; openfeature.NewClient(domain) returns a client; client.Boolean(ctx, key, default, evalCtx) never returns an error to the caller (use BooleanValueDetails for reason, variant and error code). Named domains keep tests independent of the global provider. The go-sdk v1.17.1 used here declares go 1.24.0; the next tags do not (proxy.golang.org .mod files: v1.17.2 and v1.18.0 say go 1.25.0, v1.19.0 and v1.20.0 say go 1.26.0).
  • Sticky percentages. FNV-1a over flagKey + 0x00 + targetingKey, modulo 100 000: deterministic, cheap, and independent per flag. Without a targeting key the evaluator returns TARGETING_KEY_MISSING and the default, rather than flipping per request.
  • Drain order. Readiness to 503 first, keep serving for DrainDelay (zero if the Pod has a preStop sleep that already covers propagation), then srv.Shutdown with a timeout. signal.NotifyContext turns SIGTERM into context cancellation; see OS, Processes & Signals.
  • The 5-second StateNew rule. Server.Shutdown closes idle connections but waits for connections in StateNew until they are 5 s old (net/http, issue 22682). The drain test hit this with keep-alive clients and now uses DisableKeepAlives; in production keep ShutdownTimeout comfortably above 5 s.
  • Version on every response. X-App-Version makes canaries countable from the outside (smoke.VersionMix) and lets logs and traces be split by version, which is what analysis queries need.
  • Smoke checks as code. The smoke package is what a job metric, a Flagger webhook or a pipeline step runs: readiness 200 and /version equal to the release being promoted.

Laravel ​

Before ​

The deploy most Laravel projects start with: git pull in the live directory, then commands in an order that guarantees errors:

bash
# Before: in-place deploy on the live directory
cd /var/www/shop
php artisan down                      # everyone gets 503 for the whole deploy
git pull origin main                  # live code changes file by file while requests run
composer install --no-dev             # vendor/ half-updated for tens of seconds
php artisan migrate --force           # new schema, new code, no way back
php artisan config:cache              # cached while files are still changing
php artisan up
# forgotten: php-fpm reload (OPcache keeps old bytecode), queue:restart (workers run old code)

After ​

The zero-downtime deploy script (release directories, expand-only migrations before the switch, caches inside the new release, atomic switch, php-fpm or Octane reload, queue:restart, smoke test and code-only rollback):

bash
#!/usr/bin/env bash
# deploy.sh: zero-downtime Laravel release on a VM (Nginx + php-fpm, or Octane),
# Capistrano/Deployer layout:
#   $ROOT/releases/<version>/   one directory per release, never modified after the switch
#   $ROOT/shared/.env, storage/  shared between releases
#   $ROOT/current -> releases/<version>   the only thing that changes at cut-over
#
#   deploy.sh [--dry-run] [--maintenance] VERSION ARTIFACT_DIR
#
# Order matters and is the point of the script:
#   build the release -> migrate (expand-only, old code still live) -> cache config/routes
#   -> atomic symlink switch -> reload php-fpm (or Octane) -> restart queue workers
#   -> smoke test -> on failure switch back (code only; migrations are forward-only).
# --maintenance is for the rare release that cannot be N-1 compatible: it wraps the
# migration in `artisan down` and accepts a few seconds of 503s instead. Because the
# previous release cannot run on the new schema, a failure in this mode NEVER switches
# the code back: the app stays (or goes back) in maintenance and a human decides
# (fix forward, or restore the database and then the code). Exit codes: 6 smoke test
# failed in maintenance mode, 7 a step failed between `down` and `up`.
set -euo pipefail

ROOT=${DEPLOY_ROOT:-/srv/shop}
APP_URL=${APP_URL:-http://127.0.0.1}
PHP_FPM_SERVICE=${PHP_FPM_SERVICE:-php8.4-fpm}
OCTANE=${OCTANE:-0}
KEEP=${KEEP:-5}
DRY_RUN=0
MAINTENANCE=0

usage() { echo "usage: ${0##*/} [--dry-run] [--maintenance] VERSION ARTIFACT_DIR" >&2; exit 2; }
log()   { printf '%s deploy: %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
run()   { if [ "$DRY_RUN" = 1 ]; then { printf 'DRY-RUN:'; printf ' %q' "$@"; printf '\n'; } >&2; else "$@"; fi; }

while [ "$#" -gt 0 ]; do
  case $1 in
    --dry-run) DRY_RUN=1; shift ;;
    --maintenance) MAINTENANCE=1; shift ;;
    -h|--help) usage ;;
    -*) echo "unknown option: $1" >&2; usage ;;
    *) break ;;
  esac
done
[ "$#" -eq 2 ] || usage
VERSION=$1 ARTIFACT=$2
case $VERSION in *[!A-Za-z0-9._-]*|'') echo "bad version: $VERSION" >&2; exit 2 ;; esac
[ -f "$ARTIFACT/artisan" ] || { echo "not a Laravel build: $ARTIFACT" >&2; exit 4; }
REL="$ROOT/releases/$VERSION"

# GNU mv -T / BSD mv -h: rename(2) the new link over the old one, so `current`
# always points at a complete release (no moment where it is missing).
swap_link() { case $(uname -s) in Darwin|*BSD) mv -fh "$1" "$2" ;; *) mv -T "$1" "$2" ;; esac; }
point_current_at() { run ln -sfn "$1" "$ROOT/current.new"; if [ "$DRY_RUN" = 0 ]; then swap_link "$ROOT/current.new" "$ROOT/current"; fi; }

reload_php() {
  if [ "$OCTANE" = 1 ]; then
    run php "$ROOT/current/artisan" octane:reload          # graceful worker restart, new code in memory
  else
    run systemctl reload "$PHP_FPM_SERVICE"               # php-fpm master gets SIGUSR2: graceful reload,
  fi                                                      # fresh workers and a fresh OPcache
  run php "$ROOT/current/artisan" queue:restart           # workers exit after their current job
}

smoke() {
  curl --fail --silent --show-error --max-time 5 --retry 3 --retry-delay 1 --retry-connrefused "$APP_URL/up" >/dev/null &&
    [ "$(curl --fail --silent --max-time 5 "$APP_URL/version")" = "$VERSION" ]
}

# 1. Idempotency.
if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$REL" ]; then
  log "$VERSION is already current; nothing to do"; exit 0
fi
PREV=""
if [ -L "$ROOT/current" ]; then PREV=$(readlink "$ROOT/current"); fi

# 2. Build the release next to the live one. Nothing here touches traffic.
run mkdir -p "$REL" "$ROOT/shared/storage"
run cp -R "$ARTIFACT/." "$REL/"
run rm -rf "$REL/storage"
run ln -sfn "$ROOT/shared/storage" "$REL/storage"
run ln -sfn "$ROOT/shared/.env" "$REL/.env"
run composer install --working-dir="$REL" --no-dev --prefer-dist --optimize-autoloader --no-interaction

# 3. Database first, while the OLD code still serves: migrations must be additive
#    (expand). The old release keeps working against the new schema (N-1 compatibility).
IN_MAINTENANCE=0
# Anything that fails between `down` and `up` (migrate, optimize, switch, reload) lands
# here: leave maintenance ON (the schema may be half-migrated), say so loudly, exit 7.
on_exit() {
  rc=$?
  if [ "$IN_MAINTENANCE" = 1 ] && [ "$rc" != 0 ]; then
    log "FAILED while in maintenance mode (exit $rc): the app stays DOWN; current -> $(readlink "$ROOT/current" 2>/dev/null || echo none)"
    log "the migration may be partly applied; decide by hand: fix forward, or restore the database first. Do not just run 'artisan up'."
    exit 7
  fi
}
trap on_exit EXIT
if [ "$MAINTENANCE" = 1 ]; then
  run php "${PREV:-$REL}/artisan" down --render="errors::503" --retry=60 --with-secret
  IN_MAINTENANCE=1
fi
run php "$REL/artisan" migrate --force --no-interaction

# 4. Caches are written inside the new release (bootstrap/cache), so the live one is untouched.
run php "$REL/artisan" optimize        # config:cache route:cache view:cache event:cache

# 5. Cut-over.
point_current_at "$REL"
reload_php
if [ "$MAINTENANCE" = 1 ]; then run php "$ROOT/current/artisan" up; IN_MAINTENANCE=0; fi

# 6. Post-deploy verification; roll the CODE back on failure. Never `migrate:rollback`
#    here: the previous release was built to run on the expanded schema.
if [ "$DRY_RUN" = 0 ] && ! smoke; then
  if [ "$MAINTENANCE" = 1 ]; then
    # The old code cannot run on this schema: switching back would trade a broken
    # release for a crashing one. Go back into maintenance and stop for a human.
    php "$ROOT/current/artisan" down --render="errors::503" --retry=60 || true
    log "smoke test failed after a maintenance-mode (incompatible) release; NOT switching code back."
    log "app is in maintenance on $VERSION; fix forward, or restore the database before any code rollback."
    exit 6
  fi
  if [ -n "$PREV" ]; then
    log "smoke test failed; switching back to $PREV"
    point_current_at "$PREV"; reload_php
  else
    log "smoke test failed on first deploy; removing current"; rm -f "$ROOT/current"
  fi
  exit 5
fi

# 7. Keep the newest $KEEP releases (the previous one is the instant rollback target).
if [ "$DRY_RUN" = 0 ]; then
  # shellcheck disable=SC2012  # release names are validated: no spaces or newlines
  ls -1t "$ROOT/releases" | tail -n +"$((KEEP + 1))" | while read -r old; do
    [ "$ROOT/releases/$old" = "$REL" ] || [ "$ROOT/releases/$old" = "$PREV" ] || rm -rf "${ROOT:?}/releases/$old"
  done
fi
log "deployed $VERSION (previous: ${PREV:-none})"

Its test, which runs the script with stub php, composer, systemctl and curl and asserts the order of every step and the release that was live when it ran:

bash
#!/usr/bin/env bash
# Runs laravel/deploy/deploy.sh in a temp directory with stub `php`, `composer`,
# `systemctl` and `curl` on PATH. The stubs log every call, so the test can
# assert the ORDER of migrate, optimize, switch, reload and queue:restart.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
SCRIPT="$HERE/../laravel/deploy/deploy.sh"
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
mkdir -p "$T/bin" "$T/root/shared" "$T/art"
touch "$T/art/artisan" "$T/root/shared/.env"; mkdir -p "$T/art/storage"
export CALLS="$T/calls" DEPLOY_ROOT="$T/root" PATH="$T/bin:$PATH" APP_URL=http://app

# Each stub logs its arguments and which release `current` points at when it runs
# (`ln` and `mv` are the real ones, so the switch itself is real).
for p in php composer systemctl; do
  cat > "$T/bin/$p" <<STUB
#!/usr/bin/env bash
c=\$(basename "\$(readlink "\$DEPLOY_ROOT/current" 2>/dev/null)")
echo "$p \$* (current=\${c:-none})" | sed "s|$T/root/||g" >> "\$CALLS"
case "\$*" in *"artisan migrate "*) [ -n "\${FAIL_MIGRATE:-}" ] && exit 1 ;; esac
exit 0
STUB
done
cat > "$T/bin/curl" <<'EOF'
#!/usr/bin/env bash
url=${!#}; v=$(basename "$(readlink "$DEPLOY_ROOT/current")")
echo "curl $url (current=$v)" >> "$CALLS"
[ -f "$DEPLOY_ROOT/broken-$v" ] && { echo "curl: (22) 500" >&2; exit 22; }
case $url in */version) printf '%s' "$v" ;; esac
EOF
chmod +x "$T/bin/"*

pass=0; fail=0
check() { if eval "$2"; then echo "ok   - $1"; pass=$((pass+1)); else echo "FAIL - $1"; fail=$((fail+1)); fi; }
line() { grep -n -- "$1" "$CALLS" | head -1 | cut -d: -f1; }
cur() { basename "$(readlink "$DEPLOY_ROOT/current")"; }

"$SCRIPT" 1.0.0 "$T/art" 2>/dev/null
check "first deploy points current at 1.0.0" '[ "$(cur)" = 1.0.0 ]'

: > "$CALLS"
"$SCRIPT" 1.1.0 "$T/art" 2>/dev/null
echo "  calls for 1.1.0:"; sed 's/^/    /' "$CALLS"
check "migrate runs before optimize" '[ "$(line "migrate --force")" -lt "$(line "artisan optimize")" ]'
check "migrate and optimize run while 1.0.0 is still live" 'grep -q "1.1.0/artisan migrate --force --no-interaction (current=1.0.0)" "$CALLS" && grep -q "1.1.0/artisan optimize (current=1.0.0)" "$CALLS"'
check "php-fpm reload runs after the switch" 'grep -q "systemctl reload php8.4-fpm (current=1.1.0)" "$CALLS"'
check "queue:restart comes after the php-fpm reload" '[ "$(line "systemctl reload php8.4-fpm")" -lt "$(line "queue:restart")" ]'
check "smoke test hit the new release" 'grep -q "curl http://app/version (current=1.1.0)" "$CALLS"'
check "no artisan down without --maintenance" '! grep -q "artisan down" "$CALLS"'

out=$("$SCRIPT" 1.1.0 "$T/art" 2>&1)
check "same version again is a no-op" 'grep -q "already current" <<<"$out"'

: > "$CALLS"; touch "$DEPLOY_ROOT/broken-1.2.0"
set +e; "$SCRIPT" 1.2.0 "$T/art" 2>"$T/log"; rc=$?; set -e
check "failed smoke test exits 5" '[ $rc = 5 ]'
check "current is back on 1.1.0" '[ "$(cur)" = 1.1.0 ]'
check "rollback reloaded php-fpm twice (switch + switch back)" '[ "$(grep -c "systemctl reload" "$CALLS")" = 2 ]'
check "rollback did not run migrate:rollback (forward-only)" '! grep -q "migrate:rollback" "$CALLS"'
sed "s/^[0-9:]* /  log: /; s|$T/||" "$T/log"

: > "$CALLS"
"$SCRIPT" --maintenance 1.3.0 "$T/art" 2>/dev/null
check "--maintenance: down before migrate, up after the switch" '[ "$(line "artisan down")" -lt "$(line "migrate --force")" ] && [ "$(line "systemctl reload")" -lt "$(line "artisan up")" ]'
check "--maintenance uses --with-secret and a pre-rendered 503" 'grep -q -- "down --render=errors::503 --retry=60 --with-secret" "$CALLS"'

: > "$CALLS"
OCTANE=1 "$SCRIPT" 1.4.0 "$T/art" 2>/dev/null
check "OCTANE=1 reloads Octane workers instead of php-fpm" 'grep -q "current/artisan octane:reload" "$CALLS" && ! grep -q systemctl "$CALLS"'

: > "$CALLS"; touch "$DEPLOY_ROOT/broken-1.5.0"
set +e; "$SCRIPT" --maintenance 1.5.0 "$T/art" 2>"$T/log"; rc=$?; set -e
check "--maintenance + failed smoke test exits 6 and does NOT switch code back" '[ $rc = 6 ] && [ "$(cur)" = 1.5.0 ]'
check "--maintenance + failed smoke test puts the app back into maintenance" '[ "$(grep -c "artisan down" "$CALLS")" = 2 ] && [ "$(grep -c "systemctl reload" "$CALLS")" = 1 ]'
sed "s/^[0-9:]* /  log: /; s|$T/||" "$T/log"

: > "$CALLS"
set +e; FAIL_MIGRATE=1 "$SCRIPT" --maintenance 1.6.0 "$T/art" 2>"$T/log"; rc=$?; set -e
check "--maintenance + failing migrate exits 7, stays down, no switch, no up" '[ $rc = 7 ] && [ "$(cur)" = 1.5.0 ] && grep -q "artisan down" "$CALLS" && ! grep -q "artisan up" "$CALLS" && ! grep -q "systemctl reload" "$CALLS"'
grep "FAILED while in maintenance" "$T/log" | sed "s/^[0-9:]* /  log: /; s|$T/||"

: > "$CALLS"
set +e; FAIL_MIGRATE=1 "$SCRIPT" 1.7.0 "$T/art" 2>/dev/null; rc=$?; set -e
check "failing migrate without --maintenance stops before the switch (old release stays live)" '[ $rc != 0 ] && [ "$(cur)" = 1.5.0 ] && ! grep -q "systemctl reload" "$CALLS"'

before=$(cur)
out=$("$SCRIPT" --dry-run 9.9.9 "$T/art" 2>&1)
check "dry run changes nothing" '[ "$(cur)" = "$before" ] && [ ! -d "$DEPLOY_ROOT/releases/9.9.9" ] && grep -q "DRY-RUN: php .*9.9.9/artisan migrate" <<<"$out"'

echo "$pass passed, $fail failed"
[ "$fail" = 0 ]

Nginx in front of php-fpm with $realpath_root, so requests never mix files from two releases:

nginx
# Nginx in front of php-fpm for the symlinked layout. The root goes through
# the `current` symlink; SCRIPT_FILENAME and DOCUMENT_ROOT use $realpath_root
# (the root "with all symbolic links resolved to real paths"), so each request
# names the real release directory and php-fpm/OPcache never mix files from
# two releases across a switch.
server {
    listen 80;
    server_name shop.example;
    root /srv/shop/current/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        internal;
    }

    location ~ \.php$ {
        return 404;
    }
}

The release flag as a Pennant class (targeting rules first, then a stored 5 % lottery), a cache-backed kill switch that fails open, and the controller that uses both:

php
<?php

namespace App\Features;

use App\Models\User;
use Illuminate\Support\Lottery;

/**
 * Release flag for the new checkout (Laravel Pennant, class-based feature).
 *
 * Pennant resolves the value once per scope and STORES it (database driver),
 * so a user who won the 5 % lottery keeps the new checkout on every request
 * and every server. Raising the odds later only affects users who have not
 * been resolved yet; `php artisan pennant:purge App\\Features\\NewCheckout`
 * re-rolls everyone. Remove this class (and the purge) when the rollout ends.
 */
class NewCheckout
{
    public function resolve(?User $user): mixed
    {
        return match (true) {
            $user === null => false,                       // queued jobs, console, guests
            $user->is_staff => true,                       // targeting rule: dogfood first
            in_array($user->country, ['DE'], true) => false, // legal review pending
            default => Lottery::odds(5, 100),              // percentage rollout: 5 %
        };
    }
}
php
<?php

namespace App\Support;

use Illuminate\Support\Facades\Cache;
use Throwable;

/**
 * Operational kill switch: a permanent flag that is ON by default and is
 * turned OFF in an incident, on every server at once, without a deploy.
 *
 * It lives in the shared cache store (Redis) rather than in Pennant because it
 * is global (no per-user scope) and must be cheap to read on every request.
 * If the cache is unreachable the switch fails OPEN (feature keeps running),
 * which is the right default for a feature that works but is expensive.
 *
 *   php artisan tinker --execute="App\Support\KillSwitch::off('recommendations')"
 */
final class KillSwitch
{
    public static function on(string $name): bool
    {
        try {
            return Cache::get("killswitch:{$name}", true) !== false;
        } catch (Throwable) {
            return true;
        }
    }

    public static function off(string $name): void
    {
        Cache::forever("killswitch:{$name}", false);
    }

    public static function restore(string $name): void
    {
        Cache::forget("killswitch:{$name}");
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Features\NewCheckout;
use App\Services\Recommendations;
use App\Support\KillSwitch;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Pennant\Feature;

class CheckoutController extends Controller
{
    public function __construct(private Recommendations $recommendations) {}

    public function show(Request $request): JsonResponse
    {
        // Both code paths ship in every release; the flag decides per user.
        $flow = Feature::for($request->user())->active(NewCheckout::class) ? 'v2' : 'v1';

        $payload = ['flow' => $flow, 'version' => config('app.version')];

        // The expensive call the kill switch can stop during an incident.
        if (KillSwitch::on('recommendations')) {
            $payload['recommendations'] = $this->recommendations->for($request->user());
        }

        return response()->json($payload)->header('X-App-Version', (string) config('app.version'));
    }
}
php
<?php

// routes/web.php (excerpt): the endpoints deploy.sh and the smoke test call.
// /up is Laravel's built-in health route (bootstrap/app.php: health: '/up').

use App\Http\Controllers\CheckoutController;
use Illuminate\Support\Facades\Route;

Route::get('/version', fn () => response((string) config('app.version'))->header('Content-Type', 'text/plain'));
Route::get('/checkout', [CheckoutController::class, 'show'])->middleware('auth');

On Kubernetes the Laravel web Deployment (shop-web, Nginx + php-fpm in one Pod) is canaried with Flagger through the Gateway API, with an error-rate MetricTemplate on the Nginx metrics, the builtin p99 duration check, a smoke webhook on /up and a load-test webhook:

yaml
# Flagger canary for the Laravel web Deployment `shop-web` (Nginx + php-fpm
# pod), traffic shifted through a Gateway API HTTPRoute that Flagger generates.
# Flagger creates shop-web-primary (stable) and scales shop-web (the target)
# to zero between releases; a change to the target's pod template, or to a
# ConfigMap/Secret it uses, starts an analysis.
apiVersion: flagger.app/v1beta1
kind: MetricTemplate
metadata:
  name: error-rate
  namespace: shop
spec:
  provider:
    type: prometheus
    address: http://prometheus.monitoring.svc:9090
  # Flagger fills namespace, target and interval. Result: percentage of 5xx.
  query: |
    100 * sum(rate(nginx_http_requests_total{namespace="{{ namespace }}",service="{{ target }}-canary",status=~"5.."}[{{ interval }}]))
    /
    sum(rate(nginx_http_requests_total{namespace="{{ namespace }}",service="{{ target }}-canary"}[{{ interval }}]))
---
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
  name: shop-web
  namespace: shop
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: shop-web
  autoscalerRef:
    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    name: shop-web
  progressDeadlineSeconds: 600
  service:
    port: 80
    targetPort: http
    hosts:
      - shop.example
    gatewayRefs:
      - name: public
        namespace: gateway
  analysis:
    interval: 1m        # one check per minute
    threshold: 5        # 5 failed checks -> rollback (5 minutes at worst)
    maxWeight: 50
    stepWeight: 10      # 10, 20, 30, 40, 50 -> promote: >= 5 minutes when healthy
    metrics:
      - name: error-rate
        templateRef:
          name: error-rate
          namespace: shop
        thresholdRange:
          max: 1        # percent
        interval: 1m
      - name: request-duration   # Flagger builtin: P99 in milliseconds
        thresholdRange:
          max: 500
        interval: 1m
    webhooks:
      - name: smoke
        type: pre-rollout
        url: http://flagger-loadtester.test/
        timeout: 30s
        metadata:
          type: bash
          cmd: "curl -fsS http://shop-web-canary.shop/up"
      - name: load
        url: http://flagger-loadtester.test/
        timeout: 5s
        metadata:
          cmd: "hey -z 1m -q 5 -c 2 http://shop-web-canary.shop/"

The Laravel angle ​

  • Migrations before the switch, always additive. php artisan migrate --force runs from the new release while the old one serves; the old code must ignore the new columns. Destructive steps (drop, rename, NOT NULL without default) wait for a later release. In Kubernetes the same step is a Job run as an Argo CD PreSync hook or Helm pre-upgrade hook (Kubernetes Workloads has the Job).
  • Caches per release. php artisan optimize writes bootstrap/cache/*.php inside the new release directory, so the live release keeps its own caches until the switch. After config:cache, env() outside config files returns only real environment variables.
  • php-fpm and OPcache. With opcache.validate_timestamps=0 (production), changed files are invisible until FPM restarts its workers; the deploy reloads FPM (SIGUSR2) after the switch, and $realpath_root keeps each request on one release. In containers there is nothing to reload: a new image means new Pods.
  • Octane. The app lives in worker memory; octane:reload after the switch, or let the Kubernetes rollout replace the Pods.
  • Queues. queue:restart stores a restart signal in the cache; workers exit after the current job and Supervisor starts them on the new code. Jobs serialised by the old version must still be readable by the new one (N-1 for payloads, too). In Kubernetes, the worker Deployment's rolling update does the same job; give workers a long enough grace period for their longest job.
  • Pennant semantics. A Lottery-based rollout is stored per scope on first check, so it is sticky but not adjustable: raising the odds affects only users never resolved, and pennant:purge re-rolls everyone. For a hash-based, adjustable percentage use an external provider (Unleash, Flagsmith, LaunchDarkly, flagd via OpenFeature's PHP SDK).
  • Kill switches outside Pennant. A global operational switch is a single cache key read on every request; fail open if the cache is down, as KillSwitch::on does.
  • Maintenance mode is a tool, not the default. --render="errors::503" avoids booting the framework during the 503, --with-secret lets the team in, and the cache driver makes down apply to every server at once. A maintenance-mode release is by definition not N-1 compatible, so its failure path is "stay down and call a human", never an automatic code rollback; the script's EXIT trap makes sure a failed migrate cannot leave the team guessing.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
Every deploy is a releaseFeature flags + dark deploysOpenFeature wrapper, defaults per flagRelease and rollback without deploysFlag debt, a flag service
Bad versions reach 100 %Canary with analysisArgo Rollouts / Flagger, Prometheus gatesBlast radius of a few percent, automatic abortController, trustworthy metrics
502s during deploysReadiness + preStop + drainProbe fails on SIGTERM, preStop sleep, ShutdownNo dropped requestsSlower Pod turnover
Rollback breaks on the schemaExpand/contract, forward-onlyAdditive migrations before the switchAny single step is reversibleMore releases per schema change
Rollback deploys different codeDigest pinningimage@sha256:... in GitExact rollback targetTooling to write digests
Rollback undone by GitOpsRoll back in Gitgit revert of the bumpGit and cluster agreeOne sync of latency
Low traffic, canary says nothingHeader routing + synthetic loadX-Canary: always, load-test webhookSignal without usersSynthetic traffic is not real traffic
Laravel serves old code after deployReload long-lived processesFPM reload, octane:reload, queue:restartNew code everywhereBrief worker churn
Blue-green costs doubleSmall preview, quick scale-downpreviewReplicaCount, short scaleDownDelaySecondsCheaperShorter instant-rollback window
Ingress-NGINX is retiredMove canaries to Gateway APIMap annotations to HTTPRoute weights and matchesMaintained, standard APIA migration project

A bad release reached production ​

Follow the rollback tree: flag off if the change is flagged; abort if a canary is in progress; switch back if the old slot or release still runs; otherwise redeploy the previous digest through Git. Then make sure Git matches the cluster, freeze this service until the cause is known, and add the missed signal to the analysis.

Deploying a schema change with a rolling update ​

Split it into releases as in Database-compatible releases. Run the expand migration as a pre-sync Job (Kubernetes) or before the symlink switch (VM); deploy code that tolerates both schemas; contract in a later release after the rollback window.

Canary metrics that lie ​

Query canary-only series (by Service or pod-template hash label), require data (len(result) > 0), compare against an absolute SLO threshold as well as against stable, and keep the canary long enough to see enough requests. Add one business metric for flows that fail without 5xx (an empty basket still returns 200).

Mixed versions break the browser ​

Per-request weights send a user's HTML to one version and their JS bundle to another. Use cookie routing or session affinity (Ingress-NGINX affinity-canary-behavior: sticky), keep old assets available (immutable asset URLs on a CDN), or release UI changes with a user-keyed flag instead.

Long-running work during a switch ​

Queue workers and long requests must finish or be safely interrupted: give the worker Deployment a grace period longer than its longest job, use queue:restart on VMs, make jobs idempotent so a retry after a SIGKILL is harmless, and keep job payloads readable by the previous version.

Choosing ​

Which strategy ​

SituationStrategyReason
Stateless service, good probes, low risk changeRolling updateFree, built in
Versions cannot coexist (singleton, incompatible protocol)Recreate (with a maintenance window)Honest about downtime
High-risk release, need full verification before usersBlue-greenTest in production, instant switch back
High traffic, frequent deploysProgressive canary (Argo Rollouts / Flagger)Small blast radius, automatic abort
Low traffic serviceBlue-green or header canary with synthetic checksWeight canaries lack signal
Product question (does B convert better?)A/B test with flagsSticky users, product metrics
New backend, unknown loadShadow traffic, then canaryLoad without user impact
Unfinished feature merged to mainFeature flag (release toggle)Trunk-based development
PHP app on VMsSymlink releases + reload, or blue-green ASGsSeconds to switch back

Which traffic layer ​

You haveUse
Nothing beyond ServicesReplica-ratio canary or Service selector blue-green
Ingress-NGINX (legacy)Canary annotations now, migration plan to Gateway API
A Gateway API implementationHTTPRoute weights and header matches
A mesh (Istio, Linkerd)Mesh routes for east-west; HTTPRoute where supported
VMs behind a cloud LBWeighted target groups / two ASGs

Which controller ​

SituationChoice
Argo CD shop, want explicit step lists and a UIArgo Rollouts
Flux shop, want to keep plain DeploymentsFlagger
Few services, deploys a weekRolling + manual canary via HTTPRoute PRs
Need experiments (baseline vs canary side by side)Argo Rollouts experiment

Which flag system ​

SituationChoice
Avoid vendor lock-in in codeOpenFeature API + any provider
Laravel-only app, simple rolloutsLaravel Pennant (+ cache-key kill switches)
Self-hosted, open source, many teamsUnleash or Flagsmith (or flagd)
Experiments, audit, enterprise targetingLaunchDarkly
Already on GitLabGitLab feature flags (Unleash-compatible)

In architecture: from a single process to a distributed system ​

A deployment strategy is a property of the whole system, not of one service: two versions coexist on every interface (database, queues, APIs, caches, browser assets), and the strategy decides for how long and for whom.

Monolith: one app, one database ​

A Laravel monolith on two VMs: the symlink deploy with expand-only migrations, php-fpm reload and queue:restart, a smoke test, and flags for features. Blue-green at the load balancer is the next step when releases need full verification. The hard part is not traffic but the single database: every release is N-1 compatible or it is a maintenance window.

Modular monolith: one deploy unit, many teams ​

One artefact, many teams' features: deploys must not wait for every team to be "done", so unfinished work ships dark behind release flags, and each module owns its flags and their cleanup. Canary the whole artefact; release modules by flag.

Microservices: many services, many versions ​

Twenty services deploy independently, so at any moment service A version N talks to service B version N or N-1: API compatibility (additive fields, tolerant readers, versioned endpoints) becomes the N-1 rule for networks. Progressive delivery per service with a shared AnalysisTemplate library (ClusterAnalysisTemplate), mesh or Gateway routing for east-west canaries, a GitOps repo per environment, and a platform-owned golden path: Terraform for the Gateway, Prometheus and the controllers; GitHub Actions or GitLab CI producing digests; Argo CD applying them; Helm or Kustomize for packaging.

text
1  service A: CI builds digest D, opens PR in env repo (staging), auto-merge after tests
2  Argo CD syncs staging; Rollout runs short steps; smoke + contract tests
3  promotion PR to production (GitHub Actions environment: required reviewer, freeze check)
4  Argo CD syncs prod; Rollout 5 -> 20 -> 50 -> 100 with ClusterAnalysisTemplate gates
5  any abort: Degraded alert to the owning team; revert PR prepared automatically

Distributed data: caches, queues, regions ​

Shared state outlives any version: cache entries written by N are read by N-1 after a rollback (version cache keys or keep formats compatible), queue messages produced by N are consumed by N-1 workers (schema evolution rules, as in Kafka or protobuf), and multi-region deploys run region by region, so a release is itself a canary at region scale (one region first, bake time, then the rest). Feature flag services must be reachable in every region or evaluated locally from a streamed snapshot (LaunchDarkly, Unleash proxies, flagd), with safe defaults when they are not.

Scaling path: 1x, 10x, 100x ​

ScaleStrategyVerificationRollback
1x (one team, one app)Rolling or symlink deploy; flags in-app (Pennant)Smoke test, dashboardSymlink back, kubectl rollout undo
10x (several teams, one cluster)Canary via Gateway API; blue-green for risky releases; OpenFeature + one providerPrometheus gates, synthetic checksAbort, Git revert, flag off
100x (many clusters, regions)Progressive delivery everywhere, region waves, freeze calendars as codeSLO-based promotion, automated analysis, DORA trackingAutomatic abort, automated revert PRs, global kill switches

Lab ​

Label: there is no Kubernetes cluster, Argo Rollouts, Flagger, mesh, PHP-FPM or Laravel application in this build environment. Every kubectl, kubectl argo rollouts, helm, argocd and aws command below is expected, not run: shown with the documented behaviour, never with invented output. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64; Ruby 2.6; PHP 8.5 CLI) and show real output, saved in pipeline/sources/deployment-strategies/lab-host-output.txt.

1. Go tests: flags, drain, smoke (ran on the host) ​

bash
cd docs/snippets/platform/deployment-strategies/go
gofmt -l . ; go vet ./... ; go test -race -count=1 -v ./...
# --- PASS: TestPercentageRolloutIsStickyAndMonotonic (0.28s)
#     flags_test.go:121: 10%: 2010 users, 50%: 10040 users of 20000
# ok  	academy/deployment-strategies/flags	1.729s
# --- PASS: TestDrainFailsReadinessThenFinishesInFlight (0.59s)
# --- PASS: TestShutdownTimeoutReportsStuckRequests (0.10s)
# ok  	academy/deployment-strategies/server	2.122s
# ok  	academy/deployment-strategies/smoke	1.461s

2. The service, its flags and its drain (ran on the host) ​

All lab commands start from the repository root.

bash
cd docs/snippets/platform/deployment-strategies/go
go build -ldflags "-X main.version=1.5.0" -o /tmp/orders-api ./cmd/orders-api
PORT=18082 /tmp/orders-api &
curl -si localhost:18082/version
# HTTP/1.1 200 OK
# X-App-Version: 1.5.0
# {"version":"1.5.0"}
curl -s -X POST -H "X-User-ID: staff-1" -H "X-Plan: internal" localhost:18082/checkout
# {"flow":"v2","recommendations":["sku-42"]}          (targeting rule)
n=0; for i in $(seq 1 1000); do
  curl -s -X POST -H "X-User-ID: user-$i" localhost:18082/checkout | grep -q '"v2"' && n=$((n+1)); done; echo "v2 for $n of 1000 users"
# v2 for 49 of 1000 users                              (5 % rollout)
kill -TERM %1; sleep 1; curl -s -o /dev/null -w 'readyz during drain %{http_code}\n' localhost:18082/readyz
# readyz during drain 503
sleep 6; curl -s -o /dev/null -w 'after drain %{http_code}\n' localhost:18082/readyz
# after drain 000                                      (connection refused: process exited)
# server log:
# {"level":"INFO","msg":"serving","addr":"[::]:18082","version":"1.5.0"}
# {"level":"INFO","msg":"draining","delay":5000000000}
# {"level":"INFO","msg":"stopped"}

3. Manifests against the real schemas (ran on the host) ​

bash
cd docs/snippets/platform/deployment-strategies/k8s     # from the repository root
ruby check-manifests.rb ../../../../../pipeline/sources/deployment-strategies */*.yaml
# 8 files, 22 objects, 104 schemas loaded
# manifests ok
# Negative test (copies with injected typos) is caught:
# Rollout.spec.strategy.canary.steps[0]: unknown field 'setWeigth'
# Canary.spec.analysis: unknown field 'stepWeigt'
# HTTPRoute.spec.rules[1].backendRefs[0].weight: expected integer, got String
# VirtualService.spec.http[1].route[0].destination: unknown field 'subst'
# canaryService orders-api-canry not defined

kubectl apply --dry-run=client was tried and needs API discovery from a server (couldn't get current server API group list), so the schema check above replaces it.

4. Blue-green switch and Laravel deploy with stubs (ran on the host) ​

bash
cd docs/snippets/platform/deployment-strategies           # from the repository root
bash tests/blue-green-switch-test.sh
# ok   - preview was patched before live
# ok   - second run is a no-op (idempotent)
# ok   - wrong version on preview aborts with 4 before the switch
# ok   - failing live path after the switch rolls back with 5
#   log: switch: request 6 answered 'error'; rolling back to blue
# ok   - VERIFY_N=3 with a failing live path still rolls back with 5
#   log: switch: verification ended with 'error' (0/3 requests on 1.5.0); rolling back to blue
# 10 passed, 0 failed
bash tests/laravel-deploy-test.sh
#     php releases/1.1.0/artisan migrate --force --no-interaction (current=1.0.0)
#     php releases/1.1.0/artisan optimize (current=1.0.0)
#     systemctl reload php8.4-fpm (current=1.1.0)
#     php current/artisan queue:restart (current=1.1.0)
# ok   - rollback did not run migrate:rollback (forward-only)
# ok   - --maintenance + failed smoke test exits 6 and does NOT switch code back
#   log: deploy: smoke test failed after a maintenance-mode (incompatible) release; NOT switching code back.
# ok   - --maintenance + failing migrate exits 7, stays down, no switch, no up
#   log: deploy: FAILED while in maintenance mode (exit 1): the app stays DOWN; current -> root/releases/1.5.0
# 20 passed, 0 failed

5. An Argo Rollouts canary with an abort (expected, not run) ​

bash
kubectl argo rollouts set image orders-api orders-api=ghcr.io/acme/orders-api@sha256:<new>   # or a Git commit
kubectl argo rollouts get rollout orders-api --watch
# expected: Status Progressing, Step 1/8, SetWeight 5, ActualWeight 5; AnalysisRun created at step 2
kubectl get httproute orders-api -o jsonpath='{.spec.rules[0].backendRefs[*].weight}'
# expected: 95 5 while at step 0
kubectl argo rollouts abort orders-api
# expected: weights back to 100 0, Status Degraded; spec.template still the new image (fix in Git)
kubectl argo rollouts promote orders-api --full      # emergency only: skips analysis, pauses and steps

6. Plain Deployment rollback and Helm rollback (expected, not run) ​

bash
kubectl annotate deployment/shop-web kubernetes.io/change-cause="image 1.5.0"
kubectl rollout history deployment/shop-web                  # REVISION  CHANGE-CAUSE
kubectl rollout undo deployment/shop-web --to-revision=3     # pod template only
kubectl rollout undo --dry-run=server deployment/shop-web    # preview, documented flag
helm history shop -n shop
helm rollback shop 0 -n shop --wait                         # 0 or omitted = previous release

7. Ingress-NGINX canary routing (expected, not run) ​

bash
for i in $(seq 1 1000); do curl -s -o /dev/null -w '%header{x-app-version}\n' https://shop.example/; done | sort | uniq -c
# expected with canary-weight "10": roughly 900 stable / 100 canary (random per request, not exact)
curl -s -H 'X-Canary: always' https://shop.example/ -o /dev/null -w '%header{x-app-version}\n'   # always canary
curl -s --cookie 'canary=never' https://shop.example/ -o /dev/null -w '%header{x-app-version}\n' # always stable

Common misconceptions ​

BeliefReality
Rolling back is always safeOnly if the previous version works on the current schema; rollout undo touches only the Pod template
A 10 % canary means 10 % of usersWeights are per request; stickiness needs cookies, headers or user-keyed flags
Blue-green solves database changesBoth colours usually share the database; the schema must serve both
Argo Rollouts' abort reverts GitIt "doesn't read/write anything to Git"; revert the commit yourself
Gateway API weights are percentagesProportional to their sum; a single backend gets 100 % only with weight > 0
Feature flags replace canariesFlags guard flagged code; crashes, leaks and dependency bugs need a traffic-level strategy
A flag outage breaks the appOpenFeature returns the coded default; choose defaults per flag
kubectl rollout undo sticks under GitOpsThe GitOps controller re-applies Git; roll back in Git
Recreate is never acceptableIt is the honest choice when versions cannot coexist
php artisan down is the zero-downtime deployIt is deliberate downtime; use release directories and reloads
A symlink switch reloads PHPphp-fpm/OPcache, Octane and queue workers keep old code until reloaded or restarted
Down migrations are the database rollbackForward-only migrations and expand/contract are; down migrations lose data
Average latency is a good canary gateGate on p99 (or p95) of the canary and on an absolute SLO
A canary with no data passedNo data must fail: require len(result) > 0
Ingress-NGINX is the default canary toolRetired in March 2026; use the Gateway API

Cheat sheet ​

TopicRemember
VocabularyDeploy = runs in prod; release = users reach it; rollout = the controlled path
RollingDefault; needs readiness and N-1; mechanics in Kubernetes Workloads
RecreateAll Pods killed first; downtime; for incompatible versions
Blue-greenTwo environments; switch at Service selector, route or LB; 2x cost; seconds to switch back
CanaryWeight, header, cookie; compare canary vs control and vs SLO
Ingress-NGINXcanary: "true", by-header > by-cookie > weight; one canary per rule; retired 2026
Gateway APIbackendRefs[].weight proportional; header rules for testers
Argo RolloutsRollout CRD; setWeight, pause, analysis; Failed = abort, Inconclusive = pause; Git untouched
FlaggerKeeps Deployment, creates -primary; promote >= interval x maxWeight/stepWeight; rollback = interval x threshold
HealthSuccess rate + p99 of the canary; require data; burn rate from the SLO
FlagsOpenFeature + provider; default on error; sticky hash buckets; kill switches fail open; delete after 100 %
Rollback orderFlag off > abort > switch back > redeploy previous digest via Git > roll forward
DigestsDeploy @sha256:; keep revisionHistoryLimit and Helm history
DatabaseExpand before, contract a release later; forward-only; N-1 always
Zero downtimeReadiness off on SIGTERM, preStop sleep, drain, grace > sum; readiness gates on AWS
LaravelBuild in new dir, migrate (expand), optimize, atomic switch, FPM reload / octane:reload, queue:restart, smoke
VMsAMI + instance refresh (checkpoints, auto rollback) or symlink releases
ProcessFreezes as config, smoke + synthetic checks, runbooks, DORA metrics

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between deploying and releasing, and why does it matter for rollback? Must-know ​

Answer

Answer: Deploying puts an artefact in production; releasing lets users reach the new behaviour. When they are separate (dark code behind a flag, an idle green slot, a canary at weight 0), a release can be reversed by a configuration change in seconds, while rolling back a deployment means changing the running artefact. See Deployment, release, rollout.

2 — A release renamed a column in one migration and the new code fails. Why is kubectl rollout undo not the fix, and how should the change have been shipped? Must-know ​

Answer

Answer: Undo restores only the Pod template; the old code expects the old column, which no longer exists, so the rollback fails too. Fix forward now. Ship such changes as expand/contract: add the new column, dual-write and backfill, switch reads, stop writing the old column, and drop it a release later, so each step is N-1 compatible. See Database-compatible releases.

3 — How does a blue-green switch work on plain Kubernetes, and what makes it safe? Must-know ​

Answer

Answer: Two Deployments labelled slot: blue and slot: green; the live Service selects one slot. After green is fully rolled out and smoke-tested through a preview Service, one patch of the live Service's selector moves all traffic; verifying through the public path and patching back on failure makes it safe, and keeping blue running keeps rollback instant. The database must serve both versions. See Blue-green.

4 — With Ingress-NGINX, a request has X-Canary: never and the cookie canary=always. Where does it go, and why? Important ​

Answer

Answer: To stable. Canary rules are evaluated in the order canary-by-header, then canary-by-cookie, then canary-weight; the header rule matches with never, so the cookie is not consulted. See Ingress-NGINX canary.

5 — An HTTPRoute rule lists backends with weights 3 and 1. What split results, and what if only one backend is listed with weight 0? Important ​

Answer

Answer: 75 % and 25 %, because weights are proportional to their sum. A single backend gets 100 % only when its weight is greater than 0; the HTTPRoute CRD says that with weight 0 "no traffic should be forwarded for this entry", so the rule sends nothing to it. See Gateway API.

6 — An Argo Rollouts AnalysisRun fails at 20 %. What happens in the cluster and in Git, and what must the on-call do? Must-know ​

Answer

Answer: The Rollout aborts: traffic weight returns to 0 for the canary, the stable ReplicaSet serves everything, and the Rollout is Degraded. Git still declares the new version because Argo Rollouts never writes to Git, so the on-call reverts (or fixes) the commit. Until then Argo CD syncs take no action, because Git and the live Rollout agree on the new version; the cluster stays on the old version and Degraded, and an explicit kubectl argo rollouts retry rollout (or a new revision) would start the bad canary again. See Argo Rollouts and Rollback mechanics.

7 — Flagger runs with interval: 1m, stepWeight: 10, maxWeight: 50, threshold: 5. How long at least until promotion, and how long until rollback when checks fail? Important ​

Answer

Answer: Promotion takes at least interval x (maxWeight / stepWeight) = 1 m x 5 = 5 minutes; rollback happens after interval x threshold = 5 minutes of failed checks. See Flagger.

8 — Your canary analysis query returns no data because the new version renamed its metric. What happens with result[0] >= 0.99, and how do you make the gate safe? Important ​

Answer

Answer: The template must handle an empty result explicitly; Argo Rollouts documents both choices. Use len(result) > 0 && result[0] >= 0.99 so missing data fails the measurement instead of letting an unmeasured canary pass. See Release health.

9 — How do you choose the default value of a feature flag, and what does OpenFeature do when the provider is down? Must-know ​

Answer

Answer: OpenFeature returns the caller's default on any abnormal execution and never throws. So the default is the safe state: a release flag defaults to the old path (false), a kill switch for a working but expensive feature defaults to on. See Feature flags.

10 — Why does a percentage rollout hash the user ID with the flag key, and why must raising 10 % to 50 % never remove users? Important ​

Answer

Answer: Hashing a stable targeting key makes the decision sticky per user; including the flag key makes cohorts independent between flags (Unleash's groupId, LaunchDarkly's flag key and salt). With bucket < percent as the rule, every user in the 10 % cohort is also below the 50 % threshold, so increasing the percentage only adds users; the chapter's Go test asserts it. See Feature flags.

11 — Pods return 502 for a second every time they are replaced. What is missing? Must-know ​

Answer

Answer: The process stops before load balancers have removed it. Add a preStop sleep (or a drain delay), fail readiness on SIGTERM, drain with Shutdown and a timeout, and keep the grace period larger than the sum; behind an AWS ALB, add the load balancer controller's readiness gates so new Pods are healthy in the target group before old ones go. See Zero-downtime details.

12 — After a symlink deploy of a Laravel app, some requests still run old code and queue jobs fail. Which steps are missing and in what order? Must-know ​

Answer

Answer: After the atomic switch: reload php-fpm (graceful SIGUSR2, fresh OPcache) or octane:reload for Octane, then php artisan queue:restart so workers exit after their current job and restart on the new code; before the switch, migrations must have run (expand only) and php artisan optimize must have built the caches inside the new release. See Laravel zero-downtime.

13 — When is php artisan down --with-secret the right tool? Good to know ​

Answer

Answer: For the rare release that cannot be made N-1 compatible, when a short, announced 503 is the honest option. --with-secret prints a bypass token so the team can test, --render="errors::503" serves the page before the framework boots, and the cache maintenance driver applies it to all servers. Queued jobs are not processed while the app is down. See Laravel zero-downtime.

14 — Which DORA metrics does a deployment strategy influence, and what was MTTR renamed to? Good to know ​

Answer

Answer: Deployment frequency and change lead time (throughput), change fail rate and deployment rework rate (instability), and failed deployment recovery time, which replaced MTTR in 2023. Canaries and flags mainly lower the change fail rate and the recovery time. See Freezes, verification, runbooks.

Glossary ​

TermMeaning
Deployment (act)Putting a new artefact into production infrastructure
ReleaseLetting users or traffic reach the new behaviour
RolloutThe controlled progression from old to new; ends in promotion or rollback
PromotionThe new version becomes the stable one
RollbackThe previous version serves again
Roll forwardFixing a bad release with a new release instead of going back
Recreate strategyKill all old Pods, then start new ones; downtime
Rolling updateReplace Pods gradually; both versions serve for a while
Blue-green deploymentTwo full environments; switch traffic between them
Environment switchThe single change that moves traffic: Service selector, route, LB, DNS
Canary releaseA small share of traffic to the new version, compared with the rest
ControlThe part of the service not receiving the change during a canary
Traffic weightShare of requests sent to a backend
Header-based routingRoute by a request header (X-Canary: always)
Cookie-based routingRoute by a cookie; sticky per browser
Ingress-NGINX canary annotationsnginx.ingress.kubernetes.io/canary* on a second Ingress
Gateway APIKubernetes routing API (Gateway, HTTPRoute) succeeding Ingress
HTTPRouteGateway API route; backendRefs with weights, matches, filters
Service mesh traffic splitWeighted routing between service versions inside the mesh
Istio VirtualServiceIstio routing object: matches, weighted routes, mirror
DestinationRuleIstio object defining subsets by labels
SMI TrafficSplitArchived Service Mesh Interface split API; deprecated in Linkerd
Progressive deliveryAutomated, metric-gated, step-wise release
Argo RolloutsController with Rollout, AnalysisTemplate, AnalysisRun, Experiment CRDs
Rollout CRDDeployment replacement with blueGreen and canary strategies
Canary stepssetWeight, pause, analysis, setCanaryScale, setHeaderRoute, setMirrorRoute, experiment
AnalysisTemplateMetric definitions with conditions and limits
AnalysisRunAn instantiation of an AnalysisTemplate; Successful, Failed or Inconclusive
successCondition / failureLimitExpression per measurement / tolerated failed measurements
AbortStop a rollout and send traffic back to stable
Automatic rollbackAbort triggered by failed analysis
FlaggerProgressive delivery operator (Flux family) using a Canary CRD
Canary CRD (Flagger)flagger.app/v1beta1 object: target, service, analysis, metrics, webhooks
MetricTemplateFlagger custom metric query
A/B testingSticky user split to compare product outcomes
Shadow trafficMirrored requests whose responses are discarded
Dark launchNew back-end behaviour called for real users without visible effect
Feature flagRuntime switch selecting a code path
OpenFeatureVendor-neutral feature flag API and SDKs (CNCF)
ProviderOpenFeature adapter to a flag system
Evaluation contextAttributes of the subject (targeting key, plan, country)
Targeting keyStable identity used for targeting and bucketing
Targeting rulesConditions on context attributes
Percentage rolloutSticky share of users by hash bucket
Kill switchPermanent operational flag to turn a feature off quickly
Flag debtCost of stale flags left in code
LaunchDarkly / Unleash / FlagsmithFeature flag products (SaaS / open source + hosted)
Laravel PennantLaravel's first-party feature flag package
Image digest pinningDeploying image@sha256:... instead of a tag
Revision historyOld ReplicaSets kept for rollback (revisionHistoryLimit)
kubectl rollout undoRestore a previous Pod template
Helm rollbackRe-apply a previous Helm release revision
GitOps revertRolling back by reverting the Git commit the controller syncs
Rollback windowArgo Rollouts: recent revisions skip steps on rollback
N-1 compatibilityEach version works with the previous version's schema and APIs
Expand/contractParallel change: add, migrate, then remove
Forward-only migrationsNo down migrations in production; fix with new migrations
Migration orderingExpand before the code switch, contract a release after
Release healthSLIs evaluated during and after a rollout
SLO-based promotionPromote only while SLIs stay within the SLO
Error budget burn rateSpeed of budget consumption relative to the SLO
Readiness gateExtra Pod condition required for readiness
preStopContainer hook run before SIGTERM
Connection drainingFinishing in-flight requests before closing
Immutable infrastructureReplace servers instead of changing them
AMIAmazon Machine Image: the VM release artefact
Instance refreshEC2 Auto Scaling rolling replacement with checkpoints and rollback
Symlink release switchAtomic current link swap between release directories
Capistrano / DeployerRelease-directory deploy tools (Ruby / PHP)
php-fpm reloadSIGUSR2 graceful reload of FPM workers
Laravel maintenance modeartisan down: 503 for all requests except bypass
Octane reloadoctane:reload: graceful restart of Octane workers
queue:restartSignal Laravel queue workers to exit after the current job
Smoke testsA few critical checks right after deploy
Synthetic monitoringScripted user journeys run continuously
Post-deploy verificationSmoke tests, version checks, metric checks after a deploy
Deployment freeze / change windowPeriods when deploys are blocked / allowed
RunbookWritten procedure for a deploy and its rollback
DORA metricsDeployment frequency, lead time, change fail rate, recovery time, rework rate

References ​

Built by Morteza Negahi