Deployment strategies

Rolling, blue-green, canary, feature flags, and the database migration that has to be compatible with both versions.

13 min read🔁 CI/CD, Linux and Nginx

A deployment is the moment the new version and the old one both exist, and every strategy is a decision about how long that moment lasts, who sees which version during it, and how you get back if the new one is wrong. This repository's own deploy is a worked example of the simplest safe shape; the others are what you add when the traffic, the team or the risk grows.

Rolling: replace them one at a time

Start a new instance, wait for it to be healthy, stop an old one, repeat. Capacity never drops below the old count, and at any moment some fraction of traffic is on the new version. Kubernetes's rolling update (the rollouts lesson) is this with maxSurge and maxUnavailable as the knobs; an autoscaling group with instance refresh is the same on virtual machines.

Its cost is the mixed-version window. For the length of the roll, a request may hit the old version and its retry the new one. A client may get a response shape from the new version and send its next request to the old. And two versions of the application share one database.

So a rolling deploy needs compatible versions: the API compatibility rules from the REST course, and the schema rules at the end of this lesson. Rollback is a roll in the other direction, and it takes as long.

Blue-green: two environments, one switch

Two complete environments, blue serving and green idle. Deploy to green, test it — real health checks, smoke tests, even a trickle of internal traffic — then flip the router so green serves and blue goes idle. Rollback is flipping back, in seconds, to an environment that is still warm and still running the old version.

That is what deploy/deploy.sh does on one machine: each deploy is a new timestamped directory under releases/, built and migrated and health-checked while the old release keeps serving; then the current symlink moves, nginx reloads, the server restarts, and a health check confirms. The last five releases are kept, and --rollback moves the symlink back and reloads. It is blue-green with directories instead of servers, and its one gap is the restart — a few seconds where the server process is down, which a second instance behind nginx would close.

The cost of blue-green is double the capacity during the deploy (or all the time, if green is kept warm), and the database, which cannot be blue-green: both environments share it, so the schema rule below is what makes the flip-back possible. It is the right default when you can afford the capacity and want a rollback that is instant and certain.

Canary: a little traffic, then more

Deploy the new version to a small slice — one instance, 5% of traffic — watch the error rate and latency against the old version for a fixed period, then widen: 25%, 50%, all. Any regression shows up on 5% of users and is rolled back before the rest ever see it. The observability course's SLO metrics are what you watch, and the comparison must be new versus old at the same time, not new versus last week, because traffic and its mix change.

A canary needs a router that can split traffic by weight — a load balancer with weighted targets, an ingress or mesh with traffic splitting, or, at the application level, a routing rule on a header for internal users first. Kubernetes's rolling update is not a canary: it moves through the pod ratio without stopping to look. Tools like Argo Rollouts and Flagger automate the watch-and-widen loop and the automatic rollback, and the loop is the point: a canary you do not measure is a rolling deploy with a longer name.

Feature flags: deploy is not release

The strategies above deploy code and release it in the same act. A feature flag separates them: the new code is deployed dark, behind a condition, and released by flipping the flag — for internal users, for 1% of customers, for one tenant — without a deployment at all. Rollback is the flag, in milliseconds, and the code stays deployed.

java
if (flags.isEnabled("new-checkout", customer)) return newCheckout.run(cart);
return checkout.run(cart);

The microservices course's configuration lesson covers where flags live (a config service, LaunchDarkly, Unleash, or a table). The discipline this lesson adds is that a flag is debt with a removal date. Every flag is two code paths to test and reason about, and a codebase with two hundred stale flags is a codebase nobody can reason about. Flag the risky change, release it gradually, and remove the flag and the old path the week after it reaches 100%.

Expand-contract: the database, which cannot roll back

Every strategy above assumes the old and new versions can run against the same schema at the same time, and can be swapped back. A migration that renames a column breaks that in both directions: the old version fails the moment the column is gone, and rolling back the code does not bring the column back. Expand-contract makes every schema change compatible with both versions by splitting it into three deploys:

  1. Expand: add the new column, nullable or with a default. Both versions run; the old one ignores it.
  2. Migrate: deploy code that writes both columns and reads the new one (with a fallback), then backfill the old values into the new column in batches. Both versions still run.
  3. Contract: once no running version reads the old column, remove it. A separate deploy, days later, after the rollback window has closed.

The database course's governance says this in its own words, and this repository's rule for its Flyway migrations is exactly it: expand → migrate → contract on live tables, backward compatible with existing rows, never a rewrite. The migration runs before the switchover in the deploy script for the same reason — a failed migration leaves the old release serving, and a successful one is compatible with it.

Choosing

StrategyRollbackCostsReach for it when
Rollinganother roll, minutesmixed versions during the rollthe default on a platform that does it for you
Blue-greena switch, secondsdouble capacity, a shared databaseyou want certain, instant rollback
Canarystop widening, secondsa weighted router and something to watchthe change is risky and the traffic is large enough to measure
Feature flagflip, millisecondstwo code paths until removeddeploy and release should be different days

They compose: a rolling deploy of flagged code, canaried by tenant, with expand-contract underneath. The one that is not optional is the last one; every other strategy's rollback depends on it.

Under the hood: what actually redirects the traffic

"Flip a switch" hides three different mechanisms, and they are not interchangeable.

A symlink swap is what deploy/deploy.sh does. current is repointed from one release directory to another with ln -sfn. On Linux that is a single rename(2)-class operation on the directory entry. The kernel either sees the old target or the new one, never a half-written path, so every process that opens a file under current after the swap gets a consistent view of one release or the other.

It is atomic, but it is also local to one machine. It says nothing about traffic in flight or about a second machine. That is why the health check and the nginx reload that follow it in the script matter as much as the swap itself.

A load balancer's routing table (an L4/L7 load balancer's target groups, an ingress controller, a service mesh's sidecar configuration) is what makes a weighted split, like canary's 5% and then 25%, possible at all. The balancer picks a backend per new connection (or per request, for an L7 balancer that terminates HTTP) according to the configured weights. So a change in weights takes effect immediately for anything not already connected.

Existing connections are usually left alone until they close naturally (connection draining). That is why a backend "removed" from rotation can still be serving requests for seconds afterward. The drain window is a deliberate design, not a bug: an in-flight request is not cut off mid-response.

DNS cannot do this precisely, and it is a common mistake to reach for it for a canary. A DNS answer is cached by the resolver and by the client for its TTL, which is seconds to hours, and some clients and corporate resolvers ignore a short TTL entirely. So changing which IP a name resolves to does not redirect existing traffic at all, and does not even redirect new connections from every client at the same moment.

DNS-based traffic shifting is coarse and slow by nature. It is useful for blue-green across regions, where the switch does not need to be split-second. It cannot deliver a specific percentage split the way a load balancer's weighted routing can, because "what fraction of clients see the new record" is governed by caches this system does not control.

The database is the one part none of these three mechanisms touch. It is shared by whichever mix of old and new instances traffic is currently split across. That is exactly why the compatibility requirement below is not optional for any of them.

The compatibility window, precisely

Expand-contract's rule is often stated as "add before you remove". The requirement it exists to satisfy is sharper:

for the whole time both code versions can receive traffic, every row the old version writes must be readable and writable by the old version's assumptions, and every row the new version writes must be readable by the old version too.

That is because a rolling deploy, a canary, or even a blue-green flip that has to roll back can put either version's code in front of either version's data at any moment during the window.

Concretely, in the migrate step (write both, read the new column, backfill in batches):

  • The new version writes to both the old and new column on every insert or update, not just the new one. If it wrote only the new column, a row it just created would be invisible or wrong to the old version, which does not know the new column exists and is still reading the old one.
  • The backfill has to run in batches, not one statement, for the same lock-contention reason the failed-deployments lesson covers for a single ALTER TABLE. A single UPDATE touching every row of a live table holds row locks for as long as it runs. It can queue up everything behind it, exactly the way that lesson's ALTER TABLE did.

Try it yourself

Why a 5% canary needs a load balancer, not a DNS record

A team wants to send exactly 5% of production traffic to a canary release and watch its error rate before widening. Someone suggests adding a second DNS record for the service's hostname, pointing at the canary's IP, so that (in theory) some fraction of lookups resolve to it.

Using what the "Under the hood" section above says about DNS caching, predict what actually happens to the traffic split within the first few minutes, and why a weighted load balancer target group would behave differently for the same 5% request.

Why the DNS split does not stay at 5%, and a weighted LB does

The split does not hold at anything close to 5%, and it does not update in real time. Each resolver and client that already has the old record cached keeps sending 100% of its own traffic to the old IP until its TTL expires. For a large user base with many independent resolvers, the actual fraction seeing the canary at any given minute is unpredictable. It depends on cache expiry timing the team does not control, not on the DNS weighting.

Worse, once a client's resolver does cache the canary's IP, that client is now pinned to the canary for its own TTL. There is no way to selectively route just 5% of that client's requests, only which record a given cache holds until it expires.

A weighted load balancer target group has none of this. It makes the routing decision on the balancer itself, per new connection, against its live configured weights. So a change from 5% to 25% takes effect for new connections immediately and uniformly across all clients, with no cache anywhere in the path to work around. The load balancer is in the request path. DNS is only consulted once, before the request path is chosen at all.

Misconceptions

  • "Flipping the router or the symlink is instantaneous for every client." The switch itself can be atomic on the server (a rename-class symlink swap, a load balancer's routing table update). But that is not the same as every client seeing it instantly. A connection already open when the switch happens is usually left to drain, and a DNS-based switch is bounded by caches the server does not control at all.
  • "Expand-contract is only needed for a rename or a drop." Any change where the old and new code disagree about a column's meaning needs it. Adding a column the new code requires but the old code will never populate is just as incompatible as a rename. A request served by the old version during the window still has to produce a row the new version can use.

Sources

  • Google, Site Reliability Engineering, Chapter 27, "Reliable Product Launches at Scale" — staged and canary rollouts, watching a slice before widening.
  • PostgreSQL Wiki, "Safe Operations For High Volume PostgreSQL" — batched backfills and lock-aware schema changes during a compatibility window.
  • man 2 rename — the atomicity guarantee a symlink or directory-entry swap relies on.
Progress is saved on this device and to your account when signed in.