Platform Engineering · Lesson 193

Blue/Green Deployments and Deployment Frequency: Instant Switch, Instant Rollback, Small Batches

A blue/green deployment runs two complete production environments: blue serves users while green gets the new version, is tested, and then receives all traffic in one switch, with blue kept ready so that rolling back is the same switch in reverse. The switch is instant; what makes it safe is everything around it: one immutable artifact, a green environment at full capacity, a database that works for both versions, and a watch period with a clear rollback rule. Deployment frequency decides how much each switch carries: teams that deploy many times a day ship a few changes per release, so a bad one is found in minutes. This lesson follows one release through a blue/green switch and shows two failures: a monthly release too big to debug, and a migration that made rollback impossible.

Difficulty: Intermediate · Know this first: Lesson 98, Lesson 192

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from the merge to a release confirmed healthy. It is a worked example, not a measurement. The batch size and database hops decide whether a failed release is a minute or days.

Try it: how often do you deploy, and how do you migrate?

Pick the deployment frequency and the migration style. Assume this release contains one bad change.

2changes per release
minutesto find the bad change
1 switchrollback

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Blue/green delivery grows in four levels: understanding the switch, running it safely, making the database compatible, and deploying often enough that each switch is small.

Basic — Understand the switch

At the basic level you can explain blue/green and when it fits.

  • Two environments, one router, an instant switch and an instant rollback.
  • Blue/green versus rolling updates and canaries.
  • The cost: double capacity during the switch window.

Where it breaks: switching DNS and expecting every client to move at once.

Try it: Basic

How does blue/green differ from a canary release?

Now do it: Pick one service and decide which strategy fits it.

Intermediate — Run it safely

At the intermediate level the switch is rehearsed and watched.

  • One immutable artifact; green at full capacity.
  • Smoke tests on a private route; warm-up traffic.
  • Connection draining, a watch period, and a written rollback rule.

Try it: Intermediate

Green passed its smoke tests, and right after the switch latency doubles for five minutes. A likely reason?

Now do it: Add synthetic warm-up traffic to a release pipeline.

Advanced — Make the database compatible

At the advanced level every release can be rolled back.

  • Expand and contract: additive changes now, destructive ones later.
  • Migrations run as their own pipeline step, not on application start.
  • A CI check that rejects destructive migrations in the same release as the code.

Try it: Advanced

You need to rename a column. How, with blue/green?

Now do it: Write the expand and contract steps for one rename.

Master — Deploy often

At the master level releases are small because deploys are frequent.

  • Deployment frequency, batch size, change failure rate, and time to restore per service.
  • Trunk-based development and feature flags for unfinished work.
  • Automated switch and rollback driven by metrics.

Trade-off: blue/green doubles capacity during each switch and needs compatible schemas; in return, a release can be undone in a minute, and frequent small releases make that rarely necessary.

Try it: Master

A team deploys monthly "to be safe". What do you suggest?

Now do it: Chart changes per release for one service over the last quarter.

Go deeper

Blue/green on Kubernetes with two Deployments and one Service (the switch is a selector change; Argo Rollouts' blueGreen strategy automates the same pattern with preview and active Services):

kubectl apply -f checkout-green.yaml          # Deployment checkout-green, labels app=checkout,version=green
kubectl rollout status deploy/checkout-green
kubectl port-forward deploy/checkout-green 8081:8080 &   # private route for smoke tests
curl -fsS localhost:8081/healthz
kubectl patch service checkout -p '{"spec":{"selector":{"app":"checkout","version":"green"}}}'   # the switch
kubectl patch service checkout -p '{"spec":{"selector":{"app":"checkout","version":"blue"}}}'    # rollback

Other platforms: AWS CodeDeploy blue/green with two target groups behind an Application Load Balancer, Azure App Service deployment slots with swap, Google Cloud Run traffic splitting between revisions, and weighted target groups or Envoy routes when you want a canary step before the full switch.

Deployment frequency from a deployment log, per service per week, is a count; report it next to changes per release (the batch size), change failure rate, and time to restore, so a team cannot improve one by hurting the others.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The rollback that did not roll back.

Timeline

  • 10:00Green starts with the new version. Its startup job runs a migration that renames a column by adding, copying, and dropping.
  • 10:06Blue, serving all users, starts failing on every page that reads the old column.
  • 10:10The team switches traffic to green, then back to blue; both fail in different ways, because the schema is shared.
  • 10:15–12:03The column is restored from a backup, writes since 10:00 are replayed, and blue recovers.

What changed after

Migrations run as a separate pipeline step, a CI check rejects destructive migrations in the same release as the code that needs them, renames follow expand and contract over two releases, and the team moves from weekly releases to deploying after every merge.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Linux with the standard tools (ln, mv, awk) and Python 3. The switch below is the same idea that release tools use on servers: two release directories and one pointer.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make two releases side by side, and point "current" at blue.

    Reversible

    mkdir -p ~/labs/bluegreen/releases/{blue,green} && cd ~/labs/bluegreen
    echo "checkout v41 (blue)" > releases/blue/index.html
    echo "checkout v42 (green)" > releases/green/index.html
    ln -sfn releases/blue current && cat current/index.html

    Options: ln -sfn creates or replaces a symbolic link without following an existing one.

    Expect: checkout v41 (blue).

    Clean up: rm -rf ~/labs/bluegreen.

  2. Smoke-test green directly, then switch atomically and roll back.

    Reversible

    Changes a real system: On a real server, the web server or process manager must pick up the new path (a reload); on Kubernetes the switch is the Service selector instead.

    grep -q "v42" releases/green/index.html && echo "green smoke test: ok"
    ln -sfn releases/green current.tmp && mv -Tf current.tmp current && cat current/index.html
    ln -sfn releases/blue current.tmp && mv -Tf current.tmp current && cat current/index.html

    Options: Creating a new link and renaming it over the old one with mv -T is a single atomic rename, so no request ever sees a missing link.

    Expect: The smoke test passes, then v42 (green) after the switch, then v41 (blue) after the rollback. Both releases stayed in place the whole time.

  3. Deployment frequency from a deployment log: deploys per week.

    Reversible

    printf '%s\n' 2026-11-02 2026-11-02 2026-11-03 2026-11-05 2026-11-09 2026-11-10 2026-11-10 2026-11-11 2026-11-11 2026-11-12 2026-11-13 > deploys.log
    while read d; do date -u -d "$d" +%G-W%V; done < deploys.log | sort | uniq -c

    Options: +%G-W%V prints the ISO year and week number for each date.

    Expect: Two weeks: 4 deploys in the first, 7 in the second.

2. Python: release_batches.py

This program computes deployment frequency, changes per release, and change failure rate from a deployment log, estimates how long it takes to find one bad change by bisecting releases of different sizes, and adds up the extra capacity a blue/green switch window costs. Save it as release_batches.py, then run it.

# release_batches.py
import math

DEPLOYS = [("2026-11-02", 3, False), ("2026-11-02", 2, False), ("2026-11-03", 4, True), ("2026-11-05", 2, False),
           ("2026-11-09", 1, False), ("2026-11-10", 2, False), ("2026-11-10", 3, False), ("2026-11-11", 2, False),
           ("2026-11-11", 1, False), ("2026-11-12", 2, False), ("2026-11-13", 3, False)]   # (date, changes, failed)
weeks = 2
print(f"deployment frequency: {len(DEPLOYS) / weeks:.1f} per week, {len(DEPLOYS) / (weeks * 5):.1f} per working day")
print(f"changes per release:  {sum(c for _, c, _ in DEPLOYS) / len(DEPLOYS):.1f}")
print(f"change failure rate:  {sum(1 for *_, f in DEPLOYS if f) / len(DEPLOYS):.0%}")
print()

BUILD_AND_TEST_MIN = 25                                   # one bisect round: build a partial release and test it
for label, batch in (("after every merge", 2), ("daily", 12), ("weekly", 60), ("monthly", 240)):
    rounds = math.ceil(math.log2(batch)) if batch > 1 else 0
    print(f"{label:<18} {batch:>3} changes: {rounds} bisect round{'' if rounds == 1 else 's'}, about {rounds * BUILD_AND_TEST_MIN:>3} min to find one bad change")
print("(bisecting assumes the failure reproduces in a test; production-only failures take far longer)")
print()

PODS, POD_HOUR_USD, WINDOW_H, RELEASES_PER_MONTH = 12, 0.10, 1.0, 300
extra = PODS * POD_HOUR_USD * WINDOW_H * RELEASES_PER_MONTH
print(f"blue/green window: {PODS} extra pods for {WINDOW_H:.0f} h per release, {RELEASES_PER_MONTH} releases -> USD {extra:,.0f} a month")

Run it, and you should see this output:

$ python3 release_batches.py
deployment frequency: 5.5 per week, 1.1 per working day
changes per release:  2.3
change failure rate:  9%

after every merge    2 changes: 1 bisect round, about  25 min to find one bad change
daily               12 changes: 4 bisect rounds, about 100 min to find one bad change
weekly              60 changes: 6 bisect rounds, about 150 min to find one bad change
monthly            240 changes: 8 bisect rounds, about 200 min to find one bad change
(bisecting assumes the failure reproduces in a test; production-only failures take far longer)

blue/green window: 12 extra pods for 1 h per release, 300 releases -> USD 360 a month

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/blue-green-deployments-and-deployment-frequency && cd ~/labs/blue-green-deployments-and-deployment-frequency) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Blue/Green Deployments and Deployment Frequency: Instant Switch, Instant Rollback, Small Batches", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Make two releases side by side, and point "current" at blue.'
  'Smoke-test green directly, then switch atomically and roll back.'
  'Deployment frequency from a deployment log: deploys per week.'
)

step_1() {
mkdir -p ~/labs/bluegreen/releases/{blue,green} && cd ~/labs/bluegreen
echo "checkout v41 (blue)" > releases/blue/index.html
echo "checkout v42 (green)" > releases/green/index.html
ln -sfn releases/blue current && cat current/index.html
}

step_2() {
grep -q "v42" releases/green/index.html && echo "green smoke test: ok"
ln -sfn releases/green current.tmp && mv -Tf current.tmp current && cat current/index.html
ln -sfn releases/blue current.tmp && mv -Tf current.tmp current && cat current/index.html
}

step_3() {
printf '%s\n' 2026-11-02 2026-11-02 2026-11-03 2026-11-05 2026-11-09 2026-11-10 2026-11-10 2026-11-11 2026-11-11 2026-11-12 2026-11-13 > deploys.log
while read d; do date -u -d "$d" +%G-W%V; done < deploys.log | sort | uniq -c
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

A team releases its checkout service monthly with a two-hour maintenance window. Move it to blue/green releases several times a day.

Clarifying questions to ask

How is green built and sized? Where is the switch, and how are connections drained? How are smoke tests and warm-up run? How do schema changes work? What is the watch period and rollback rule? Which metrics show the change is working?

Rough sizing

Say 12 pods at peak, a Postgres database shared by all versions, 40 changes merged a week, and a monthly change failure rate of 20% today.

Shape of the answer

Images by digest from CI; green as a second Deployment at full size behind a Service with a selector switch (or Argo Rollouts blueGreen); a private preview Service for smoke tests and synthetic warm-up; migrations as a separate expand step with contract in a later release and a CI check against destructive changes; a 10-minute watch with automatic switch-back on error-rate and latency thresholds; blue kept for an hour; weekly reporting of deployment frequency, changes per release, change failure rate, and time to restore.

Trade-offs to name

Double capacity for each switch window costs money; compatible migrations take two releases instead of one; in return, maintenance windows go away and a bad release is undone in a minute.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Monthly releaseHop 1: Batch sizeBreaksA monthly release of 240 changes. After the switch, the error rate on checkout rises; switching back to blue takes a minute. Then the hard part: which of 240 changes caused it?
Monthly releaseHop 7: WatchDegradesCheckout errors rise to 2% within 4 minutes.
Destructive migrationHop 5: DatabaseBreaksGreen's deploy job runs its migration as it starts: rename customer_name to full_name, implemented as add, copy, and drop. Blue, still serving all users, reads customer_name, and starts failing on every order page before the switch.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Batch size → Artifact → Green → Smoke and warm → Database → Switch → Watch → Rollback → Frequency. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 194
Preview Environments and Environment Management: Ephemeral, Seeded, and Cleaned Up

Shared staging environments become queues and arguments: one team's broken change blocks everyone, and nobody knows what is deployed. Preview environments (ephemeral environments) give every pull request its own short-lived copy…

Go to Lesson 194 →

Or browse the full course from the Lessons index.