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).