Skip to main content

Chapter 38 — CI/CD, Infrastructure as Code & Deployment Strategies

Part VII · Delivery | Prerequisites: Ch 35–Ch 37 | Builds: Pulsely's pipeline — gated CI, IaC, canary/blue-green with zero-downtime migrations

You have spent the last three chapters earning everything a deploy needs: a test suite that gates change (Ch 35), an immutable container that runs the same everywhere (Ch 36), and a cloud topology of failure domains and identities to run it on (Ch 37). This chapter is where they meet. It answers the last operational question in the book: how does a commit become production, safely, repeatably, and reversibly? In a system that holds patient charts, "become production" carries extra weight — a bad deploy can drop a claim, lose a lab order, or expose PHI, and the last two are reportable events, not just bugs. By the end you'll be able to draw the path from a git push to live traffic the same way you can draw the request spine — naming every gate, what it costs, and how it fails — and you'll know why a senior engineer's highest compliment for a deploy is that it was boring.

This is the chapter that makes deploying a non-event. We do that by making it deterministic, gating it on quality, and — the part most teams skip — decoupling the act of deploying code from the act of releasing behavior to users.


1. The problem: deploying by hand, and the deadlock it hides​

It's Friday, 16:40. Pulsely's clinical-orders service — the one that submits lab orders, e-Rx, and referrals — needs a one-line hotfix shipped before the weekend. The on-call engineer SSHes into the production box, runs git pull && npm ci && pm2 restart, watches the logs scroll, and goes home. Twenty minutes later order submission starts returning 500s and a clinic can't send its afternoon labs. The box was running Node 20.11; staging was on 20.14; a native dependency (a package with compiled C code inside it, not pure JavaScript) got reinstalled and recompiled against a slightly different system C library — libc, the low-level C library the operating system ships — producing a subtly different binary that crashed on this box but not on staging. It's the server-side twin of shipping a React bundle that was transpiled against a different Node than the one your tests ran on: same source, different machine underneath, different behavior. Nobody noticed because nobody was looking. The fix that took thirty seconds to write took four hours and a ruined evening to recover from.

Pull that story apart and you find four distinct diseases, each of which this chapter cures.

The artifact that was tested is not the artifact that shipped. CI built and tested something on the branch. Then the deploy box ran npm ci again, fresh, and pulled a newer transitive patch release that CI never saw. "It passed on the branch" was true and irrelevant — green and live were different bytes. Any time the thing you validate and the thing you run are produced by separate builds, your tests are guarding a ghost.

The deploy was a snowflake. The production box had drifted — a manual hotfix here, a leftover node_modules there, a Node minor nobody upgraded. No two servers were byte-identical, so "it works on staging" carried no information about prod. Configuration that lives in the heads of operators instead of in a file is configuration you cannot reproduce, review, or roll back.

Rollback was slower than the incident. "Roll back" meant "redeploy the previous git SHA," which re-ran npm ci and re-ran the migration — twelve minutes, during an outage, with the clock running. A recovery path slower than the failure it recovers from is not a recovery path; it's a second outage you opt into.

And the quietest, nastiest one — a deadlock between schema and code. A week earlier, someone shipped a feature that added a NOT NULL column to clinical_orders inside the deploy. During the rollout, old app instances were still writing rows without the column and crash-looped; new instances couldn't start until the column existed. The schema change blocked the old code; the old code blocked the schema change. The deploy wedged itself, half-up, in a state neither version could escape. Nobody designed this deadlock — it emerged because two things that evolve on independent timelines were forced to change in the same instant.

There's a fifth disease underneath all of these, and it's conceptual. Release and deploy were fused. The only way to get that Friday hotfix to users was to ship the entire branch — including half-finished care-team worklist code sitting in the same trunk. Every deploy was an all-or-nothing bet on everything merged since the last one. When deploying is the only lever for releasing, you can never ship small.

🧭 The reframe. A deploy is not an event you perform; it is the output of a machine you build once. The machine takes a commit and emits a running, validated, reversible production change, with no human typing commands into a prod box and no decision made under outage pressure. Your job this chapter is to build that machine — and then to make sure releasing behavior is a separate, smaller, faster lever than deploying code.


2. The mental model: a conveyor of gates, a desired-state document, and two timelines​

Hold five pictures. The first three describe getting code to prod; the last two describe doing it without downtime.

A pipeline is a conveyor of quality gates. Picture a factory line. A candidate artifact rides the belt, and at each station a gate inspects it: does it build, do the tests pass, is it free of known vulnerabilities, is it packaged and signed? A gate is not a warning — it is a stop. Fail one and the belt halts; the candidate never reaches the next station. This is the same membrane logic you met at the very start of the book, turned inward: instead of validating a request before it touches durable state, you validate an artifact before it touches production.

Build once, promote the same bytes. The artifact — a container image identified by its sha256 digest — is created exactly once, at the start of the line, and is thereafter immutable. The same digest flows dev → staging → prod. Environments differ only by injected config and secrets, never by a rebuild. This single rule kills the "tested ≠ shipped" disease at the root: there is only one artifact, so green and live cannot diverge.

🔑 The promotion invariant. What you test is what you ship is what you run. One build, one immutable digest, promoted unchanged across every environment. The instant a deploy step contains npm install, docker build, or "pull latest," you have broken this invariant and reintroduced drift. Config is the variable; the artifact is the constant — the same theme you saw for the container runtime, now enforced across the whole delivery path.

Infrastructure is a desired-state document, not a runbook. You don't script "create a load balancer, then a database, then wire them." You declare the end state you want to exist, and a reconciler computes the diff between that declaration and reality, then closes it. The code is the truth; the cloud is a cache of that truth that may have drifted. This is exactly the orchestrator's reconciliation loop you've already met, lifted up from "N healthy pods" to "an entire VPC, its databases, and its IAM roles."

Deploy ≠ release. Deploy means the code is present and running in production. Release means users actually see its behavior. These are different events, and a feature flag is the valve between them. You can deploy code that is dormant — shipped but dark — and release it later by flipping a flag, to 1% of users first, with a kill switch. Fusing the two (as our Friday story did) is why teams fear deploys; separating them is the single highest-leverage move in this chapter.

Schema and code evolve on two independent timelines. During any gradual rollout, old code and new code run at the same time against one shared schema. Both must tolerate the shape the other reads and writes. You cannot change the column and the code that uses it in the same instant — that's the deadlock from §1. The discipline that keeps the timelines compatible is expand/contract, and it is the spine of zero-downtime deploys.

🧭 Mental model. A deployment strategy is a function over one curve: blast radius versus confidence. How much production traffic sees the new version before you trust it? Rolling replaces instances gradually (everyone, a few at a time). Blue-green runs two full stacks and flips atomically (nobody, then everybody, in one switch). Canary sends a sliver first — 1% — watches, then widens (a controlled few, then more, then all). Every strategy is just a different shape of "expose slowly enough to catch a problem before it's everyone's problem."


3. Theory & invariants​

A model tells you how to picture delivery; invariants tell you what must stay true or the machine quietly breaks. These are the load-bearing rules.

First, get the two halves of "CI/CD" straight, because people slur them together and the distinction matters.

CI — Continuous Integration — is the discipline that every change is merged to trunk frequently and validated against trunk by an automated pipeline. The pipeline is the single source of truth for "is this mergeable?" The enemy CI defeats is the long-lived branch that diverges for three weeks and detonates on merge.

CD is two different things wearing one acronym, and you must pick deliberately:

  • Continuous Delivery: every green build is deployable — but a human presses the button. The pipeline gets the artifact to the doorstep of prod and waits.
  • Continuous Deployment: every green build deploys to prod automatically, no human gate.

You choose per service, not per org. A stateless read API with strong canary analysis can deploy continuously; a claims/billing service touching money and a payer may keep a human button for a long time. Maturity of your tests and observability decides which you've earned.

🔑 The reversibility invariant. Any release must be revertible faster than your time-to-detect a problem. If you can detect a bad release in two minutes, you must be able to undo it in less. A change that cannot be cheaply reverted — because it destroyed data or broke a contract — is not a release; it is a migration, and migrations must be made safe by construction (expand/contract), because you have given up the right to simply undo them.

That invariant forces the rest of the theory.

Artifact immutability and provenance. One artifact, one content hash, content-addressable. Tag it with the build's git SHA and provenance metadata (who built it, from what commit, with what inputs) — never with a moving pointer like latest. The digest is the promotion handle; it is also what lets rollback be instant (§5), because the previous good version still exists, unchanged, addressable by its hash.

Idempotency of deploys and IaC apply. Running the same deploy or the same terraform apply twice converges to the same state — the second run is a no-op, not a doubling. This is the same idempotency property you met for message handlers, now applied to infrastructure: a reconciler that wasn't idempotent would be unusable, because you could never safely re-run it after a partial failure.

The compatibility window. During a rolling or canary deploy, version N and version N+1 of your code run simultaneously against one schema and one message bus. Therefore both versions must read and write shapes the other tolerates — N+1 must not write a row N can't read, and must not require a field N never sends. This N-1/N compatibility is not optional politeness; it is the precondition that makes gradual rollout possible at all, and it extends to event schemas on your bus (Ch 27).

Expand/contract is how you keep the two timelines compatible. This chapter owns expand/contract as the deploy-coordination protocol — the choreography of migration steps against code rollouts. The SQL-level safety of each DDL statement (which ALTERs lock, which rewrite the table, how to add a constraint without a long lock) is owned by Ch 19; cite it, don't re-derive it. The phases:

EXPAND ──▶ MIGRATE/BACKFILL ──▶ SWITCH READS ──▶ CONTRACT
add nullable dual-write old flip reads to drop the old
column; new + new; backfill the new column column / code;
code tolerates existing rows in once backfill no reader left
both shapes throttled batches is verified depends on it

The defining property: every phase is independently deployable and safe to halt between. You can stop after EXPAND and sit there for a week. Each transition is backward-compatible, so a rollback at any point lands on code that still works against the schema as it currently is.

🔑 The health-gate invariant. Promotion is conditional on observed system health, not on elapsed time. A canary widens from 1% to 25% because its error rate, latency, and saturation stayed within threshold relative to the baseline during a bake window — not because thirty seconds passed. The SLIs and traces you've already defined for the service are the inputs to this control loop. A deploy without a health gate is a deploy that finds its bugs in your users.

Finally, the vocabulary to make the rest of the chapter precise: pipeline/stage/job (the line, a phase, a unit of work); runner/agent (the machine executing a job); artifact/registry (the built thing, where it's stored); plan vs apply (compute the infra diff vs. enact it); state/lock (IaC's record of reality, and the mutex — a do-not-disturb sign only one caller can hold — protecting it); drift (reality diverging from the declared state); blast radius (how much is exposed to a bad change); bake time (how long you watch before widening); canary analysis (the metric comparison that judges a canary); kill switch (the instant-off lever for a flag or a rollout).


4. Under the hood: from git push to live traffic​

Let's walk the conveyor once, station by station, with just enough mechanics to kill the magic — the same way you walked the request spine at the start of the book.

push ─▶ BUILD ─▶ TEST ─▶ SCAN ─▶ PACKAGE ─▶ [registry] ─▶ DEPLOY(dev→staging→prod)
tsc unit SAST image sha256:… reconcile + canary
Docker +integ. +deps +sign (immutable) + health gate
+contract +IaC

The pipeline definition is code in the repo. Here is the shape in GitHub Actions; the same DAG-of-jobs concept exists in GitLab CI, CircleCI, and Buildkite. Note needs: — it makes the gates a directed graph, so nothing wasteful runs until its predecessor is green.

# .github/workflows/deliver.yml
name: deliver
on:
push: { branches: [main] }
permissions:
id-token: write # for OIDC → AWS, no static keys (see §8)
contents: read

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '20.14', cache: 'npm' } # cache keyed on package-lock.json
- run: npm ci # lockfile-exact, deletes node_modules — never `npm install`
- run: npm run build # tsc/esbuild → dist/

test:
needs: build
runs-on: ubuntu-latest
services: # ephemeral real infra for integration tests
postgres: { image: postgres:16, env: { POSTGRES_PASSWORD: test }, ports: ['5432:5432'] }
redis: { image: redis:7, ports: ['6379:6379'] }
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run test:unit # fast, parallel
- run: npm run test:integration # against the real Postgres/Redis above
- run: npm run test:contract # contracts vs the lab & clearinghouse partners

Build. npm ci (not npm install) installs exactly the lockfile, deleting node_modules first — the determinism guarantee you built into the container image. Then tsc/esbuild compiles to dist/. The base image is pinned by digest, not a floating tag, or "the same Dockerfile built twice" silently diverges.

Test — the gates that build on your test suite. Unit first (fast, parallel, fail-fast — don't spin containers if logic is red), then integration against ephemeral real Postgres and Redis spun up as CI services, then contract tests. In a clinical system those contracts are doing real work: they pin the shape of the messages you exchange with external partners — the HL7v2/FHIR lab-result feed, the X12 837/835 clearinghouse traffic, the eligibility 270/271 — so that a partner's schema drift fails here, in CI, and not the first time a real lab result comes back malformed in production. You gate on coverage delta and flake quarantine, never raw test counts (a flaky test retried three times to pass is a failing gate wearing a green hat). This is the same layered suite you built earlier, now wired as blocking stations on the line.

Scan — the gate juniors skip. Each is blocking, with a documented severity threshold:

  • SAST: lint + semgrep for code-level vulnerabilities.
  • Dependency CVEs: npm audit / trivy on the lockfile and the built image.
  • Secret scanning: catch a key someone pasted into a commit.
  • IaC scan: tfsec/checkov on the Terraform/CDK — e.g. a security group open to 0.0.0.0/0, a public S3 bucket, or an unencrypted volume fails here, before it ever reaches AWS.
  • License check: no surprise GPL in a proprietary build.

Package — build the immutable artifact, once. The multi-stage Dockerfile from your container build produces a slim, non-root image. CI pushes it to a registry and captures the digest (sha256:…). That digest — not a tag — is the promotion handle for the rest of the line.

package:
needs: [test] # implicitly also needs scan via the DAG
runs-on: ubuntu-latest
outputs: { digest: ${{ steps.push.outputs.digest }} }
steps:
- uses: aws-actions/configure-aws-credentials@v4
with: { role-to-assume: ${{ secrets.ECR_PUSH_ROLE }}, aws-region: us-east-1 } # OIDC
- id: push
run: |
IMAGE=$ECR/pulsely-orders
docker build -t $IMAGE:${{ github.sha }} .
docker push $IMAGE:${{ github.sha }}
echo "digest=$(docker inspect --format='{{index .RepoDigests 0}}' $IMAGE:${{ github.sha }})" >> $GITHUB_OUTPUT
- run: cosign sign --yes $IMAGE@${{ steps.push.outputs.digest }} # provenance: prod admits only this

cosign sign attaches a signature so that production can verify at admission that it only runs digests this pipeline produced — closing the supply-chain loop (§8).

The IaC engine — desired state, applied. The deploy stage doesn't ssh anywhere; it reconciles infrastructure. Pulsely is an AWS + TypeScript shop, so we use the CDK to stay in TS; the model is identical to Terraform's, only the authoring ergonomics differ.

// infra/orders-service.ts — declare the desired state; CDK synthesizes CloudFormation
const service = new ecs.FargateService(this, 'OrdersService', {
cluster,
taskDefinition: orders, // references the image DIGEST passed in from CI
desiredCount: 6,
circuitBreaker: { rollback: true }, // auto-rollback a failed ECS deployment
healthCheckGracePeriod: Duration.seconds(30),
});
const tg = new elbv2.ApplicationTargetGroup(this, 'OrdersTG', {
vpc, port: 3000, targetType: TargetType.IP,
healthCheck: { path: '/readyz', interval: Duration.seconds(10) }, // readiness gates traffic
});
service.attachToApplicationTargetGroup(tg);

The Terraform contrast, so the concept — plan (compute diff) → apply (enact) → state (recorded reality) — is concrete:

resource "aws_ecs_service" "orders" {
name = "pulsely-orders"
task_definition = aws_ecs_task_definition.orders.arn # pins the image digest
desired_count = 6
deployment_controller { type = "CODE_DEPLOY" } # blue-green via CodeDeploy
}

State management — the part that bites you. Terraform keeps a state file mapping each declared resource to its real cloud ID — this aws_ecs_service.orders block corresponds to that ARN. Without the mapping, the tool can't tell "create a new service" from "update the existing one," so the state file is load-bearing, not a cache you can delete. It's also sensitive — it can hold secrets and full resource attributes, and in a healthcare shop it must never be allowed to contain PHI — so it must never be committed to git; it lives in a remote backend: S3 stores the file, DynamoDB holds a lock.

The lock is the whole game. A lock here is a mutex — in plain terms, a do-not-disturb sign that only one apply can hold at a time. Without it, picture two teammates both hitting "Deploy" in the same minute. Each reads the old state. Each computes its changes as if it were the only one running. Then they write over each other — and the tool's record and the real cloud end up permanently out of sync, reality and the tool's picture of reality disagreeing, so you spend a day reconciling by hand with import. That's why the lock (DynamoDB) matters just as much as the state file (S3). (CDK keeps the equivalent state inside CloudFormation, which serializes applies for you — one fewer footgun, at the cost of being CloudFormation-bound and inheriting its slower, sometimes opaque diffs.) When you adopt a resource that already exists outside the tool, you import it into state rather than letting the tool try to recreate it and collide.

Deployment execution — the three strategies, mechanically.

  • Rolling is the orchestrator's default: ECS/Kubernetes replaces tasks a few at a time, honoring maxSurge/maxUnavailable, and routes traffic to a new task only once its readiness probe passes. Cheap (no extra capacity), but produces a mixed-version window and rolls back slowly (you must roll forward to the old version).
  • Blue-green stands up a second, identical "green" stack beside the live "blue," runs smoke tests against green privately, then swaps the load balancer / target group in one atomic flip. Rollback is the reverse flip — seconds. Cost: ~2× capacity during the cutover, and it's awkward when a stateful change can't run two versions at once.
  • Canary uses weighted routing (ALB weighted target groups or a service mesh) to send 1% → 5% → 25% → 100% of traffic to the new version, with automated canary analysis comparing canary metrics to the baseline at each step before widening.

Migrations under the hood. A migration runner (node-pg-migrate, Prisma Migrate; the JVM analog is Flyway/Liquibase) executes versioned, forward-only scripts and records each in a ledger table, so the database knows exactly which migrations have run. The transferable principle from the Flyway world: migrations are versioned code with a checksum and a ledger — not ad-hoc SQL someone pastes into a prod console. And the DDL itself is not free. On older Postgres, ALTER TABLE … ADD COLUMN … NOT NULL DEFAULT could rewrite the entire table: Postgres copies every existing row in order to write the new column's value into each one — and while it copies, an exclusive lock blocks every read and write to that table. On a busy chart or orders table that means every query stacks up behind the migration and the app effectively freezes. Newer Postgres avoids the copy by recording the default once as metadata, making a defaulted add a fast metadata-only operation. Which ALTER locks, which rewrites, and how to add a constraint with NOT VALID + VALIDATE to avoid a long lock — that SQL-safety detail is Ch 19's to own; here we only need the consequence: the migration is a separate, carefully-ordered step, not a line in the app's startup.

🛑 What we deliberately did not explain. The internal DAG scheduler of a CI runner and how it provisions ephemeral VMs; the full CloudFormation/Terraform graph-resolution algorithm; the exact lock semantics of every Postgres DDL statement (Ch 19); the service-mesh data plane that implements weighted routing; and the statistical methods behind sophisticated automated canary analysis. We located each on the conveyor and named what it does. The point of an under-the-hood beat is to remove magic, not to reimplement the tools.


5. In production: the zero-downtime migration, end to end​

The pieces above are the parts list. Here is how they assemble into the move that separates engineers who deploy from engineers who operate: shipping a schema change to a live, high-traffic system with zero downtime and an instant rollback path. We'll ship Pulsely's real increment — adding a clinical_orders.priority_code column (routine vs STAT on a lab or e-Rx order, a small coded field the order form lets a provider pick) — through the full expand/contract dance, decoupled by a flag, gated by health. This is a live table full of PHI that clinics write to all day, so "zero downtime" here also means "no window where an order is lost or an order read fails."

One pipeline, many environments, by promotion. The exact image digest CI produced is pinned per environment; only config is injected at deploy (env vars / SSM Parameter Store / Secrets Manager). Staging and prod therefore run identical bytes against different databases and secrets — the promotion invariant made operational. A protected main branch with required status checks and a merge queue keeps trunk always-green, and only the pipeline — never a human at a prod box — performs the deploy.

The migration runs as its own pipeline step, ordered around the app rollout — never inside it. This is the discipline that dissolves the §1 deadlock. EXPAND runs before the new app rolls; CONTRACT runs after, in a later deploy, once nothing reads the old shape. Walk the column through:

  1. EXPAND. A migration step adds priority_code as nullable (or with a safe default), and the new code is written to tolerate both priority_code = NULL and a populated value. Deploy the new code via canary. Both versions are now compatible with the schema: old code ignores the column it doesn't know about; new code handles its absence.
  2. DUAL-WRITE + BACKFILL. Behind a feature flag, new code writes priority_code on every new and updated order. Separately, a batched, throttled backfill job walks existing rows — a few thousand at a time, sleeping between batches — to populate history (existing orders default to routine). Throttling is not optional: an unthrottled backfill is a lock storm and a replication-lag spike that brings down the very production you're trying not to disturb (Ch 19, Ch 29). The backfill has a kill switch.
  3. SWITCH READS. Once the backfill is verified complete (zero NULLs remain), flip the read path to require priority_code. This is a flag flip — a release, not a deploy. The code is already in prod; you're only changing which branch it takes.
  4. CONTRACT. In a later deploy, once no running code reads the old shape, drop the old column / dead code and add the NOT NULL constraint. Nothing depends on the old shape anymore, so this is safe.

🏭 Why rollback is code-only, and why that's the whole point. Notice what rollback means here. At no phase do you run a "down migration" in prod to undo a schema change — running down-migrations against live patient data is how you turn an incident into a catastrophe. Instead, because every phase preserved backward compatibility, rolling back means re-pointing the load balancer to the previous immutable digest — seconds, no rebuild, no schema touched. The previous code still works against the current schema by construction. Expand/contract's real product isn't "a new column"; it's "a deploy you can abort at any instant without data surgery."

Deploy decoupled from release, via flags. The flag SDK defaults off, supports percentage rollout and a kill switch. Merging the priority_code feature does not launch it; flipping the flag does — to 1% of users first, watched, then widened. This is the valve from §2 made concrete: the dual-write, the read-switch, and the routine/STAT picker on the order form are all gated independently of the deploys that shipped them. And flags are tech debt with a clock: a flag left at 100% for eight months becomes undocumented load-bearing infrastructure. A flag lifecycle policy and scheduled cleanup are part of the practice, not an afterthought.

Canary analysis you can trust. Per service, you define the SLIs (error rate, p99 latency, saturation), the thresholds relative to baseline, the bake duration, and a minimum traffic volume before judging — you do not promote a canary off three requests at 3 a.m. The analysis is a comparison, not an absolute check: route a slice of identical traffic to canary and baseline, and ask "is the canary materially worse than the version it's replacing, right now, under today's load?" If the canary's error budget burns past threshold during the bake, the pipeline automatically aborts and rolls back to the prior digest — no human in the loop, because the loop is faster and calmer than a human under pressure. The same machinery is your protection against the bad change you didn't catch in CI: CI proves the artifact is correct in a test environment; the canary proves it's healthy in production, and they catch different bugs.

Drift detection closes the loop. Someone, someday, will click something in the AWS console "just this once." A scheduled terraform plan / cdk diff in CI compares declared state to reality on a timer and alerts on any non-empty diff, so the desired-state document stays the truth rather than slowly becoming fiction.

🏭 Two framings to carry forward. First: the pipeline itself is code, reviewed like code. The CI YAML and the IaC are PR-reviewed; plan output is read before apply; infra changes land in a non-prod account first. A pipeline nobody reviews is a second, unaudited codebase with production credentials. Second: a rollback runbook should fit on an index card — "re-point to digest X" — because anything longer is something you'll get wrong at 3 a.m. The work of this chapter is front-loading all the thinking so the incident-time action is trivial.


6. Common pitfalls​

Each is signature → fix: the symptom you'll observe, then the principle that resolves it.

Prod runs different code than staging. Signature: a bug appears only in prod; staging was green; the two were built separately. Fix: promote the digest, never rebuild per environment. Forbid npm install / docker build in any deploy step. One artifact, many environments. (Violates the promotion invariant.)

The deploy hangs forever; tasks never go ready. Signature: the rollout sits at "0/6 healthy" indefinitely. Fix: your readiness probe depends on something that's down (a third-party API, a not-yet-migrated DB). Make readiness shallow — process up plus critical local deps — and liveness shallower still. A readiness check that can't pass is a deploy that can't finish.

A rolling deploy 500s mid-rollout. Signature: errors spike only while old and new versions coexist, then clear once rollout completes. Fix: new code wrote a shape old code can't read (or required a field old code never sent). You skipped expand/contract — make the change backward-compatible first, ship the schema separately from the reader.

ADD COLUMN NOT NULL DEFAULT locks the table for minutes. Signature: the migration step wedges; queries pile up behind an exclusive lock; order submission stalls. Fix: add the column nullable, backfill in throttled batches, then add the constraint as a separate validated step. Know your engine's DDL lock semantics (Ch 19) before you write the migration, not during the outage.

Two CI runs corrupt the Terraform state. Signature: apply errors with a state mismatch; resources exist in the cloud but not in state, or vice versa. Fix: enable remote state locking (DynamoDB / Terraform Cloud) so applies serialize. Never run concurrent applies against one state.

A secret leaks into build logs. Signature: a token is visible in a job's output or in docker history. Fix: OIDC short-lived creds instead of static keys, secret masking in the runner, and pull-at-deploy from a manager — and rotate the leaked credential immediately and audit its use. A leaked secret is compromised the moment it's logged. (Secrets handling: Ch 31.)

The canary "passed" but prod melts at 100%. Signature: 1% looked fine; the full rollout falls over. Fix: the canary saw no real traffic mix or baked too briefly. Gate on minimum volume and representative traffic, and lengthen the bake. A canary that judges on too little data is theater.

Rollback re-runs the migration and makes it worse. Signature: the "undo" deploy executes a down-migration that drops a column live code still needs. Fix: never auto-run down-migrations on rollback in prod. Roll back code only and rely on the expand/contract compatibility you preserved. (If you can't roll back code-only, you skipped a phase.)

A flag has been on at 100% for eight months and is now load-bearing. Signature: nobody remembers why the flag exists; removing it breaks prod. Fix: a flag lifecycle policy with scheduled cleanup; treat a stale flag as a bug with a ticket. Flags are debt that accrues interest.

A flaky test is retried three times until it passes. Signature: the gate is "green" only after retry: 3. Fix: quarantine flakes into a non-gating lane and root-cause them; never blanket-retry. A flake silently retried is a failing gate you've lied to yourself about.


7. Tradeoffs​

Senior engineering is naming the spectrum and saying why you stand where you stand.

Continuous Delivery (human button) ↔ Continuous Deployment (fully automatic). Auto-deploy demands high test and observability maturity — trustworthy canary analysis, fast detection, instant rollback. You lean automatic for stateless services with strong gates, where shipping ten times a day in small increments is safer than batching. You keep a human button for regulated, stateful, or money-touching services — a claims/RCM service or anything writing to a chart — or simply until your canary analysis has earned your trust. You'd reverse toward automatic the day your incidents start coming from big batched deploys rather than from individual changes.

Rolling ↔ blue-green ↔ canary. Rolling: cheapest (no extra capacity), but a mixed-version window and slow rollback. Blue-green: instant flip and clean rollback, but ~2× capacity during cutover and awkward when a change can't run two versions at once. Canary: best blast-radius control, but needs weighted routing and good metrics. Default to canary for a stateless API; reach for blue-green when a change genuinely can't run two versions simultaneously and you want one atomic cutover. The Pulsely ADR (below) lands exactly here.

Terraform ↔ CDK. Terraform is multi-cloud with a mature module ecosystem and an HCL learning curve and explicit state to manage. CDK lets an AWS + TS team stay in one language with real abstractions, but it's CloudFormation-bound and its diffs can be leakier. Choose CDK for an AWS + TypeScript shop (Pulsely); reverse to Terraform for multi-cloud or when you need its ecosystem of modules.

Mono-pipeline ↔ per-service pipelines. A shared pipeline gives consistency; per-service pipelines give independent cadence and a smaller blast radius. Favor per-service as the org scales and teams want to ship on their own clock without coordinating a shared line.

Expand/contract (slow, multi-deploy) ↔ big-bang migration (fast, risky). Expand/contract is several deploys and real choreography. A big-bang migration in a maintenance window is one shot — acceptable only when you're allowed to take downtime, which for a clinical system that providers use around the clock is almost never. The cost of expand/contract is coordination; the cost of big-bang is an outage you scheduled.

Flags everywhere ↔ flag minimalism. Flags decouple deploy from release, but each adds a runtime branch and multiplies your test matrix. Gate only risky or irreversible launches behind flags, and retire them aggressively. A codebase where everything is behind a flag is a codebase where nothing's behavior is knowable from the code alone.

🚫 A framing this book rejects. "We'll set up the pipeline properly after we ship — for now just SSH in, it's faster." It feels faster exactly once. Manual deploys don't save time; they defer it to your worst possible moment — an outage, under pressure, with no rollback and no record of what changed. The pipeline isn't ceremony you add when you're "mature"; it's the thing that lets you stay un-mature safely, because it makes every deploy boring whether or not your code is good.


8. Security & scale notes​

The pipeline holds production credentials — it is a top attack target. This is the supply-chain threat, and it's the highest-leverage one you own: compromise the pipeline and you don't need to breach prod, because the pipeline deploys to prod for you. So the first security question is the same membrane question you keep returning to: did a claim (a PR, an artifact) get treated as truth without verification?

No long-lived keys in CI — use OIDC federation. The runner authenticates to AWS via short-lived, assumed-role credentials obtained through OIDC, scoped to a least-privilege deploy role (the IAM discipline from Ch 37). There are no static cloud keys stored as CI secrets to leak. Secrets the app needs are pulled at deploy time from a manager (SSM / Secrets Manager / Vault), masked in logs, scoped per environment, and rotated — never baked into an image layer or a build arg (full crypto/secrets treatment: Ch 31).

Untrusted PRs must not run privileged jobs. A fork's pull request can contain malicious workflow changes; if it can assume your deploy role, it owns prod. Gate privileged jobs to trusted branches, require approval to run workflows from forks, and keep runners protected.

Artifact provenance: prod admits only what the pipeline built. Pin base images by digest, scan every build for CVEs, generate an SBOM — a software bill of materials, a manifest listing every dependency and version baked into the image, so that when the next CVE lands you can answer "are we affected?" in seconds instead of days — sign artifacts (cosign), and verify signatures at admission: production checks the signature at the exact moment it's asked to run an image and refuses any digest the pipeline didn't build and sign. This is the same single-source-of-truth principle applied to what's allowed to run.

PHI and secrets must never end up in the pipeline's exhaust. Build logs, docker history, and the Terraform state file are all places bytes quietly leak; none may ever contain PHI or a credential — a state file with PHI sitting in an S3 bucket is a reportable breach, not a cleanup task. Run only HIPAA-eligible AWS services under a signed BAA (a Business Associate Agreement — the contract that permits AWS to process PHI on your behalf); keep every PHI store in private subnets with no public route; and encrypt at rest by default (S3 with SSE, RDS/Aurora encryption). The pipeline's job is to make those the only reachable state — the tfsec/checkov gate fails the build the moment someone declares a public bucket, an open security group, or an unencrypted volume.

Secrets blast radius is bounded by scoping. Per-environment secrets mean a staging leak can't touch prod. No secret in an image layer, a build arg, or a state file (which is why state never goes in git).

Now scale, where gradual rollout has a sharp edge.

Rolling and canary create a mixed-version fleet — N-1/N compatibility is a scale property, not a nicety. During every gradual rollout, two code versions serve real traffic against one schema and one event bus. The compatibility window from §3 must hold for both your app code and your message/event schemas (Ch 27) — an N+1 producer must not emit an event N consumers choke on. Forget this and your "zero-downtime" deploy is a partial outage that lasts exactly as long as the rollout.

Migrations and backfills must throttle to survive production load. A backfill or an index build competes with live traffic for DB IOPS and inflates replication lag. Batch it, throttle it, give it a kill switch, and watch replica lag while it runs (Ch 19, Ch 30). The migration that's harmless on an idle staging DB is an outage on a busy prod one.

Health gates must judge relative to baseline, not against absolute numbers. A canary threshold of "error rate < 0.5%" false-trips during a legitimate traffic spike and false-passes at 3 a.m. low volume. Gate on error-budget burn relative to the current baseline (Ch 33) and require minimum volume, so the gate measures your change's effect, not the weather.

🔑 Ramp the flag, not just the deploy. Flipping a flag to 100% instantly shifts traffic patterns — cold caches, new query paths, fan-out that didn't exist a second ago. That stampede can melt a system that the deploy itself didn't touch. A release is a load event. Ramp the flag gradually for the same reason you canary the deploy: so the new load arrives in a sliver you can watch, not a wall you can't.


9. Interview lens & exercises​

Interview questions​

Delivery questions separate engineers who've operated systems from those who've only built them. The tell is whether the answer names tradeoffs and reversal conditions.

"Walk me through deploying a schema change with zero downtime."

  • Junior answer: "Run the migration, then deploy the new code."
  • Senior answer: names expand/contract explicitly — add a nullable column with code that tolerates both shapes, dual-write behind a flag, throttled backfill with a kill switch, switch reads, then contract in a later deploy. Stresses that the migration is a separate step ordered around the app rollout (expand before, contract after), and that rollback is code-only — re-point to the previous digest — because compatibility was preserved at every phase. Never runs a down-migration in prod.

"Rolling, blue-green, or canary — which and why?"

  • Junior: recites the three definitions.
  • Senior: frames it as blast radius vs. capacity cost vs. statefulness, picks per change, and names the catch for each — rolling's mixed-version window (so N-1/N compatibility must hold), blue-green's 2× capacity and atomic flip (good when two versions can't coexist), canary's need for weighted routing and trustworthy metrics. States the reversal condition.

"Why build once and promote the same artifact?"

  • Junior: "It's faster."
  • Senior: eliminates environment drift so green == shipped, enables instant digest-based rollback, and underpins provenance/signing so prod only runs what the pipeline produced. Ties it to the promotion invariant: config is the variable, the artifact is the constant.

"How do you decouple deploy from release?"

  • Junior: "Use a staging branch."
  • Senior: feature flags as the valve — ship code dark, release with a ramped flag, kill-switch on regression, and a flag lifecycle policy because stale flags are debt. Deploy means "running in prod"; release means "users see it"; the flag separates them.

"How does the pipeline get prod credentials safely?"

  • Junior: "Store them as CI secrets."
  • Senior: OIDC federation → short-lived assumed roles, least-privilege deploy role scoped to exact actions, no static keys, masked logs, secrets pulled at deploy from a manager, and untrusted PRs barred from privileged jobs — because the pipeline is a top supply-chain target.

Exercises & the Pulsely increment​

Do these against the Pulsely codebase you've been building. The goal is a delivery machine you'd trust on a Friday.

  1. Build the gated pipeline (core increment). Author the GitHub Actions pipeline: build → test (with ephemeral Postgres/Redis services) → scan (Trivy + semgrep + tfsec) → package (signed image digest), with every gate able to stop the line. Prove that the same digest is what flows dev → staging → prod, and that no deploy step rebuilds.

  2. Define the infra as code. Express the clinical-orders-service infrastructure (ECS Fargate service, ALB target groups, Aurora, secrets) in CDK (or Terraform with remote, locked state). Run cdk diff / terraform plan, review the output, apply to a non-prod account, then manually change one resource in the console and watch drift detection catch it.

  3. Ship clinical_orders.priority_code with zero downtime. Walk the column through full expand/contract — add nullable, dual-write behind a flag, throttled backfill with a kill switch, switch reads, contract — across multiple deploys. At each phase, demonstrate that rolling back is code-only and touches no data.

  4. Canary + rollback drill. Configure a 1% → 25% → 100% canary with health-gated promotion. Then deliberately ship a regression and verify the pipeline auto-aborts and rolls back to the prior digest faster than your time-to-detect. If rollback is slower than detection, your reversibility invariant is broken — fix it before you trust the pipeline.

  5. Write the two ADRs.

    • ADR-038a — Deployment strategy: "Canary-first with blue-green fallback for stateful changes." Context, options (rolling/blue-green/canary), the decision, consequences, and the conditions that flip you from canary to blue-green.
    • ADR-038b — Migration plan: "Expand/contract for all schema changes; deploy decoupled from release via flags." Document the phase protocol, the rollback-is-code-only rule, the throttling/kill-switch discipline for backfills, and the flag lifecycle policy.

Key takeaways​

  • A deploy is the output of a machine you build once — a conveyor of quality gates — not an event you perform by hand under pressure.
  • The promotion invariant: build once, promote the same immutable digest across every environment; config is the variable, the artifact is the constant. Green == shipped == running.
  • Deploy ≠ release. Deploy puts code in prod; a feature flag is the valve that releases its behavior — ramped, kill-switched, and retired aggressively.
  • Infrastructure is a desired-state document, reconciled by a tool, with remote locked state. The code is the truth; the cloud is a cache that can drift — so detect drift.
  • The reversibility invariant: a release must be revertible faster than time-to-detect. If it can't be cheaply reverted, it's a migration, made safe by expand/contract.
  • Expand/contract keeps schema and code compatible across the rollout window so that rollback is code-only — re-point to the previous digest, never run a down-migration in prod.
  • Deployment strategy is a blast-radius vs. confidence dial: rolling (cheap, mixed-version), blue-green (atomic flip, 2× capacity), canary (best control, needs weighted routing + metrics). Default canary; blue-green when versions can't coexist.
  • Health gates promote on observed SLIs relative to baseline, not elapsed time; the pipeline holds prod creds, so OIDC short-lived roles, signed artifacts, and least privilege are non-negotiable.

← Previous: Ch 37 — Cloud & AWS for Backend Engineers · Up: Part VII overview · Master TOC · Next: Ch 39 — Software Architecture & Service Boundaries →