Skip to content

CI/CD and Deployment Strategies

Intermediate 54 min read Part 14 of 18

Ship code safely and often: CI/CD stages, rolling, blue-green, canary, shadow and A/B, feature flags, rollback, Terraform, GitOps and 12-factor.

Summary#

Continuous Integration (CI) means every developer merges small changes into the main branch often, at least daily. Each merge is automatically built and tested, so the main branch always works. Continuous Delivery (CD) goes further: every change that passes the pipeline is packaged as a deployable artifact, and promoted through environments automatically. Production release is then a button press. Continuous Deployment removes the button, so every green change goes to production on its own.

Deployment strategies control how a new version replaces the old one:

  • rolling replaces instances a few at a time;
  • blue-green switches all traffic between two full environments;
  • canary sends a small slice of traffic to the new version, and watches metrics before expanding;
  • shadow copies live traffic to the new version without returning its responses;
  • A/B testing splits users between variants, to measure a business outcome.

Feature flags separate deploying code from releasing a feature, so you can switch features on for 1% of users, or kill them instantly. Rollback is the plan for when things go wrong: redeploy the last good version, flip a flag, or roll forward with a fix. That only works if database and API changes stay backward-compatible.

Infrastructure as Code (IaC), with tools such as Terraform, describes servers, networks and databases in versioned files. A plan shows the diff before an apply makes it real. GitOps makes a Git repository the source of truth for what runs in a cluster, and an agent (Argo CD, Flux) continuously pulls and reconciles. Configuration management keeps settings out of code, validated, versioned and rolled out as carefully as code. The 12-factor app is a set of twelve rules (config in the environment, stateless processes, logs as streams, and more) that make services easy to build, deploy and scale this way.

Why It Exists#

Before CI/CD, teams released every few weeks or months. Code piled up on long-lived branches. "Integration week" meant merging conflicting changes and discovering that nothing worked together. Releases were manual runbooks of 80 steps executed at 2 a.m. by tired engineers. Each one bundled hundreds of changes, so when something broke, nobody knew which change caused it, and rolling back meant undoing everything.

The insight behind CI/CD is counter-intuitive: releasing more often is safer. Small changes are easier to review, test, reason about and undo. If a deploy contains one change and the error rate rises, you know exactly what to revert. Automation removes human error from the repetitive steps, and makes the process the same every time.

The research backs this up. The DORA research programme (summarised in Accelerate by Nicole Forsgren, Jez Humble and Gene Kim, 2018) found that high-performing teams deploy more often and have lower change failure rates and faster recovery. Speed and stability are not a trade-off when the pipeline is good. It measures delivery with four key metrics:

MetricWhat it measuresElite teams (roughly)
Deployment frequencyHow often you ship to productionOn demand, many times per day
Lead time for changesCommit to running in productionLess than a day
Change failure rateShare of deploys causing an incident or rollbackLow, around 0–15%
Time to restore serviceHow fast you recover from a failed changeLess than an hour

A second reason is changes cause most outages. Google's Site Reliability Engineering book (2016) notes that roughly 70% of outages are due to changes in a live system. If change is the main risk, then how you change, meaning progressively, observably and reversibly, is the main reliability lever.

How It Works#

CI/CD pipeline stages#

A pipeline is an automated sequence of stages. Each stage is a gate: if it fails, the change stops, and the author is told quickly. The order puts fast, cheap checks first, so most failures surface within minutes.

  1. Source. A push or pull request triggers the pipeline. Branch protection requires review and green checks before merging.
  2. Build. Compile the code, resolve dependencies from a lockfile, and produce artifacts. Build once, deploy many: the exact same artifact (a container image with an immutable digest) is promoted through every environment. Rebuilding per environment risks shipping something different from what you tested.
  3. Static checks. Linting, formatting, type checks, and static analysis (SAST) for security bugs.
  4. Unit tests. Thousands of fast, isolated tests, finishing in seconds to a few minutes.
  5. Integration tests. The service with its real dependencies (a database in a container, a fake of the payment API), and contract tests between services.
  6. Package and scan. Build the container image, generate a Software Bill of Materials (SBOM) listing every dependency, scan for known vulnerabilities (CVEs), sign the image, and push it to a registry.
  7. Deploy to staging (or an ephemeral preview environment per pull request). Run smoke tests and a small set of end-to-end tests.
  8. Production deploy. A progressive rollout, gated by automated health analysis and sometimes a manual approval for regulated systems.
  9. Post-deploy verification. Synthetic checks, SLO dashboards, and automatic rollback triggers. The pipeline doesn't end when the deploy finishes. It ends when the new version has proven healthy.

Continuous delivery vs continuous deployment. Both automate everything up to production. In continuous delivery, a human decides when to release, often because of business timing or compliance. In continuous deployment, every change that passes goes out automatically. Many large web companies do continuous deployment for most services. Banks and medical device firms often stop at delivery.

A minimal pipeline in GitHub Actions, as pipeline-as-code in the repository:

name: ci
on:
  pull_request:
  push: { branches: [main] }
jobs:
  build-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci                      # exact versions from lockfile
      - run: npm run lint && npm run typecheck
      - run: npm test -- --coverage
  image:
    needs: build-test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions: { contents: read, packages: write, id-token: write }
    steps:
      - uses: actions/checkout@v4
      - run: docker build -t ghcr.io/acme/checkout:${{ github.sha }} .
      - run: trivy image --exit-code 1 --severity CRITICAL ghcr.io/acme/checkout:${{ github.sha }}
      - run: docker push ghcr.io/acme/checkout:${{ github.sha }}
      - run: cosign sign --yes ghcr.io/acme/checkout:${{ github.sha }}   # keyless, OIDC identity
      # CD: a later job (or Argo CD Image Updater) bumps the tag in the GitOps repo

CI/CD pipeline stages, in depth: speed, the test pyramid, branching and flaky tests#

Pipeline speed is a feature. If CI takes 45 minutes, developers batch changes, context-switch, and stop running it locally. A common target is under 10 minutes for the pre-merge path. Techniques for keeping it there:

  • Caching: dependency caches keyed by the lockfile hash, Docker layer caches (BuildKit cache mounts, registry caches), and compiler caches.
  • Incremental and affected-only builds: in a monorepo, build tools with a dependency graph (Bazel, Nx, Turborepo, Pants) rebuild and retest only targets affected by the change, often with remote caching and remote execution shared across developers and CI. Google's internal monorepo and its build system (Blaze, open-sourced as Bazel in 2015) are the canonical example.
  • Parallelism and sharding: split the test suite across N runners by historical timing, so a 40-minute suite runs in 5 minutes on 8 shards.
  • Ordering: run the fastest and most-likely-to-fail checks first.

The test pyramid (a metaphor popularised by Mike Cohn) says to have many fast unit tests, fewer integration tests, and very few slow end-to-end (E2E) tests. E2E tests through a browser or across many services are slow, flaky and expensive to debug, so keep them for critical user journeys, such as signup, checkout and login. Contract tests (consumer-driven contracts, with tools like Pact) verify that service A's expectations of service B's API still hold, without starting both, which is essential in microservices.

Flaky tests pass and fail on the same code, because of timing, ordering, shared state or network dependence. They are corrosive. Developers learn to click "retry", and real failures get ignored. Handle them by:

  1. detecting them automatically (re-run failures, and flag tests whose result differs);
  2. quarantining them out of the blocking path, with an owner and a deadline;
  3. fixing the root cause: inject clocks, isolate state, and remove sleeps.

Google has published that a meaningful share of its tests show some flakiness, which is why its infrastructure tracks flakiness as a first-class metric.

Branching strategy.

  • Trunk-based development: everyone merges to main at least daily, via short-lived branches (hours to a day or two). Incomplete features hide behind feature flags. This is the strategy most associated with high DORA performance.
  • GitFlow: long-lived develop, release and hotfix branches. It suits software with versioned releases (desktop apps, libraries, firmware), but slows web services and creates merge pain.
  • Release branches: cut a branch per release for stabilisation, as mobile apps often do on a weekly train, because app-store review prevents instant rollback.

Merge queues. With hundreds of merges a day, two changes can each pass CI against an old main, and break when combined. A merge queue (GitHub merge queue, Bors, GitLab merge trains, Uber's SubmitQueue) tests each change on top of the changes ahead of it, and merges only if that combined state is green. It keeps main always green at high merge rates, at the cost of some queuing latency. Queues can speculatively test batches in parallel to recover throughput.

Environments. Classic pipelines use dev, then staging, then production. Modern teams add ephemeral preview environments per pull request (spun up in a namespace, torn down on merge) for realistic review, and keep staging as close to production as possible: same images, same IaC, smaller scale. However, staging never fully matches production traffic, data and scale, which is why progressive production rollouts with real-traffic analysis matter more than a perfect staging environment.

Artifact promotion. The artifact is identified by an immutable digest (sha256:...), and promoted by changing metadata (a tag, or a GitOps manifest) rather than rebuilt. That gives you traceability: for any running container, you can answer "which commit, which pipeline run, which tests, which dependencies". This chain of custody is what supply-chain frameworks such as SLSA formalise (see the deep dive on supply-chain security below).

Netflix's pipeline is a useful real-world model. Netflix built Spinnaker (open-sourced in 2015) as a multi-cloud continuous delivery platform that models pipelines as stages, bakes immutable machine images, and supports red-black (blue-green) and canary deployments with automated canary analysis. Netflix's broader engineering culture emphasises that each team owns its service's pipeline and production health, with the platform providing paved roads.

Deployment strategies: recreate, rolling, blue-green, canary, shadow and A/B#

A deployment strategy decides how traffic moves from version N to version N+1. Each one trades cost, speed, risk and complexity differently.

Recreate. Stop all old instances, then start the new ones. It's simple, and there's never a mix of versions, but it causes downtime. It's acceptable for dev environments, batch workers, or apps that can't run two versions at once (for example, a singleton that holds an exclusive lock).

Rolling update. Replace instances in small batches: take one (or a percentage) out of the load balancer, update it, wait for health checks, and continue. It is the default in Kubernetes (maxSurge and maxUnavailable) and in auto-scaling groups. It needs no extra capacity, and there's no downtime. The catch is that both versions serve traffic at the same time during the rollout, so they must be compatible. Rollback is just another rolling update, which takes as long as the rollout. The blast radius grows step by step, without automated analysis between steps, unless you add pauses.

Blue-green. Run two full environments. Blue serves production. Green gets the new version, is warmed up and tested in place, and then the router (load balancer, DNS or service mesh) switches all traffic to green at once. Blue stays idle as an instant rollback target, and is reused for the next release. Netflix calls its variant red-black. The benefits are instant cut-over and instant rollback, by switching back. The costs are double capacity during the switch, and an all-or-nothing switch: if green has a bug that only appears under real load, 100% of users see it. Shared databases complicate it, because both colours talk to the same schema. Long-lived connections (WebSockets) and DNS caching can make the "instant" switch gradual in practice.

Canary. Deploy the new version to a small subset (1%, then 5%, 25%, 50%, 100%), compare its health metrics against the baseline, and either promote or abort. The name comes from canaries in coal mines, which warned miners of gas before it harmed them. Canaries limit the blast radius to a small share of users, and test with real production traffic, which staging can't replicate. They require fine-grained traffic splitting (a service mesh, Gateway API weights, a load balancer with weighted target groups, or simply a few instances among many), good metrics, and patience (bake time).

Shadow (dark launch, traffic mirroring). Production traffic is copied to the new version, whose responses are discarded. Users only ever see the old version's responses. You compare latency, errors and even response bodies between the two. It is ideal for rewrites and migrations, such as a new search backend, a new pricing engine, or a language port, because you test at full production load with zero user impact. The hard part is side effects. A shadowed "charge card" or "send email" request must not execute for real. Shadow systems need stubbed downstream writes, a separate datastore, or read-only paths. They also double load on shared dependencies, so make sure those can take it.

A/B testing. Split users (not requests) into variants by a stable hash of user ID, show each group a different experience, and measure a business metric (conversion, retention, watch time) with statistical rigour. A/B testing answers "is the new version better?", while canary answers "is the new version safe?". It's usually implemented with feature flags or an experimentation platform rather than separate deployments, and it requires sticky assignment, so a user doesn't flip between variants.

StrategyDowntimeExtra capacityRollback speedBlast radiusVersions live at onceBest for
RecreateYesNoneSlow (redeploy)100%OneDev, batch, singletons
RollingNoSmall surgeSlow (roll back)Grows graduallyTwoDefault for stateless services
Blue-greenNo2× during switchInstant (switch back)100% at switchOne at a timeCritical services, simple fast rollback
CanaryNoSmallFast (shift weight to 0)Small, controlledTwoHigh-traffic services with good SLIs
ShadowNoUp to 2× for shadowNot needed (no user impact)Zero to usersTwo (one hidden)Rewrites, risky backends, performance tests
A/BNoSmallFlag offExperiment populationTwo or moreMeasuring product impact

Deployment strategies, in depth: canary analysis, bake time, wave rollouts and the database#

What to compare in a canary. Compare the canary against a baseline of the same size, started at the same time on the old version, rather than against the whole existing fleet. Long-running instances have warm caches, JIT-compiled code and different memory states, so a brand-new instance of the old code is the fair comparison. That's the approach used by Kayenta, the automated canary analysis tool Netflix and Google open-sourced together in 2018 (and integrated into Spinnaker). It compares metric distributions between baseline and canary with a nonparametric statistical test (Mann-Whitney U), classifies each metric as pass, high or low, and produces an overall score against a threshold.

Which metrics to compare.

  • Error rate: HTTP 5xx share and exception counts.
  • Latency percentiles: p50, p99.
  • Saturation: CPU, memory, GC pauses.
  • Business metrics: checkout success, plays started.
  • Downstream effects: errors returned by services the canary calls.

How long to bake. Some bugs appear only after a cache expires, a cron runs, memory leaks for an hour, or the daily peak arrives. Bake time trades speed for detection. A typical pattern is minutes for the first step, and longer (an hour or more) before going global, with extra caution near peak traffic. Many companies also impose deployment freezes during critical business periods, such as Black Friday or the year-end holidays.

Is the canary big enough to detect anything? Statistics limits what a small canary can see. Suppose the baseline error rate is 0.1%, and you want to catch a regression to 0.2%. At 5% of 2,000 RPS, the canary sees 100 RPS, which is 60,000 requests in 10 minutes. At 0.1%, you expect 60 errors, and at 0.2%, 120. The difference is clear, about 5 standard deviations given Poisson noise of about √60 ≈ 7.7. But a regression from 0.1% to 0.12% (72 vs 60 errors) is within noise. Low-traffic services need longer bakes, a larger canary fraction, or synthetic traffic. Rare-path bugs (a specific country, or a rarely used endpoint) may not appear in a canary at all, which is why per-segment metrics and fast rollback still matter.

Wave deployments. Large providers deploy in waves of increasing size, each with its own bake time:

  1. one instance (a "one-box" stage);
  2. one availability zone;
  3. one region;
  4. a few regions;
  5. everywhere.

The AWS Builders' Library article "Automating safe, hands-off deployments" describes this kind of pipeline, with automatic rollback on alarms at each stage. Combine it with cell-based architecture (High Availability Design), so a wave is a set of cells, and a bad change affects only the customers in those cells. Different regions should never receive a risky change at the same time, which keeps regions independent failure domains.

Session affinity and mixed versions. During rolling and canary deployments, a user's consecutive requests may hit v41, then v42, then v41. If v42 writes a cookie, cache entry or message format that v41 can't read, users see errors that look random. Rules: new versions must read old formats, and must not write new formats until all readers understand them (see the expand and contract pattern below). Or pin users to one version with sticky routing for the duration of the rollout.

Kubernetes specifics. A Deployment's rolling update gives a basic, instance-proportional canary: 1 new pod among 20 receives about 5% of traffic. For precise percentages, header-based routing and automated analysis, use Argo Rollouts or Flagger with a mesh or Gateway API (Containers and Kubernetes):

apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata: { name: checkout }
spec:
  replicas: 20
  strategy:
    canary:
      canaryService: checkout-canary
      stableService: checkout-stable
      trafficRouting: { istio: { virtualService: { name: checkout } } }
      steps:
        - setWeight: 5
        - pause: { duration: 10m }
        - analysis: { templates: [{ templateName: error-rate-and-p99 }] }
        - setWeight: 25
        - pause: { duration: 30m }
        - setWeight: 50
        - pause: { duration: 30m }
      # failed analysis aborts: weight returns to 0, stable keeps serving
  selector: { matchLabels: { app: checkout } }
  template:
    metadata: { labels: { app: checkout } }
    spec:
      containers:
        - name: app
          image: ghcr.io/acme/checkout@sha256:4f1c...   # deploy by digest

Blue-green details. The switch can happen at several layers:

  • DNS, which is slow and unreliable, because resolvers and clients cache records beyond their TTL;
  • a load balancer listener or target-group swap, which is fast;
  • a Kubernetes Service selector change (version: blue to version: green), which is fast;
  • mesh weights, which are fast and can be gradual.

Warm green up before the switch: fill caches, JIT, and connection pools. Drain blue gracefully after the switch. Keep blue around until you're confident, then scale it down to save cost. A common hybrid is blue-green with canary: deploy green, shift 5% of traffic to it, then 100%, keeping blue for instant rollback.

Feature flags#

A feature flag (feature toggle) is a runtime switch in code, if (flags.isOn("new-checkout", user)), whose value comes from a flag service rather than from the deploy. It decouples deployment from release. Code can ship to production dark (turned off), and be turned on later, for specific users, or gradually, without another deploy.

Kinds of flags (Pete Hodgson's widely cited taxonomy on martinfowler.com):

TypePurposeLifetimeExample
Release toggleHide incomplete or unreleased features; enable trunk-based developmentDays to weeks, then deleteNew checkout page behind new-checkout
Experiment toggleA/B or multivariate testsDuration of the experimentTwo recommendation ranking variants
Ops toggle (kill switch)Turn off expensive or failing features under loadLong-livedDisable "similar items" widget when the recommender is slow
Permission toggleEnable features for specific customers or plansLong-livedBeta programme, enterprise-only feature

How flag evaluation works. Evaluating a flag on every request with a network call to a flag service would add latency and a hard dependency. Instead, SDKs:

  1. fetch all flag rules at startup;
  2. keep them in memory;
  3. receive updates by streaming (Server-Sent Events or long polling) or periodic polling;
  4. evaluate rules locally, in microseconds.

Rules can target user attributes (country, plan, internal staff), allow-lists, or percentage rollouts. Percentage rollouts must be sticky: hash (flagKey, userId) to a number in 0–99, and enable the flag if that number is below the rollout percentage. Raising from 10% to 20% keeps the first 10% enabled, and adds a new 10%. Including the flag key in the hash makes different flags select different user subsets, so the same unlucky 10% of users don't get every experiment.

import { createHash } from "crypto";
 
type Rule = { attribute: string; values: string[] };
type Flag = { key: string; enabled: boolean; rules: Rule[]; rolloutPercent: number };
 
function bucket(flagKey: string, userId: string): number {
  const h = createHash("sha256").update(`${flagKey}:${userId}`).digest();
  return h.readUInt32BE(0) % 10000;          // 0..9999, sticky per flag and user
}
 
export function isEnabled(flag: Flag | undefined, user: Record<string, string>): boolean {
  if (!flag || !flag.enabled) return false;  // unknown or killed flag: safe default
  for (const r of flag.rules) {              // explicit targeting wins
    if (r.values.includes(user[r.attribute])) return true;
  }
  return bucket(flag.key, user.id) < flag.rolloutPercent * 100;
}
 
// flags live in memory; a streaming client replaces this map on every update
// isEnabled(flags.get("new-checkout"), { id: "u_829", country: "IN", plan: "pro" })

Feature flags, in depth: flag debt, failure modes and the Knight Capital lesson#

Flags are technical debt with interest. Every flag doubles the code paths through that section. Ten independent flags create 1,024 combinations nobody has tested. Release flags must be removed after full rollout. Teams set expiry dates, create a cleanup ticket when the flag is created, have linters flag stale flags, and run dashboards of flags at 100% for more than 30 days. Long-lived ops and permission flags are fine, but should be documented and owned.

The flag service is a dependency. Design for its failure:

  • SDKs keep serving the last known rules if the service is unreachable;
  • they start with bundled defaults if they can't fetch at boot;
  • defaults should be the safe, old behaviour.

Never make a critical path depend on a synchronous remote flag call. Treat flag changes as production changes: audit-log who changed what, require approval for sensitive flags, and roll out percentage increases gradually, with the same monitoring as code deploys. A flag flip that sends 100% of traffic to an untested path is just a deploy without the safety net.

Knight Capital, 2012. This is a famous cautionary tale, documented in the US SEC's order against the firm. During a deploy of new trading code, one of eight servers did not receive the update. A repurposed flag activated the new feature on the seven updated servers, but on the old server, the same flag triggered long-dead legacy code ("Power Peg"), which began sending a flood of orders into the market. In about 45 minutes, the firm lost roughly $460 million, and needed a rescue. The lessons map directly onto this page:

  • automate deployments, so they are complete and verified on every server;
  • never reuse a flag name for new behaviour;
  • delete dead code;
  • monitor and alert on anomalous behaviour, with a fast kill switch.

Testing with flags. Test both states of each active flag, at least the default-off and target-on states, in CI. For risky combinations, add explicit tests. Run the production default configuration in staging. OpenFeature (a CNCF project) standardises the flag-evaluation API across vendors (LaunchDarkly, Flagsmith, Unleash, cloud offerings), so application code isn't locked into one SDK.

Experiments need rigour. Flags make A/B tests easy to run, and also easy to get wrong. Common mistakes:

  • peeking: stopping the test the moment it looks significant, which inflates false positives;
  • sample ratio mismatch: a 50/50 split that ends up 52/48, signalling a bug in assignment or logging;
  • novelty effects;
  • testing too many metrics without correction.

The deep dive below covers the maths. Large experimentation platforms (Microsoft's ExP, Booking.com, Netflix) run thousands of experiments a year, and have published extensively on these pitfalls. Trustworthy Online Controlled Experiments by Ron Kohavi, Diane Tang and Ya Xu (2020) is the standard reference.

Rollback#

Rollback returns production to the last known-good state when a change misbehaves. Mean time to recover depends far more on how quickly you can roll back than on how quickly you can debug. Rollback first, debug later. Options, fastest first:

  1. Flip the feature flag off, in seconds, without any deploy. It's possible when the change was flag-guarded.
  2. Shift traffic back: canary weight to 0, or the blue-green switch back. Seconds.
  3. Redeploy the previous artifact: the previous image digest, or a git revert of the GitOps manifest. This takes minutes, depending on rollout speed. Since artifacts are immutable and kept, the old version is always available.
  4. Roll forward: ship a fix quickly, through the same pipeline. This is appropriate when rollback is impossible (for example, a data migration already ran), or when the fix is trivial and well understood. It's risky under pressure, so pipelines need a fast path that still runs the essential checks.

Automatic rollback. Pipelines should roll back without waiting for a human, when canary analysis fails, or when alarms fire (error-rate or latency SLO burn, crash loops, failed health checks) during or shortly after a deploy. The faster the detection and the reaction, the smaller the impact. A deploy that is rolled back in 3 minutes, affecting 5% of traffic, costs about 0.15 "full-outage minutes" of error budget, compared with 30 minutes at 100% for a manual rollback after a page.

What rollback can't undo.

  • Database schema and data migrations. If v42 dropped a column, rolling back to v41, which reads that column, fails. If v42 wrote data in a new format, v41 may not understand it.
  • Messages and events already published in a new schema to Kafka or queues, which consumers may now choke on (Kafka).
  • External side effects: emails sent, payments captured, calls to partners.
  • Client releases: mobile apps in users' hands can't be rolled back. You have to stay backward compatible with old app versions for months.
  • Caches filled with new-format entries.

The cure is backward- and forward-compatible changes, applied in multiple steps, so that every version in production can run against every schema version that's live at the same time.

Rollback, in depth: expand and contract, compatibility windows and rollback drills#

The expand and contract pattern (also called parallel change) is the backbone of zero-downtime schema changes. Renaming users.fullname to users.display_name the naive way (ALTER TABLE ... RENAME COLUMN) breaks every running instance of the old version immediately. In expand and contract, each phase is a separate deploy, and each is independently roll-back-able:

  1. Expand: ALTER TABLE users ADD COLUMN display_name TEXT NULL. In PostgreSQL, adding a nullable column without a volatile default is a quick metadata change (PostgreSQL).
  2. Dual write: the app writes both columns, and still reads fullname.
  3. Backfill: UPDATE users SET display_name = fullname WHERE display_name IS NULL AND id BETWEEN ..., in batches of, say, 10,000 rows, with pauses, to avoid long locks, replication lag and WAL bloat.
  4. Switch reads: the app reads display_name, falling back to fullname if it's null. Keep dual writes.
  5. Stop old writes, after the rollback window (perhaps a week).
  6. Contract: drop fullname in a later release, once no running or rollback-target version reads it.

Operational hazards of migrations.

  • Long-running ALTER TABLE statements that take an exclusive lock queue behind long transactions, and then block every query behind them. Use lock_timeout and retries.
  • Creating indexes should use CREATE INDEX CONCURRENTLY in Postgres.
  • On MySQL, online schema change tools (gh-ost from GitHub, pt-online-schema-change) copy the table in the background, and swap.
  • Run migrations as a separate pipeline step before the code that needs them, not inside app startup, where 20 pods race to run the same migration (Containers and Kubernetes covers the init-container trap).

Compatibility windows. Define how many versions can coexist. Typically N and N+1 during a rollout, and N-1 as a rollback target. So code at version N+1 must work with the schema at version N, and code at version N must work with the schema at version N+1. For APIs: add fields, never remove or repurpose them within the window, and make readers tolerant of unknown fields (protobuf and Avro are designed for this, with schema registries enforcing compatibility rules). For events: version the schema, and keep consumers able to read old and new.

Rollback drills. A rollback path you've never exercised will fail when you need it. Regularly roll back a harmless deploy in production, to keep the path fast and to verify that old artifacts, old configs and old migrations still work. Measure the "time to rollback" as an SLO for the platform itself.

Roll back or roll forward?

  • Roll back when the cause is unclear, the impact is large, or the previous version is known-good and compatible.
  • Roll forward when rollback is unsafe (data already migrated, or partners already integrated), the fix is small and understood, and your pipeline can deliver it in minutes.
  • Never "fix forward" by SSH-ing into servers and editing files. That creates drift no pipeline knows about.

Infrastructure as code with Terraform#

Infrastructure as Code (IaC) means describing infrastructure (networks, load balancers, databases, DNS records, IAM roles, Kubernetes clusters) in text files that are versioned in Git, reviewed in pull requests, and applied by tools. Clicking through a cloud console (ClickOps) is unrepeatable, unreviewable and undocumented. IaC makes environments reproducible: staging and production are built from the same code with different variables, and a region can be rebuilt from scratch during disaster recovery.

Declarative vs imperative. Imperative tools (shell scripts, the AWS CLI, early Ansible playbooks) list steps: "create a VPC, then create subnet A". Declarative tools (Terraform, CloudFormation, Pulumi's model, Kubernetes manifests) describe the desired end state: "there is a VPC with these subnets", and compute the steps themselves. Declarative definitions are idempotent: applying the same code twice changes nothing the second time.

How Terraform works.

  1. Write configuration in HCL (HashiCorp Configuration Language): resource blocks for things to create, data blocks to read existing things, variable and output blocks, and module blocks to reuse groups of resources.
  2. terraform init downloads providers: plugins that translate resources into API calls for AWS, GCP, Azure, Kubernetes, Cloudflare, Datadog, GitHub and thousands more.
  3. terraform plan reads the state (Terraform's record of what it has created, with real IDs), refreshes it against the cloud's real resources, and builds a dependency graph from references: a subnet references a VPC ID, so the VPC comes first. It then diffs desired against actual, and shows what it would create, update in place, or destroy and recreate.
  4. terraform apply executes the plan, walking the graph and creating independent resources in parallel. It records results in the state.
  5. State locking prevents two people or pipelines applying at once and corrupting the state.
terraform {
  backend "s3" {
    bucket       = "acme-tfstate-prod"
    key          = "network/eu-west-1.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true          # S3-native state locking in recent Terraform versions
  }
}
 
provider "aws" { region = "eu-west-1" }
 
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"            # pin module versions
  name    = "prod"
  cidr    = "10.20.0.0/16"
  azs             = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
  private_subnets = ["10.20.0.0/19", "10.20.32.0/19", "10.20.64.0/19"]
  public_subnets  = ["10.20.96.0/22", "10.20.100.0/22", "10.20.104.0/22"]
  enable_nat_gateway = true
}
 
resource "aws_db_instance" "orders" {
  identifier          = "orders-prod"
  engine              = "postgres"
  instance_class      = "db.r6g.xlarge"
  allocated_storage   = 500
  multi_az            = true
  storage_encrypted   = true
  deletion_protection = true     # plan cannot silently destroy it
  db_subnet_group_name = aws_db_subnet_group.orders.name   # implicit dependency
}

Infrastructure as code, in depth: state, drift, blast radius and the IaC landscape#

State is the crux. Terraform's state maps each resource address (aws_db_instance.orders) to a real cloud ID, plus the attributes it last saw. Rules for handling it:

  • Keep it remote (S3, GCS, Azure Blob, or Terraform Cloud and HCP), encrypted, versioned and locked.
  • Treat it as sensitive: it can contain plaintext secrets, such as generated passwords and private keys.
  • Never edit it by hand. Use terraform state mv, import and removed and moved blocks for refactors.

Losing the state means Terraform no longer knows it owns those resources. It would try to create duplicates.

Splitting state to limit blast radius. One giant state for an entire company means every plan touches thousands of resources, takes minutes, and a mistake can destroy anything. Split it by layer and environment: network, then data stores, then compute and applications, then DNS, per environment and region. Pass values between layers with outputs, remote-state data sources, or parameter stores. Smaller states give faster plans, clearer ownership, and limited damage.

Plan review is the safety gate. A plan that shows -/+ destroy and then create replacement for a database is a red flag. Some attribute changes force replacement (changing a DB's identifier, a subnet's CIDR, or some encryption settings). Protect critical resources with prevent_destroy lifecycle rules and cloud-side deletion protection. Apply exactly the saved plan that was reviewed (terraform plan -out then apply on that plan), so nothing changes between review and apply.

Policy as code. Automatically reject plans that violate rules before anyone applies them: no public S3 buckets, encryption required, approved instance types only, required tags for cost allocation. Tools include OPA and Conftest, HashiCorp Sentinel, Checkov, tfsec and Trivy for misconfiguration scanning, and cloud-native ones such as AWS Config rules.

Drift. Someone edits a security group in the console during an incident, and now reality differs from code. Run scheduled terraform plan jobs to detect drift, alert on it, and either codify the change or revert it. Restrict console write access in production, so drift is rare and deliberate (break-glass procedures, with audit).

The IaC landscape.

ToolModelFits when
Terraform / OpenTofuDeclarative HCL, multi-cloud providers, state fileMulti-cloud or SaaS-heavy estates; the most widely used IaC tool. OpenTofu is the Linux Foundation fork created after HashiCorp moved Terraform to the Business Source License in 2023
AWS CloudFormation / CDKDeclarative templates managed by AWS; CDK generates them from TypeScript, Python and othersAWS-only shops wanting AWS-managed state and rollback
PulumiReal programming languages (TS, Python, Go) generating a declarative graphTeams who want loops, types and tests in a general-purpose language
Azure Bicep / ARM, Google Infrastructure ManagerCloud-native declarative templatesSingle-cloud Azure or GCP shops
CrossplaneKubernetes CRDs that provision cloud resources, reconciled continuouslyPlatform teams offering self-service infrastructure through the Kubernetes API and GitOps
Ansible, Chef, Puppet, SaltConfigure software on existing servers (packages, files, services)Mutable VMs, on-prem fleets, OS-level configuration
PackerBuilds machine images (AMIs)Immutable VM images for auto-scaling groups

Immutable vs mutable infrastructure. Classic configuration management tools (Puppet, Chef, Ansible) converge long-lived servers towards a desired state. Over time, servers accumulate differences ("snowflakes"). Immutable infrastructure never modifies running servers. You bake a new image (a container or VM image), deploy new instances, and delete the old ones. Containers made this the default. Configuration-management tools remain useful for building images, for bare-metal and network devices, and for legacy estates.

Testing IaC. Use terraform validate and fmt in CI, run policy checks on the plan JSON, and use ephemeral test environments created and destroyed by automated tests (Terratest, or terraform test in recent versions). A plan diff posted as a pull-request comment (Atlantis, Terraform Cloud, Spacelift, env0) makes reviews effective.

GitOps#

GitOps applies CI/CD ideas to operations: a Git repository holds the declarative desired state of a system, and software agents continuously reconcile the running system to match it. The OpenGitOps project (under the CNCF) defines four principles:

  1. Declarative: the desired state is expressed declaratively, as Kubernetes manifests, Helm values, or Kustomize overlays.
  2. Versioned and immutable: the state is stored in a way that keeps full history, which in practice means Git.
  3. Pulled automatically: agents pull the desired state from the source, rather than CI pushing into the cluster.
  4. Continuously reconciled: agents keep observing actual state, and correct drift.

Push vs pull. In push-based CD, the CI system runs kubectl apply or helm upgrade against the cluster, so CI needs cluster admin credentials, which is a juicy target. In pull-based GitOps, an agent inside the cluster (Argo CD or Flux) watches the Git repo, and applies changes. Credentials never leave the cluster, and every change to production is a Git commit with an author, a review and a timestamp. Rollback is git revert. Drift (someone runs kubectl edit) is detected, shown as "OutOfSync", and optionally reverted automatically (self-heal).

The flow. The flow uses two repositories, or two folders: application source and environment configuration.

  1. CI builds the image from the app repo, and pushes checkout@sha256:....
  2. CI, or an image-updater bot, opens a pull request to the config repo, bumping the image digest in envs/staging/checkout/values.yaml.
  3. After merge, Argo CD syncs staging. Automated tests pass.
  4. A promotion pull request bumps envs/prod/..., and Argo CD syncs prod, often through Argo Rollouts for a canary.

GitOps, in depth: repository layout, secrets, fleets and failure modes#

Repository layout. Common patterns:

  • App-of-apps or ApplicationSets in Argo CD: one root application that generates applications per service and environment, or per cluster, from a template.
  • Kustomize overlays: base/ plus overlays/staging and overlays/prod, which patch replicas, resources and config.
  • Helm umbrella charts with values files per environment.

Keep environment configuration separate from application source. Otherwise every config change triggers app CI, and every app commit risks an unintended deploy. Avoid long-lived branches per environment. Folders per environment on main are easier to diff and promote between.

Secrets in GitOps. Git must never contain plaintext secrets. Options:

  • External Secrets Operator or the CSI secrets store: Git holds a reference, and the secret lives in Vault or a cloud secrets manager;
  • Sealed Secrets or SOPS: Git holds ciphertext that only the cluster or KMS can decrypt.

See Security Fundamentals.

Ordering and dependencies. CRDs before custom resources, namespaces before workloads, database migration Jobs before the Deployment that needs them. Argo CD's sync waves and hooks (PreSync, Sync, PostSync), and Flux's dependsOn, express ordering.

Fleets. With many clusters (per region or cell), ApplicationSets or Flux generate per-cluster applications from cluster labels. Progressive delivery across a fleet means promoting a change cluster by cluster or wave by wave, not merging one commit that every cluster syncs simultaneously. A bad commit to a shared base, synced by 50 clusters in the same minute, is a global outage. Use staged folders, or promotion tooling, to make waves explicit.

Failure modes.

  • Git or the Git host down: the clusters keep running their last applied state. Only changes are blocked. Mirror critical repos.
  • Argo CD down: same. Nothing is reverted, but drift isn't corrected either.
  • Emergency changes: during an incident, someone needs to scale up now. Either commit quickly (and have the pipeline fast enough), or pause auto-sync for that application, change it live, and then commit the change back. Never leave the cluster silently out of sync.
  • Fields owned by controllers: HPA-managed replicas should be ignored in diffs (ignoreDifferences), or removed from the manifest, otherwise GitOps and the HPA fight forever.

GitOps beyond Kubernetes. The same pattern drives infrastructure (Crossplane, or Terraform controllers that reconcile from Git), and even configuration of network devices. The key ideas, Git as the source of truth, pull-based reconciliation and drift detection, apply to any system with a declarative API.

Configuration management#

Configuration is everything that varies between deploys or over time while the code stays the same: database URLs, timeouts, pool sizes, feature flags, rate limits, routing rules, allow-lists, and topology. Configuration changes are code changes in disguise, and they cause a large share of outages. So they need the same discipline: versioning, review, validation, staged rollout and rollback.

Layers of configuration.

LayerExamplesChanged byPropagation
Build-timeCompiler flags, bundled defaultsCode commitNew artifact
Deploy-time (static)DB host, credentials reference, replica count, resource limitsGitOps commit, environment variables, ConfigMapsRestart or rollout
Runtime (dynamic)Feature flags, rate limits, timeouts, kill switches, routing weightsConfig service or flag UI, with auditPushed to running processes in seconds
SecretsPasswords, API keys, TLS keysSecrets manager, rotationMounted files or SDK fetch, reloaded on rotation

Infrastructure topology is configuration too. Take a Redis deployment. You choose between a single node (simplest, no failover), a primary with an HA replica (failover, read replicas, but asynchronous replication can lose the last acknowledged writes on failover), or a cluster that shards keys over 16,384 hash slots across nodes. With a cluster, the "configuration" a client needs is the slot-to-node map. Clients cache it, compute each key's slot, and connect directly to the right node. If a slot moves during rebalancing or failover, the server answers MOVED, and the client refreshes its map. Nodes gossip the cluster state among themselves, but they don't proxy requests. This is a good model of distributed configuration in general: clients hold a cached view, the server side is the source of truth, and there's an explicit invalidation signal when the view is stale (Redis). Topology choices, such as whether reads can go to replicas, or which keys share a hash tag such as {user:123} to stay on one node, belong in reviewed configuration, because they change correctness and failure behaviour.

Dynamic configuration services. For runtime config, processes subscribe to a config store, and apply changes without restart:

  • ZooKeeper: store config in a znode, such as /config/checkout/timeouts. Clients read it and set a watch. When the znode changes, ZooKeeper sends a one-time notification, and the client re-reads the data and sets a new watch. Writes go through the leader, and ZAB consensus gives every client the same order of updates. This pattern long powered configuration in Hadoop, HBase, Kafka (before KRaft) and many in-house systems (ZooKeeper and etcd).
  • etcd: keys with revisions. Clients watch a key or prefix from a revision, and receive every change in order, without missing any. This is how Kubernetes components see config changes.
  • Consul KV, with blocking queries and consul-template; Spring Cloud Config; AWS AppConfig (with validators and staged deployment of config); Azure App Configuration; Google Cloud Runtime Configurator and Firebase Remote Config.
  • Flag platforms for feature flags (LaunchDarkly, Unleash, Flagsmith).

Configuration management, in depth: config as code, safe propagation and outage lessons#

Facebook's Configerator. The SOSP 2015 paper "Holistic Configuration Management at Facebook" (Chunqiang Tang and others) describes a system where all config is code in Git. Configs are written in a language that compiles and validates them (with schema checks and user-defined validators), go through code review, are canary-tested on a subset of servers with automated health checks, and are then distributed through a ZooKeeper-like tree to proxies on every server. Facebook reported that configuration changed at a rate comparable to, or higher than, code commits. The paper's lesson is that config deserves more safety, not less, because a single value can affect every server instantly.

Common configuration failure modes, and defences.

FailureDefence
Typo or invalid value (timeout 3000 meant as ms, read as seconds)Typed schemas with units (timeout_ms), range validation in CI and on load
Valid but harmful value (pool size 10,000 exhausts the DB)Canary config changes on a subset, watch metrics, staged rollout like code
Global instant push takes down everythingWaves by region or cell; "config bake time"
A process crashes on bad config, then restarts and reads it again (crash loop)Validate before swapping in; keep last-known-good in memory and on disk; reject bad updates
Config store outage blocks startupCache last-known-good locally; bundle safe defaults; don't make the store a hard boot dependency
Thundering herd: 50,000 clients re-read after one changePush deltas, use local proxies or caches, add jitter to re-reads
Nobody knows which config version is liveExport config_version as a metric, and log it with every change

Real incidents illustrate the point.

  • On 2 July 2019, Cloudflare deployed a new WAF rule with a regular expression that caused catastrophic backtracking. Because WAF rules were pushed globally at once, CPU spiked to 100% across its network, causing a global outage of about 27 minutes. Its post-mortem led to staged rollouts for rules, and a regex engine without backtracking.
  • In July 2024, a faulty content configuration update for CrowdStrike's Falcon sensor, pushed to Windows hosts globally without staged rollout, crashed about 8.5 million machines (Microsoft's estimate). It's another example of a "data, not code" change that needed canarying.

Static config: files and environment variables. For deploy-time config, prefer environment variables or mounted files, per the 12-factor app below. Kubernetes ConfigMaps mounted as files update in place (after a delay), while environment variables require a restart. Many teams roll pods on config change, by hashing the ConfigMap into a pod annotation, so a config change becomes an ordinary, observable, roll-back-able rollout. That's often preferable to hot reload for anything except truly dynamic settings.

Classic configuration management (Puppet, Chef, Ansible, Salt) also deserves its name here. These tools manage the software configuration of servers: packages, files, users, services, and kernel settings. Agents (Puppet, Chef) periodically converge each node to a declared state. Agentless tools (Ansible) push changes over SSH. In container-centric estates, much of this moved into Dockerfiles and IaC, but these tools still manage VM fleets, network gear and the base images themselves.

The 12-factor app#

The Twelve-Factor App is a methodology published in 2011 by Adam Wiggins and colleagues at Heroku, at 12factor.net. It distils the practices that make web services portable, easy to deploy continuously, and easy to scale horizontally on any platform. It predates Docker and Kubernetes, yet reads like their design spec.

#FactorWhat it meansIn today's terms
1CodebaseOne codebase per app, tracked in version control, many deploysOne repo (or monorepo folder) per service; the same commit runs in every environment
2DependenciesExplicitly declare and isolate dependenciesLockfiles; everything in the container image; no reliance on host packages
3ConfigStore config in the environment, not in codeEnv vars, mounted ConfigMaps and Secrets; no environment-specific builds
4Backing servicesTreat databases, queues and caches as attached resourcesSwap a local Postgres for RDS by changing a URL, with no code change
5Build, release, runStrictly separate the three stagesBuild an image once; release = image plus config, with an ID; run = execute it
6ProcessesRun the app as stateless processes; state lives in backing servicesNo sticky sessions or local files; sessions in Redis; uploads to object storage
7Port bindingThe app is self-contained and exports HTTP by binding a portContainer listens on 8080; no external app server injection
8ConcurrencyScale out via the process modelMore replicas, different process types (web, worker) scaled independently
9DisposabilityFast startup and graceful shutdownStart in seconds; handle SIGTERM, drain, finish or requeue work
10Dev/prod parityKeep development, staging and production as similar as possibleSame images and IaC everywhere; small time gap between writing and deploying
11LogsTreat logs as event streams written to stdoutThe platform ships logs to ELK, Loki or a cloud service; the app never manages log files
12Admin processesRun one-off admin tasks as one-off processes in the same environmentMigrations as Kubernetes Jobs using the same image and config

The 12-factor app, in depth: why each factor matters for CI/CD, and what's changed since 2011#

Why the factors enable safe delivery.

  • Build, release, run and config make build once, deploy many possible: the same artifact goes to every environment, with only config differing. So what you tested is what you run, and rollback is just "run release N-1".
  • Processes, concurrency and disposability make rolling and canary deploys and autoscaling safe, because any instance can be killed and replaced at any moment without losing state.
  • Dev/prod parity reduces "works in staging" surprises.
  • Logs as streams lets the platform, not each app, handle aggregation, so observability works uniformly.
  • Backing services as attached resources makes failover and migration a config change.

What's evolved.

  • Secrets in environment variables are discouraged now. They leak into crash dumps, child processes and ps-style tooling. Prefer mounted files or secrets-manager SDKs with rotation, while keeping the spirit of "config outside code".
  • Config in the environment is extended by dynamic configuration and feature flags for runtime changes. The factor describes deploy-time config.
  • Telemetry, security and API-first were proposed as additional factors, for example in Kevin Hoffman's Beyond the Twelve-Factor App (O'Reilly, 2016). Modern additions in the same spirit include exposing health endpoints (liveness and readiness), emitting metrics and traces via OpenTelemetry, and defining contracts with OpenAPI or protobuf.
  • Stateful workloads (databases, Kafka) don't fit factor 6, and aren't meant to. They are the backing services, usually managed services or operators.
  • Dev/prod parity is now achieved with containers, IaC and ephemeral environments, not by running everything locally. With dozens of services, local development often uses remote dev environments, or service virtualisation.

When to Use It#

CI is close to universal. Any team with more than one developer, or any code that runs in production, benefits from automated build and test on every change. Beyond that, the level of investment depends on the signals.

  • Continuous delivery (every green build is deployable, with one-click release): use it for essentially all services. The upfront cost is a pipeline and IaC. The payoff is boring, repeatable releases.
  • Continuous deployment (no human gate): use it when tests and production monitoring are trustworthy, rollback is fast, and changes are small. That suits most web backends and SaaS products. Pair it with feature flags.
  • Canary and automated analysis: use it for services with enough traffic to produce statistically meaningful signals (hundreds of requests per second or more), and an SLO that matters. Payments, checkout, login, and core APIs.
  • Blue-green: when you need instant, whole-version rollback; when two versions can't easily coexist behind a load balancer; or for infrastructure-like components (a gateway, or a database proxy) where partial rollouts are awkward.
  • Shadow traffic: for rewrites, migrations to a new datastore or engine, or performance validation of a new version at full production load.
  • Feature flags: for trunk-based development, for gradual releases of user-facing features, for kill switches on expensive features, and for experiments.
  • IaC: for every cloud resource that matters, from the first production environment. Retrofitting IaC onto a hand-built estate is much harder than starting with it.
  • GitOps: when you run Kubernetes (or another declarative platform), want an audit trail of every production change, and want to keep cluster credentials out of CI.

When NOT to Use It#

  • Full continuous deployment for regulated or safety-critical software (medical devices, avionics, some banking systems). Regulations may require human sign-off, validation records, and release windows. Keep CI and continuous delivery, and gate production with approvals.
  • Canary analysis on very low-traffic services. At 1 request per second, a 5% canary sees 3 requests a minute, and analysis is noise. Use synthetic traffic, longer bakes, or blue-green with good smoke tests instead.
  • Shadow traffic for write-heavy, side-effecting paths, unless you can fully isolate writes. Shadowing "place order" against a shared database or payment provider will double-charge.
  • Blue-green for large stateful systems. Duplicating a 20 TB database for each release isn't practical. Blue-green the stateless tier, and evolve the schema with expand and contract.
  • Feature flags for everything. Small bug fixes and refactors don't need flags, and every flag adds a branch to test and remove later. Don't use flags as a long-term configuration system without ownership.
  • GitOps for highly dynamic, imperative operations, such as autoscaled replica counts, per-request routing decisions, or second-by-second tuning. Those belong to controllers or dynamic config, not Git commits.
  • Heavy IaC abstraction for a throwaway prototype. A one-week spike can be ClickOps. But anything that will reach production gets codified before it does.

How to Implement It#

  1. Start with trunk-based development and CI on every pull request: lint, unit tests, a build, under 10 minutes. Protect main.
  2. Build once, with immutable artifacts: container images tagged with the commit SHA, deployed by digest, plus an SBOM, a vulnerability scan and a signature.
  3. Codify infrastructure (Terraform or OpenTofu, Pulumi, or CDK) with remote, locked, encrypted state, split by layer and environment, a plan on every pull request, policy checks, and apply only from the pipeline.
  4. Adopt GitOps for deployments: a config repo with environment overlays, Argo CD or Flux in each cluster, and promotion by pull request.
  5. Define SLIs and SLOs first (Observability), then add progressive delivery that uses them: canary steps, automated analysis, automatic rollback, and waves across regions or cells.
  6. Add feature flags with an SDK that evaluates locally, safe defaults, an audit log, and flag-expiry hygiene.
  7. Make database changes backward compatible (expand and contract), and run migrations as explicit pipeline steps.
  8. Practise rollback: time it, drill it, and make it one command or one click.
  9. Measure DORA metrics (deploy frequency, lead time, change failure rate, time to restore) and pipeline duration. Improve the slowest step.

A deploy-gate controller that promotes or rolls back based on SLO signals, as pseudo-code:

type Step = { weight: number; bakeMinutes: number };
const steps: Step[] = [ { weight: 1, bakeMinutes: 10 }, { weight: 10, bakeMinutes: 20 },
                        { weight: 50, bakeMinutes: 30 }, { weight: 100, bakeMinutes: 0 } ];
 
async function progressiveRollout(release: string): Promise<"promoted" | "rolled_back"> {
  for (const step of steps) {
    await router.setWeight(release, step.weight);
    const deadline = Date.now() + step.bakeMinutes * 60_000;
    while (Date.now() < deadline) {
      const c = await metrics.compare({ canary: release, baseline: "stable", windowMin: 5 });
      const bad = c.errorRateRatio > 1.5 || c.p99Ratio > 1.3 || c.crashLoops > 0
               || (await alarms.anyFiring(release));
      if (bad) {
        await router.setWeight(release, 0);        // stop the bleeding first
        await deployer.scaleDown(release);
        await notify(`rollback ${release}: ${JSON.stringify(c)}`);
        return "rolled_back";
      }
      await sleep(30_000);
    }
  }
  await deployer.markStable(release);              // becomes the next baseline
  return "promoted";
}
TechnologyFits when
GitHub Actions / GitLab CI / Jenkins / CircleCI / BuildkiteGeneral CI pipelines; Jenkins for self-hosted, plugin-heavy setups; Buildkite for self-hosted runners at scale
Bazel / Nx / Turborepo / GradleFast incremental builds with remote caching, especially in monorepos
Argo CD / FluxPull-based GitOps delivery to Kubernetes
Argo Rollouts / FlaggerCanary and blue-green on Kubernetes with automated metric analysis
SpinnakerMulti-cloud CD with pipelines, canary analysis (Kayenta), VM and Kubernetes targets
AWS CodeDeploy / CodePipeline, Google Cloud Deploy, Azure DevOpsCloud-native pipelines and deployment strategies on one provider
Terraform / OpenTofu / Pulumi / CloudFormation / CDKInfrastructure as code
Atlantis / Terraform Cloud / SpaceliftPlan-on-PR and controlled apply workflows for IaC
LaunchDarkly / Unleash / Flagsmith / OpenFeature / AWS AppConfigFeature flags and runtime configuration
Statsig / Optimizely / GrowthBook / EppoExperimentation and A/B testing with statistical analysis
Trivy / Grype / Snyk, Syft, CosignVulnerability scanning, SBOM generation, signing
gh-ost / pt-online-schema-change / Flyway / Liquibase / AtlasOnline schema changes and versioned migrations

Trade-offs#

OptionProsConsPick when
Continuous deploymentFastest feedback; tiny changes; no release ceremonyNeeds excellent tests, monitoring and rollbackWeb services and SaaS with mature pipelines
Continuous delivery with manual gateHuman judgement; compliance evidenceSlower; batches grow; gate becomes a rubber stampRegulated industries, coordinated launches
RollingNo extra capacity; built inMixed versions; slow rollback; no analysis by defaultDefault for stateless services
Blue-greenInstant switch and rollback; one version liveDouble capacity; all-or-nothing exposureCritical services, incompatible versions
CanarySmall blast radius; real-traffic validationTooling for traffic split and analysis; slowerHigh-traffic, SLO-critical services
ShadowZero user impact at full loadSide effects need isolation; doubles loadRewrites, engine migrations, performance tests
Feature flagsDecouple deploy from release; instant killFlag debt; combinatorial testing; a runtime dependencyTrunk-based development, gradual releases, experiments
Push-based CDSimple; works for any targetCI holds production credentials; drift unnoticedNon-Kubernetes targets, small setups
Pull-based GitOpsAudit trail; no credentials in CI; drift correctionExtra components; emergency changes need a processKubernetes fleets, compliance-sensitive orgs
Terraform / OpenTofuMulti-cloud, huge provider ecosystemState management burden; HCL limitsMost cloud estates
Cloud-native IaC (CloudFormation, CDK, Bicep)Provider-managed state and rollbackSingle cloudAll-in on one provider
Static config with restartSimple; every change is a normal rolloutSlower changesMost settings
Dynamic config serviceInstant changes without deploysA global blast radius if unvalidated; extra systemKill switches, rate limits, tuning knobs

Common Pitfalls#

  • Rebuilding artifacts per environment, so production runs something never tested. Build once, promote by digest.
  • A slow, flaky pipeline. Developers batch changes, and ignore failures. Treat pipeline time and flakiness as metrics with owners.
  • Deploying to all regions at once. Use waves, with bake time between them.
  • Canarying without automated analysis. "We'll watch the dashboard" fails at 3 a.m. Encode the comparison and the rollback.
  • Comparing the canary against the whole fleet instead of a fresh baseline. Cold-start effects create false alarms, or hide real regressions.
  • Schema changes that break the previous version, such as dropping or renaming columns in one step. Rollback then becomes impossible.
  • Shadowing writes into shared systems: duplicate payments, emails or messages.
  • Feature flags that never die, or reused flag names. That's the Knight Capital lesson.
  • Config pushed globally and instantly, without validation or canary. That's the Cloudflare 2019 and CrowdStrike 2024 lesson.
  • Terraform state on a laptop, unencrypted, unlocked, or shared through Git. That leaks secrets and corrupts state.
  • ClickOps hotfixes in production that never get codified, so the next apply silently reverts them.
  • GitOps versus the HPA, where both "own" replicas, so they fight.
  • Secrets in pipeline logs, or long-lived cloud keys in CI. Use OIDC federation for short-lived credentials, and log masking.
  • Deploying on Friday evening with nobody watching. The real problem is lack of automated detection and rollback. Fix that, and the day matters less.

Real-World Examples#

  • Amazon described a deployment every 11.6 seconds on average across its production systems (Jon Jenkins, O'Reilly Velocity, 2011). Its Builders' Library describes pipelines that deploy in waves (one box, then one AZ, then regions) with automatic rollback on alarms, and bake times between stages.
  • Netflix built Spinnaker, open-sourced in 2015, for multi-cloud continuous delivery with red-black deploys. With Google, it open-sourced Kayenta for automated canary analysis in 2018. Netflix popularised shadowing (traffic replay) for testing major migrations.
  • Google's SRE book describes progressive rollouts and canarying as core practices, and notes that roughly 70% of outages stem from changes to live systems. Google builds from a monorepo, with Blaze/Bazel.
  • Facebook (Meta) manages configuration as code with Configerator, and gates features with Gatekeeper, per the SOSP 2015 paper. Code and config changes are canaried on employees and small server sets first.
  • Etsy was an early, public champion of continuous deployment (its "Deployinator" tool, and many deploys per day), and of a culture of blameless post-mortems.
  • Knight Capital (2012), Cloudflare (2019) and CrowdStrike (2024) are canonical failures of, respectively, incomplete deployments with flag reuse, globally instant rule rollout, and a globally instant content update. Each led to industry-wide emphasis on staged, verified rollouts.
  • Heroku published the Twelve-Factor App (2011) from its experience running large numbers of apps on its platform.

Case studies that use this pattern#

  • Payment System: zero-downtime schema migrations, canaries on payment success rate, idempotency so retries during rollouts are safe.
  • Stock Exchange: strict release controls, deterministic replays to validate new versions, kill switches.
  • News Feed: feature flags and A/B experiments on ranking, shadow scoring of new models.
  • ChatGPT-style Assistant: shadow and canary rollouts of new model versions, with quality and latency guardrails.
  • Metrics Monitoring: the SLI pipeline that canary analysis and automatic rollback depend on.

In the Interview#

Deep Dive: The statistics behind canaries and A/B testsShow

Canary as hypothesis testing. The null hypothesis is that the canary behaves like the baseline. You reject it if a metric differs beyond what noise explains. Two kinds of errors matter:

  • false positives roll back good releases, and erode trust in the system;
  • false negatives ship bad ones.

The number of comparisons is large: dozens of metrics, each checked every minute, across several steps. Without correction, something will look significant by chance. With 50 independent metrics at α = 0.05, the chance that at least one is a false alarm is 1 − 0.95⁵⁰ ≈ 92%. Practical systems handle this in several ways:

  • use effect-size thresholds (for example, "error rate at least 1.5× baseline and statistically significant"), not significance alone;
  • classify metrics as critical (any failure aborts) or advisory, which add up to a score;
  • use nonparametric tests (Mann-Whitney U, as in Kayenta) for skewed latency distributions;
  • require sustained deviation across consecutive windows.

Detectable effect size. For a rate metric with baseline p, and n canary requests, the standard error is about √(p(1−p)/n). To detect an absolute increase of δ with a two-sided test at α = 0.05 and 80% power, you need roughly n ≈ 2(1.96 + 0.84)² · p(1−p) / δ² requests per arm. For p = 0.1% and δ = 0.1% (a doubling), n ≈ 2 · 7.84 · 0.000999 / 0.000001 ≈ 15,700 requests per arm, which is minutes at 100 RPS. For δ = 0.02% (a 20% relative increase), you need 25× more, about 390,000 requests: over an hour at 100 RPS. This is why low-traffic services can only catch large regressions with canaries, and why rare-path monitoring and fast rollback remain essential.

A/B tests add product-metric rigour. Experiments typically:

  • pre-register the primary metric;
  • compute the sample size from the minimum detectable effect;
  • run for full weekly cycles, to average out day-of-week effects;
  • avoid peeking, or use sequential testing methods (such as always-valid p-values or group-sequential designs) that permit early stopping;
  • check sample ratio mismatch with a chi-squared test on assignment counts;
  • reduce variance with pre-experiment covariates (CUPED, introduced by Deng, Xu, Kohavi and Walker at Microsoft in 2013), which can cut required sample sizes substantially.

They also watch guardrail metrics (latency, crash rate, revenue) to catch harm, even when the primary metric improves.

Interference. A/B tests assume one user's treatment doesn't affect another's. Social networks, marketplaces (ride-hailing supply), and ad auctions violate this. Platforms then randomise by cluster (city, time slice, or graph cluster), using "switchback" experiments in marketplaces. Canary analysis has a similar issue: a canary that hammers a shared database hurts the baseline too, so comparisons understate the damage. Watch shared-dependency health separately.

Deep Dive: Deploying stateful, long-lived and client-side systemsShow

Databases. You don't blue-green a 20 TB primary. Instead:

  • schema changes use expand and contract;
  • engine upgrades use replicas: upgrade a replica, fail over to it, then upgrade the old primary;
  • major migrations use logical replication or change data capture (CDC) into the new cluster, then a dual-read comparison, then a cut-over with a short write freeze, or dual writes with reconciliation.

Managed services (RDS blue/green deployments, Cloud SQL maintenance) automate parts of this. The cut-over is still the riskiest moment, so rehearse it on a production-sized copy.

Message consumers and Kafka. Rolling a consumer group triggers rebalances. Each pod leaving or joining reassigns partitions, which pauses consumption. Mitigations:

  • cooperative incremental rebalancing;
  • static group membership, so a restart within the session timeout keeps its partitions;
  • rolling slowly.

Producers and consumers must agree on schemas through a registry, with compatibility rules, so new producers never emit messages old consumers can't parse during the rollout (Kafka). For stream processors (Flink), upgrades take a savepoint, deploy the new job from the savepoint, and keep the old savepoint for rollback. State schema changes need the same care as database migrations.

Long-lived connections. WebSocket, gRPC streaming and MQTT servers hold connections for hours. A deploy that kills pods disconnects thousands of clients at once, and they all reconnect together (a thundering herd). Mitigations:

  • drain gradually: stop accepting new connections, then close existing ones over minutes, with jittered reconnect hints;
  • keep enough capacity for reconnect spikes;
  • for very large fleets, roll slowly, in small batches.

See Real-time Communication and the Chat System case study.

Caches and serialised data. If v42 writes cache entries in a new format, v41 (still live during rollout, or after rollback) may crash reading them. Version cache keys (user:v2:123) or the payload format, and make readers tolerant. The same applies to session cookies, JWT claims, and anything else persisted by one version and read by another.

Mobile and desktop clients. Releases go through app-store review, adoption takes weeks, and old versions live for years. So:

  • server APIs must remain backward compatible with every supported client version;
  • release trains (weekly or biweekly) replace continuous deployment;
  • staged rollouts in the app stores (for example, 1%, then 5%, then 20%) provide canaries;
  • server-side feature flags and remote config let you turn features off without shipping a new binary;
  • minimum-version enforcement handles the rare cases where old clients must be cut off.

Edge and device fleets. CDN configs, IoT firmware, and endpoint agents (the CrowdStrike lesson) must be rolled out in rings, from internal devices to a small external ring to everyone, with telemetry gates and the ability to stop and revert. Firmware adds A/B partitions, so a failed boot falls back to the previous image automatically.

Deep Dive: Software supply-chain security in the pipelineShow

Why the pipeline is a target. A compromised build system injects malicious code into signed, trusted artifacts that every customer installs.

  • In the SolarWinds attack (disclosed December 2020), attackers modified the Orion build process, so legitimate signed updates carried a backdoor to thousands of organisations.
  • The xz utils backdoor (discovered March 2024) was planted through a long social-engineering campaign by a maintainer persona, and hidden in release tarballs and build scripts. It was caught by chance, by an engineer investigating SSH login latency.
  • Dependency confusion attacks (demonstrated publicly by Alex Birsan in 2021) published public packages with the names of companies' internal packages, which build tools then preferred.

SLSA (Supply-chain Levels for Software Artifacts, from the OpenSSF) defines increasing levels of build integrity:

  • the build is scripted and produces provenance, a signed statement of what source, builder and parameters produced an artifact;
  • provenance is generated by a hosted, hardened build platform, not the developer's machine;
  • builds are isolated and tamper-resistant, so one build can't influence another, and secrets aren't exposed to user-defined steps.

Consumers verify provenance before deploying.

Signing and verification. Sigstore's cosign signs container images, using either keys or keyless signing tied to a CI identity through OIDC (for example, "this was built by the GitHub Actions workflow release.yml in repo acme/checkout on main"). Signatures are recorded in the Rekor transparency log. Admission controllers in Kubernetes (Kyverno, Sigstore policy-controller) refuse to run images that aren't signed by the expected identity. SBOMs (SPDX or CycloneDX, generated by Syft and other tools) list every component, so when the next Log4Shell (December 2021) appears, you can answer "where are we affected?" in minutes, not weeks.

Pipeline hardening checklist.

  1. Pin dependencies by lockfile hashes, and pin CI actions by commit SHA, not mutable tags.
  2. Use OIDC federation for short-lived cloud credentials, instead of long-lived keys stored as CI secrets.
  3. Grant least-privilege tokens per job, such as read-only by default.
  4. Don't run untrusted pull-request code with secrets. Forks get no secrets.
  5. Mirror and scan dependencies through an internal proxy registry. Reserve internal package names on public registries.
  6. Use reproducible builds where possible, so independent rebuilds can verify artifacts. Debian and Nix have invested heavily in this.
  7. Protect branches, with required reviews (two-person rule for release configs) and signed commits for sensitive repos.
  8. Separate build and deploy permissions. The thing that builds can't deploy to production by itself. Deployment requires provenance verification.

These measures are cheap compared with the cost of shipping a compromised artifact to every server, or every customer, through your own trusted pipeline.

Key Takeaways#

  • CI merges small changes often and verifies each one automatically. Continuous delivery keeps every green build releasable. Continuous deployment releases it automatically. Small, frequent changes are safer, as the DORA research shows.
  • Pipeline stages go from cheap to expensive: build, static checks, unit tests, integration and contract tests, package, scan and sign, staging, progressive production rollout, post-deploy verification. Build once, promote by digest. Keep it under about 10 minutes, and kill flakiness.
  • Deployment strategies: rolling is the default, blue-green gives an instant switch and rollback, canary gives small blast radius and real-traffic analysis, shadow gives zero-impact load testing (beware side effects), and A/B measures business impact. Deploy in waves across cells and regions.
  • Feature flags decouple deploy from release. Evaluate them locally, use sticky hashing for percentages, have safe defaults, audit changes, and delete flags after rollout.
  • Rollback first, debug later: flag off, shift traffic, or redeploy N-1. That only works with backward-compatible schema, API, message and cache changes. Use expand and contract for schemas.
  • IaC with Terraform: declarative code, plus plan and apply, plus remote, locked, encrypted state. Split state to limit blast radius, use policy as code, detect drift, and apply only from pipelines.
  • GitOps: Git is the source of truth, and in-cluster agents pull and reconcile, giving an audit trail, easy rollback, drift correction, and no production credentials in CI.
  • Configuration changes are code changes. Validate them, canary them, roll them out in waves, keep last-known-good, and know which version is live. ZooKeeper and etcd watches push dynamic config to clients.
  • The 12-factor app (config in the environment, stateless disposable processes, logs as streams, build/release/run separation, dev/prod parity) is the design that makes all of the above work.