Lab: A Release with Migrations, Smoke Tests and Rollback
Rehearse a release on a real database: run a backward-compatible migration as its own step, deploy a new version, catch its bug with a smoke test, roll the code back while the schema stays, and measure the errors during the switch.
Contentsand lesson path
On this page
- Release order: migrate, deploy, verify, roll back code
- On PostgreSQL: locks and transactions
- Lab steps
- Check your understanding
- Apply it
- Review prompt
Lessons of Service Production Readiness
- What Changes Between Your Laptop and Production Concept · 15 min
- Workers, Processes and the Reverse Proxy Worked example · 25 min
- Health, Readiness and Graceful Shutdown Worked example · 25 min
- Configuration That Fails Fast Concept · 15 min
- Lab: A Release with Migrations, Smoke Tests and Rollback Lab · 30 min
- Check: Production Readiness Review Knowledge check · 8 questions
What you will learn
- Sequence a release so backward-compatible migrations run as a separate step before new code, verify it with smoke tests, and roll back application code without rolling back the schema.
- Implement liveness and readiness checks that reflect real dependencies, and shut down gracefully on SIGTERM by draining in-flight requests and jobs.
Prerequisites: Database Schema Migrations
01. Release order: migrate, deploy, verify, roll back code
A release that changes the database has two parts that fail in different ways: the schema change and the new code. This lab rehearses an order that keeps them independent, with a real database, two app versions and a smoke test that catches a broken release.
Why not migrate when each container starts? Putting alembic upgrade head && exec uvicorn ... in the entrypoint looks convenient, but with ten replicas, ten processes race to change the same tables; without a lock they collide, and with one they queue. A migration that takes minutes makes every new container miss its startup probe, so the orchestrator restarts it again and again. A migration that fails halfway leaves you unsure which schema the old and new containers face.
The safer order runs the migration once, as its own release step, before any new code ships: a Kubernetes Job, a pipeline stage or a platform's release command (the Twelve-Factor App calls these one-off admin processes). If it fails, the pipeline stops and the running version keeps serving. Only after it succeeds does the pipeline roll out new code, run smoke tests, and either finish or roll the code back.
That order only works if every migration is backward-compatible: during the rollout, and after a rollback, the previous code runs against the new schema. Expand and contract reaches a breaking change in safe steps. To rename fullname to display_name:
- Expand: add
display_nameas a nullable column; old code ignores it. - Deploy code that reads
display_namewith a fallback tofullnameand writes both. - Backfill old rows in small batches.
- Contract: in a later release, once no running code reads
fullname, drop it.
The lab performs step 1 and the read side of step 2.
02. On PostgreSQL: locks and transactions
The lab uses SQLite from Python's standard library so it runs anywhere without a database server; each move maps to PostgreSQL. ALTER TABLE ... ADD COLUMN takes an ACCESS EXCLUSIVE lock, held only briefly for a nullable column without a volatile default. But if a long query holds the table, the DDL waits in the lock queue and every later query on that table waits behind it. So the release job runs SET lock_timeout = '2s'; and retries instead of stalling traffic. A plain CREATE INDEX blocks writes for the whole build; CREATE INDEX CONCURRENTLY does not, but PostgreSQL refuses it inside a transaction (in Alembic, wrap it in with op.get_context().autocommit_block():). Add a foreign key as NOT VALID, which applies to new rows at once, and run VALIDATE CONSTRAINT later under a lock that lets writes continue.
Two release jobs must not migrate at once, so the job first takes pg_advisory_lock(<id>); in the lab, BEGIN IMMEDIATE plays that role. PostgreSQL runs DDL inside transactions, and Alembic's default env.py runs all pending migrations of one alembic upgrade in a single transaction: if the second of two fails, the first and its alembic_version row roll back too, and the next run starts from the first again (transaction_per_migration=True commits each migration separately). The lab's migrate.py behaves like that default.
03. Lab steps
Step 1: ship the first release. You need Python 3.9 or later (tested with 3.13), Bash, curl and patch. Create the folder and the first migration, then save the four files below. migrate.py takes SQLite's write lock with BEGIN IMMEDIATE, applies every pending file in one transaction and records it in schema_migrations. deploy.sh replaces the running app and waits until /healthz answers. smoke.sh checks health, a profile read and a checkout write, and exits 1 at the first failure, so a pipeline can stop on it. It creates a real order; in production, smoke tests use a test account.
mkdir -p release-lab/migrations release-lab/releases/v1 release-lab/releases/v2
cd release-lab && export LAB="$PWD"
cat > migrations/0001_init.sql <<'SQL'
CREATE TABLE users (id INTEGER PRIMARY KEY, fullname TEXT NOT NULL);
CREATE TABLE orders (id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users (id),
quantity INTEGER NOT NULL);
INSERT INTO users (id, fullname) VALUES (1, 'Ada Lovelace');
SQL
python3 -c "import sys; assert sys.version_info >= (3, 9); print('python ok')"python ok"""Release step: apply pending migrations/NNNN_*.sql in order, then print the schema."""
import pathlib
import sqlite3
import sys
conn = sqlite3.connect(sys.argv[1], timeout=5, isolation_level=None)
conn.execute("BEGIN IMMEDIATE") # write lock: a second migrate job waits up to 5 s
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY)")
done = {row[0] for row in conn.execute("SELECT version FROM schema_migrations")}
try:
for path in sorted(pathlib.Path("migrations").glob("*.sql")):
if path.stem in done:
continue
for statement in path.read_text().split(";"):
if statement.strip():
conn.execute(statement)
conn.execute("INSERT INTO schema_migrations VALUES (?)", (path.stem,))
print("applied", path.stem)
conn.execute("COMMIT")
except sqlite3.Error as exc:
conn.execute("ROLLBACK") # DDL is transactional here, as in PostgreSQL
sys.exit(f"migration failed, nothing applied: {exc}")
versions = [row[0] for row in conn.execute("SELECT version FROM schema_migrations")]
columns = [row[1] for row in conn.execute("PRAGMA table_info(users)")]
print("schema at", max(versions), "| users:", ", ".join(columns))"""orders service v1: reads fullname."""
import json
import sqlite3
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
VERSION, DB = "v1", sys.argv[2]
class App(BaseHTTPRequestHandler):
def reply(self, status, data):
body = (json.dumps(data) + "\n").encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/healthz":
return self.reply(200, {"version": VERSION})
user_id = self.path.removeprefix("/users/")
row = sqlite3.connect(DB).execute(
"SELECT fullname FROM users WHERE id = ?", (user_id,)).fetchone()
self.reply(200, {"name": row[0]}) if row else self.reply(404, {})
def do_POST(self): # POST /orders {"user_id": 1, "quantity": 2}
order = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
try:
with sqlite3.connect(DB, timeout=2) as conn:
cur = conn.execute(
"INSERT INTO orders (user_id, quantity) VALUES (?, ?)",
(order["user_id"], order["quantity"]))
self.reply(201, {"order_id": cur.lastrowid})
except (KeyError, sqlite3.Error) as exc:
self.reply(500, {"error": repr(exc)})
def log_message(self, *args):
pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), App).serve_forever()#!/usr/bin/env bash
# Usage: deploy.sh <release> stops the running app, starts releases/<release>/app.py
set -euo pipefail
PORT=8710
if [ -f app.pid ] && kill "$(cat app.pid)" 2> /dev/null; then
while kill -0 "$(cat app.pid)" 2> /dev/null; do sleep 0.1; done
fi
python3 "releases/$1/app.py" "$PORT" orders.db > "app-$1.log" 2>&1 &
echo $! > app.pid
for _ in $(seq 50); do # readiness: wait until /healthz answers
curl -sf -o /dev/null "http://127.0.0.1:$PORT/healthz" && break
sleep 0.1
done
echo "deployed $(curl -s "http://127.0.0.1:$PORT/healthz")"#!/usr/bin/env bash
# Usage: smoke.sh [base-url] prints each check and exits 1 at the first failure
set -u
BASE="${1:-http://127.0.0.1:8710}"
check() { # check <name> <wanted HTTP status> <curl arguments...>
local name="$1" want="$2" got
shift 2
got=$(curl -s -o /dev/null -w '%{http_code}' "$@")
if [ "$got" != "$want" ]; then echo "FAIL $name: HTTP $got, wanted $want"; exit 1; fi
echo "ok $name"
}
check health 200 "$BASE/healthz"
check profile 200 "$BASE/users/1"
check checkout 201 -X POST -H 'Content-Type: application/json' \
-d '{"user_id": 1, "quantity": 2}' "$BASE/orders"
echo "smoke passed against $(curl -s "$BASE/healthz")"cd "$LAB"
python3 migrate.py orders.db # release step 1: schema
bash deploy.sh v1 # release step 2: code
bash smoke.sh # release step 3: verifyapplied 0001_init
schema at 0001_init | users: id, fullname
deployed {"version": "v1"}
ok health
ok profile
ok checkout
smoke passed against {"version": "v1"}Step 2: expand the schema as its own step. Add the nullable column and run the migration job while v1 is still serving; a second run finds nothing to do. The smoke test against v1 is the check that matters: the old code works with the new schema, so a rollback to it will be safe.
cd "$LAB"
echo "ALTER TABLE users ADD COLUMN display_name TEXT;" \
> migrations/0002_add_display_name.sql # nullable, no default: v1 ignores it
python3 migrate.py orders.db
python3 migrate.py orders.db # a rerun applies nothing
bash smoke.sh # v1 is still serving, now on the new schemaapplied 0002_add_display_name
schema at 0002_add_display_name | users: id, fullname, display_name
schema at 0002_add_display_name | users: id, fullname, display_name
ok health
ok profile
ok checkout
smoke passed against {"version": "v1"}Step 3: deploy v2 and let the smoke test catch it. v2 reads display_name with a fallback to fullname. It also reads the checkout field as qty, while clients still send quantity: the kind of rename that unit tests with updated fixtures miss. The patch shows the whole change; save it, then build and deploy v2.
--- releases/v1/app.py
+++ releases/v2/app.py
@@ -1,10 +1,10 @@
-"""orders service v1: reads fullname."""
+"""orders service v2: reads display_name, falls back to fullname."""
import json
import sqlite3
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
-VERSION, DB = "v1", sys.argv[2]
+VERSION, DB = "v2", sys.argv[2]
class App(BaseHTTPRequestHandler):
@@ -21,7 +21,8 @@
return self.reply(200, {"version": VERSION})
user_id = self.path.removeprefix("/users/")
row = sqlite3.connect(DB).execute(
- "SELECT fullname FROM users WHERE id = ?", (user_id,)).fetchone()
+ "SELECT COALESCE(display_name, fullname) FROM users WHERE id = ?",
+ (user_id,)).fetchone()
self.reply(200, {"name": row[0]}) if row else self.reply(404, {})
def do_POST(self): # POST /orders {"user_id": 1, "quantity": 2}
@@ -30,7 +31,7 @@
with sqlite3.connect(DB, timeout=2) as conn:
cur = conn.execute(
"INSERT INTO orders (user_id, quantity) VALUES (?, ?)",
- (order["user_id"], order["quantity"]))
+ (order["user_id"], order["qty"])) # bug: clients send "quantity"
self.reply(201, {"order_id": cur.lastrowid})
except (KeyError, sqlite3.Error) as exc:
self.reply(500, {"error": repr(exc)})cd "$LAB"
cp releases/v1/app.py releases/v2/app.py && patch -s releases/v2/app.py < v2.patch
bash deploy.sh v2
bash smoke.sh; echo "smoke exit code: $?"
curl -s -X POST -d '{"user_id": 1, "quantity": 2}' http://127.0.0.1:8710/ordersdeployed {"version": "v2"}
ok health
ok profile
FAIL checkout: HTTP 500, wanted 201
smoke exit code: 1
{"error": "KeyError('qty')"}Health and profile pass, so a readiness probe alone would have accepted v2. The checkout check fails, smoke.sh exits 1, and the response body names the cause.
Step 4: roll back the code, not the schema. Deploy v1 again, repeat the smoke test, and look at the schema and the stored orders.
cd "$LAB"
bash deploy.sh v1 # roll back the code only
bash smoke.sh
python3 migrate.py orders.db # the schema stays at 0002
python3 -c "import sqlite3; print(sqlite3.connect('orders.db').execute(
'SELECT COUNT(*), SUM(quantity) FROM orders').fetchone())"deployed {"version": "v1"}
ok health
ok profile
ok checkout
smoke passed against {"version": "v1"}
schema at 0002_add_display_name | users: id, fullname, display_name
(3, 6)v1 serves again with display_name still in place. Nothing was migrated down: in an incident, a down-migration risks losing data written since the release, and the fixed v2 will need the column anyway. The orders table holds the three successful smoke checkouts, two quantities each; the failed v2 checkouts wrote nothing.
Step 5: measure what the switch cost. deploy.sh stops one process before it starts the next, so for a moment nothing listens. Send health requests about every 10 ms while you redeploy v1 and count the answers; 000 means curl could not connect.
cd "$LAB"
for _ in $(seq 200); do # about one health request every 10 ms during a redeploy
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8710/healthz; sleep 0.01
done > switch.log &
sleep 0.5 && bash deploy.sh v1 > /dev/null; wait
sort switch.log | uniq -c 4 000
196 200In one run, 4 of 200 requests failed during one switch of a single process on a laptop; a rerun on a busy shared server counted 64, because the new process took longer to start. Your count will differ. This is why production rollouts start the new instances, wait for readiness, move traffic, and only then stop the old ones with a graceful shutdown, as in the health and shutdown lesson. Even then, measure errors during a release instead of assuming there were none. Finish with step 6.
cd "$LAB" && kill "$(cat app.pid)" && echo "app stopped"app stopped04. Check your understanding
05. Apply it
Carry the rehearsal into your own pipeline:
- Make the migration a separate pipeline step or Kubernetes
Jobthat runs before the rollout and stops the release when it fails. - Write a smoke test that goes through the table your migration changed, and make the pipeline roll the code back when it exits non-zero.
- Rehearse step 4 on staging: roll back the code and confirm that the previous version passes the smoke test on the new schema.
- Measure failed requests during one rollout of your service, and note the conditions.
06. Review prompt
Without looking back, explain why the lab ran the migration before deploying v2, and what the smoke test against v1 in step 2 proved. Describe the four phases of expand and contract for a column rename, say why the rollback in step 4 left the schema alone, and explain what the count in step 5 tells you and what it does not.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.