Deployment Strategies

Rolling, blue-green, canary, feature flags and safe database migrations.

What is it?

Shipping new code is one of the most common causes of outages. A deployment strategy decides how new versions replace old ones so that users see no downtime and a bad release can be caught and reversed quickly.

- Rolling: replace instances a few at a time. - Blue-green: run the new version as a complete second environment, then switch all traffic at once. - Canary: send a small slice of traffic to the new version, watch metrics, then grow it gradually. - Feature flags: ship code turned off, and enable it at runtime for chosen users, separating deploy from release. - Dark launches: run new code paths on real traffic without showing the results to users.

Databases need extra care, because code can be rolled back in seconds but data changes often can't. The expand/contract pattern makes schema changes safe for zero-downtime deploys.

Explain like I'm 10

A rolling deploy is renovating a hotel one floor at a time while guests stay. Blue-green is building an identical hotel next door and moving everyone over at once, keeping the old one ready. A canary is letting a few guests try the new wing first and watching for complaints.

Examples

Rolling update settings in Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout
spec:
  replicas: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 2         # up to 12 pods may exist during the rollout
      maxUnavailable: 0   # never drop below 10 ready pods
  template:
    spec:
      containers:
        - name: checkout
          image: registry.example.com/checkout:1.8.0
          readinessProbe:
            httpGet: { path: /ready, port: 8080 }

Kubernetes starts new pods, waits for readiness, then removes old ones, a couple at a time. Old and new versions serve traffic together during the rollout, so they must be compatible.

Expand/contract: renaming a column safely

-- Goal: rename users.fullname -> users.display_name with zero downtime

-- 1. EXPAND (deploy A): add the new column; old code ignores it
ALTER TABLE users ADD COLUMN display_name TEXT;

-- 2. Deploy code that WRITES BOTH columns, still reads fullname
-- 3. Backfill existing rows in small batches
UPDATE users SET display_name = fullname
WHERE display_name IS NULL AND id BETWEEN 1 AND 10000;   -- repeat per batch

-- 4. Deploy code that READS display_name (still writes both)
-- 5. Deploy code that stops writing fullname

-- 6. CONTRACT (only after no running code uses it)
ALTER TABLE users DROP COLUMN fullname;

Every step is backward compatible with the version running before it, so any single deploy can be rolled back. The destructive step happens last, once nothing depends on the old column.

How it works

Rolling needs no extra infrastructure beyond some spare capacity, but old and new versions run side by side, and rolling back is another rolling deploy.

Blue-green keeps two full environments. "Green" gets the new version and is tested; then the router or DNS switches traffic from "blue". Rollback is switching back, which is fast. Costs: double capacity during the switch, and both versions must work with the same database.

Canary routes a small percentage (1%, then 5%, 25%, 100%) to the new version, comparing error rates, latency and business metrics against the baseline. Automated canary analysis can halt and roll back without a human. Needs traffic-splitting (load balancer weights or a service mesh) and good metrics.

Feature flags wrap new behavior in a runtime check. Code deploys dark, and the flag turns it on for staff, a percentage of users, or a region. If something breaks, you flip the flag off instead of redeploying. Flags are technical debt: remove them once a feature is fully launched.

Dark launches (or shadow traffic) send real requests to the new code path but discard or only log its results, testing performance and correctness under real load without user impact. Watch out for side effects: a shadowed "send email" call must not actually send.

Rollbacks must be fast and rehearsed. They're only safe if the previous version still works with the current data, which is why schema changes follow expand/contract (also called parallel change): add new structures, migrate and dual-write, switch reads, then remove the old structures in a later release.

Rolling:     [v1 v1 v1 v1] -> [v2 v1 v1 v1] -> [v2 v2 v1 v1] -> [v2 v2 v2 v2]

Blue-green:  Router --100%--> Blue (v1)        Router --100%--> Green (v2)
                              Green (v2) idle   =>               Blue (v1) standby

Canary:      Router --95%--> v1 fleet
                    --5%---> v2 canary   (compare errors/latency; grow or roll back)

Expand/contract timeline
 add column -> write both -> backfill -> read new -> stop writing old -> drop old
 |<------------ every step compatible with the previous deploy ------------>|

Why does it exist?

Big-bang deploys with downtime windows don't fit services that must always be up and ship many times a day. Most incidents follow a change, so strategies that limit how many users see a bad change, and how long it takes to undo it, directly reduce the impact of mistakes.

When to use it

- Rolling: the default for stateless services with backward-compatible changes. - Blue-green: when you need instant cutover and instant rollback, and can afford double capacity briefly. - Canary: high-traffic, high-risk services where you have good metrics to compare. - Feature flags: risky features, gradual rollouts to user segments, experiments, and kill switches. - Expand/contract: any schema change on a database used by live code.

When not to use it

Canaries are weak on very low-traffic services: 5% of a few requests per minute won't give a meaningful signal. Blue-green doesn't save you from incompatible database changes, because both colors share the data. Feature flags are overkill for trivial changes and harmful when left in code for years.

Common mistakes

  • Running a destructive migration (drop or rename a column) in the same release as the code change, making rollback impossible.

  • Assuming old and new versions never run together; during rolling or canary deploys they always do.

  • Running a canary without comparing it against a baseline, so a doubled error rate goes unnoticed.

  • Leaving feature flags in the code long after launch, creating untested combinations and dead branches.

  • Shadowing traffic to code with side effects, sending real emails or charges from the 'dark' path.

Practice exercises

  1. Easy:

    Compare rolling and blue-green deploys on rollback speed, infrastructure cost and version overlap.

  2. Medium:

    Plan a zero-downtime migration that splits a single 'address' text column into street, city and postal_code columns, listing every deploy step.

  3. Hard:

    Design an automated canary pipeline: which metrics you compare, how you decide statistically to proceed or roll back, and how it handles low-traffic hours.

Interview questions

What's a rolling deployment?

Replacing instances of the old version with the new one in small batches, waiting for each batch to become healthy before continuing. No extra environment is needed, but both versions serve traffic during the rollout.

Blue-green vs canary?

Blue-green switches all traffic from the old environment to a fully deployed new one at once, with instant switch-back. Canary shifts traffic gradually, starting with a small percentage, and watches metrics to limit how many users a bad version affects.

What's the difference between deploying and releasing?

Deploying puts new code into production; releasing exposes the behavior to users. Feature flags separate them, so code can be deployed off and turned on later, for some users, without another deploy.

What is a dark launch?

Running a new code path in production on real traffic without users seeing its output, for example shadowing requests to a new service and comparing results. It tests performance and correctness safely, as long as side effects are suppressed.

Why must old and new versions be compatible during a deploy?

Rolling and canary deploys run both at once, and rollbacks bring the old version back. Both must read and write the same data and API formats, or requests fail depending on which instance handles them.

Explain expand/contract migrations.

Make schema changes in backward-compatible steps: expand (add new columns/tables), dual-write, backfill, switch reads, stop writing old, then contract (remove old structures) in a later release. Each step is safe to roll back.

What metrics would you watch during a canary?

Error rate and latency percentiles versus the baseline, saturation (CPU, memory), and business metrics like checkout success or sign-ups, since some bugs return 200 but do the wrong thing.

What are the risks of feature flags?

Combinatorial complexity (many flags make untested combinations), stale flags as tech debt, flag-service dependency on the request path, and inconsistent behavior if flag evaluation differs between services. Mitigate by removing flags after launch and caching evaluations with safe defaults.

Why can't blue-green alone make a schema change safe?

Both environments share the database. If green's migration drops or renames something blue needs, switching back to blue breaks. You still need backward-compatible, expand/contract migrations.

A deploy is at 30% canary and errors spike. Walk through the response.

Stop the rollout and shift traffic back to the stable version (automatically, ideally). Confirm the metrics recover. Check whether the canary wrote incompatible data that needs repair, then investigate from logs and traces before trying again.