Docker Hour 6: Production Applications and Architecture Design
- A lightweight architecture design method: non-functional requirements → data flow → 12-Factor check → architecture decision records (ADRs) and trade-off tables → failure mode analysis.
- Build five common production scenarios hands-on: three-tier web + cache, gateway and HTTPS, async and scheduled jobs, database migrations and zero-downtime releases, file uploads and object storage; for each, explain the data flow, design rationale, failure behavior and Azure managed replacement.
- Design high availability and disaster recovery: zone redundancy (ACA zone-redundant environments, ECS across AZs), multi-region entry points (Front Door / Route 53 failover), image replication (ACR geo-replication vs ECR cross-region), the data tier (PostgreSQL Flexible Server HA / read replicas / geo-redundant backup, RDS Multi-AZ / Aurora), verified with RTO / RPO and drills.
- Score a system with a review checklist and failure mode analysis, find root causes from evidence in incident drills, then deploy to Azure, smoke test and clean up in the right order.
1-hour schedule
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Setup: generate the sample project | One script generates the orders project (30 files) and pulls images | — | Environment check |
| 1 | 00–05 | Architecture design method | 12-Factor, reference architecture, ADRs, trade-off tables, one image, several process types | From requirements to architecture (four design mistakes) + 12-Factor self-checker | Start the whole system |
| 2 | 05–13 | ① Three-tier web ⭐ | Connection pools and budget, cache-aside and degradation, liveness/readiness probes, idempotency keys | The journey of one request (six cases) + connection budget calculator | Idempotency, caching, scaling replicas, graceful degradation |
| 3 | 13–20 | ② Gateway and HTTPS | TLS termination, 301, rate limiting 429, 413, request IDs, resolver 127.0.0.11; ACA ingress / Front Door | A request through the gateway (six outcomes) + gateway routing simulator | Certificates, rate limiting, body size limit, DNS trap |
| 4 | 20–28 | ③ Async and scheduled jobs | ack, retries, dead-lettering, idempotent consumers, graceful shutdown, cron; Service Bus + KEDA + ACA Jobs | The life of a message (six endings) + live queue simulator | Backlog, poison messages, graceful shutdown, daily report |
| 5 | 28–35 | ④ Database migrations and releases | One-off migration job, advisory locks, expand/contract, lock_timeout, backup-restore drill, PITR | A release with a schema change (six paths) | Concurrent migrations, contract, backup → restore |
| 6 | 35–42 | ⑤ File uploads and object storage | Azurite, short-lived read-only SAS, user delegation SAS, disabling Shared Key, direct upload | Upload and download (seven cases) | Upload, SAS, tampering 403, sharing across replicas |
| 7 | 42–51 | ⑥ High availability and disaster recovery (new) | Failure domains and RTO/RPO, ACA zone redundancy vs ECS across AZs, Front Door / Route 53 failover, ACR geo-replication vs ECR replication, PG HA / read replicas / geo-redundant backup vs RDS Multi-AZ / Aurora, DR drills | Failure and failover simulator (Azure / AWS × six failures) + RTO/RPO calculator | Tabletop drill: write a DR runbook for orders |
| 8 | 51–60 | Architecture review and incident drill | Failure mode analysis, Well-Architected review scoring, 7 incident drills, interactive troubleshooting tree, preview of hour 7 | Incident postmortem timeline + review scorer | End-to-end smoke test, incident drills, cleanup |
| — | After class | Cheat sheet · Final lab | Deploy to Azure with azure/deploy.sh → smoke test → observe scaling → verify security → clean up | Final quiz (12 questions) | Final lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / objects | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Architecture method (12-Factor, ADRs, failure analysis) | ✓ | · | · | · | · | · | ✓ | ✓ | docs/adr/*.md, compose.yaml anchors | M1 / M8 |
| Connection pools, caching, probes, idempotency | · | ✓ | · | ✓ | · | · | ✓ | ✓ | pg_stat_activity, redis-cli, /readyz | M2 |
| Gateway, TLS, rate limiting | · | · | ✓ | · | · | ✓ | ✓ | ✓ | nginx -t, openssl s_client, limit_req | M3 |
| Queues, dead-lettering, graceful shutdown, scheduled jobs | ✓ | · | · | ✓ | · | · | · | ✓ | rabbitmqctl list_queues, KEDA, az containerapp job | M4 |
| Migrations, expand/contract, backup and restore | ✓ | · | · | · | ✓ | · | ✓ | ✓ | pg_advisory_lock, pg_dump -Fc, PITR | M5 |
| Object storage and SAS | · | · | ✓ | · | · | ✓ | ✓ | ✓ | generate_blob_sas, --allow-shared-key-access false | M6 |
| Zone redundancy and multi-region DR | · | · | ✓ | · | ✓ | · | ✓ | ✓ | --zone-redundant, az acr replication, --zonal-resiliency, replica promote | M7 |
| Reviews, drills and smoke tests | ✓ | · | · | · | · | · | ✓ | ✓ | smoke.sh, Well-Architected checklist | M8 / Final lab |
What this lesson leaves out (and where to learn it)
| Topic | Why not here | Where to learn it |
|---|---|---|
| Writing multi-stage, non-root Dockerfiles with health checks | Hour 2; used as-is here | Hour 2 |
| Image CI, signing, promotion by digest, ACA traffic splitting / ECS blue/green rollback | Release pipeline; here we only plug in the migration job | Hour 5, Module 7 |
| Basic deployment with ECS / ALB / ECR | AWS appears here only as an architectural comparison | Hour 4 |
| Metrics, alert rules, SLOs and dashboards | Here we only list what to alert on | Prometheus & Grafana in 8 + 1 Hours (Chinese) |
| Managing the whole infrastructure (including multi-region) with Terraform | Infrastructure as code; here concepts use the CLI | Terraform in 8 Hours (Chinese) |
| Deep troubleshooting, load testing and performance tuning, chaos experiments | Needs its own lesson | Hour 7 |
How to use this course
Concepts · Diagram · Animation · Commands · Lab · In Production · Troubleshooting · Quiz · Audio · Video. Every animation has failure branches: pick one to see where the system breaks, then compare with the real error in "Troubleshooting".
A quiz score ≥ 70% or "Mark this module complete" counts, saved in this browser (shared with the course index; resets on refresh if local storage is blocked).
The "Audio" tab reads the scripts with the browser's Web Speech API (en-US); without an English voice, read them or use a TTS tool.
Module 0 · Setup: generate the sample project (before class)
- An Ubuntu 24.04 VM (2 vCPU / 4 GiB or more recommended) with Docker Engine 29.x and Compose v5.x installed (Hour 1, Module 0).
- Access to Docker Hub and mcr.microsoft.com; the VM security group opens ports 8443/8080 (or use SSH port forwarding).
- The final lab needs Azure CLI 2.75+ (some Module 7 commands need 2.86+) and a subscription where you have Contributor + User Access Administrator. The cloud resources from Hours 3–5 should already be cleaned up as in Hour 5, Module 8.
Step 1: check the environment
docker version --format 'Engine {{.Server.Version}}'
sudo apt-get install -y jq openssl # the labs use jq to parse JSON
docker compose version
free -h | head -2; nproc
Engine 29.x.x Docker Compose version v5.x.x Mem: 3.8Gi … 2
Step 2: generate the project
Download orders-bootstrap-part6.sh (kept in the same folder as this page), or expand the block below, copy everything and save it on the VM under the same file name. The script is shared with the Chinese edition, so its comments and echo messages are in Chinese; the code is identical.
Full text of orders-bootstrap-part6.sh (click to expand, about 39 KB)
#!/usr/bin/env bash
# 第六课示例项目 orders 一键生成脚本:bash orders-bootstrap-part6.sh → 生成 ~/orders
set -euo pipefail
D=${1:-$HOME/orders}; mkdir -p "$D"; cd "$D"
cat > .env.example <<'ORDERS_EOF'
# 复制为 .env 并修改密码;.env 不要提交到 Git
DB_PASSWORD=change-me-db
MQ_PASSWORD=change-me-mq
# Azurite 的公开开发账户(文档公开的固定 key,只能用于本机)
AZURITE_CONN=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://azurite:10000/devstoreaccount1;
ORDERS_EOF
cat > .gitignore <<'ORDERS_EOF'
.env
gateway/certs/
__pycache__/
ORDERS_EOF
cat > README.md <<'ORDERS_EOF'
# orders — Docker 第 6 小时示例项目
订单系统:SPA + nginx 网关(HTTPS/限流)+ Flask API(连接池、旁路缓存、幂等键)
+ PostgreSQL + Redis + RabbitMQ Worker(重试/死信/优雅停机)+ 迁移任务 + 定时报表 + Azurite(Blob + SAS)。
```bash
cp .env.example .env # 修改密码
./gen-cert.sh # 自签名证书
docker compose up -d --build # https://localhost:8443
docker compose run --rm report # 定时任务(手动运行)
bash azure/deploy.sh # 部署到 Azure(付费资源,用完 az group delete)
```
课程:docker-h6.html
ORDERS_EOF
cat > compose.yaml <<'ORDERS_EOF'
name: orders
x-app: &app
image: orders:1.0
build: ./app
environment: &app-env
DATABASE_URL: postgresql://orders:${DB_PASSWORD:?run cp .env.example .env}@postgres:5432/orders
REDIS_URL: redis://redis:6379/0
QUEUE_BACKEND: rabbitmq
RABBITMQ_URL: amqp://orders:${MQ_PASSWORD:?run cp .env.example .env}@rabbitmq:5672/
STORAGE_CONNECTION_STRING: ${AZURITE_CONN}
BLOB_PUBLIC_BASE: https://localhost:8443/blob
APP_VERSION: "1.0"
restart: unless-stopped
stop_grace_period: 30s
services:
migrate: # 一次性任务:迁移成功后才启动 api / worker
<<: *app
command: ["orders-migrate"]
restart: "no"
depends_on:
postgres: { condition: service_healthy }
api:
<<: *app
depends_on:
migrate: { condition: service_completed_successfully }
redis: { condition: service_healthy }
rabbitmq: { condition: service_healthy }
azurite: { condition: service_started }
deploy:
replicas: 2
resources: { limits: { cpus: "0.5", memory: 256M } }
worker:
<<: *app
command: ["orders-worker"]
healthcheck: { disable: true }
depends_on:
migrate: { condition: service_completed_successfully }
rabbitmq: { condition: service_healthy }
deploy:
replicas: 2
report: # 定时任务:docker compose run --rm report(由主机 cron / ACA Job 触发)
<<: *app
command: ["orders-report"]
restart: "no"
healthcheck: { disable: true }
profiles: [jobs]
depends_on:
postgres: { condition: service_healthy }
gateway:
image: nginx:1.29-alpine
ports: ["8443:443", "8080:80"]
volumes:
- ./gateway/nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./gateway/certs:/etc/nginx/certs:ro
- ./web:/usr/share/nginx/html:ro
depends_on: [api]
restart: unless-stopped
postgres:
image: postgres:17
environment:
POSTGRES_USER: orders
POSTGRES_PASSWORD: ${DB_PASSWORD:?run cp .env.example .env}
POSTGRES_DB: orders
volumes: [pgdata:/var/lib/postgresql/data]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U orders -d orders"]
interval: 5s
timeout: 3s
retries: 10
restart: unless-stopped
redis:
image: redis:7-alpine
command: ["redis-server", "--appendonly", "yes", "--maxmemory", "128mb", "--maxmemory-policy", "allkeys-lru"]
volumes: [redisdata:/data]
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
retries: 10
restart: unless-stopped
rabbitmq:
image: rabbitmq:4-management
environment:
RABBITMQ_DEFAULT_USER: orders
RABBITMQ_DEFAULT_PASS: ${MQ_PASSWORD:?run cp .env.example .env}
ports: ["127.0.0.1:15672:15672"] # 管理界面只绑定本机
volumes: [mqdata:/var/lib/rabbitmq]
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 10s
timeout: 5s
retries: 12
restart: unless-stopped
azurite:
image: mcr.microsoft.com/azure-storage/azurite
command: ["azurite-blob", "--blobHost", "0.0.0.0", "--location", "/data", "--skipApiVersionCheck"]
volumes: [blobdata:/data]
restart: unless-stopped
volumes:
pgdata:
redisdata:
mqdata:
blobdata:
ORDERS_EOF
cat > gen-cert.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# 生成本机自签名证书(仅开发用;生产用 ACA 托管证书 / Let's Encrypt / Key Vault 证书)
set -euo pipefail
mkdir -p gateway/certs
openssl req -x509 -newkey rsa:2048 -nodes -days 30 \
-keyout gateway/certs/tls.key -out gateway/certs/tls.crt \
-subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
chmod 644 gateway/certs/tls.key # 容器内 nginx master 以 root 读取;勿在生产这样做
echo "证书已生成:gateway/certs/"
ORDERS_EOF
mkdir -p app
cat > app/.dockerignore <<'ORDERS_EOF'
__pycache__
*.pyc
.git
migrations-contract
ORDERS_EOF
mkdir -p app
cat > app/Dockerfile <<'ORDERS_EOF'
# syntax=docker/dockerfile:1
# check=error=true
ARG PYTHON_VERSION=3.13
FROM python:${PYTHON_VERSION}-slim AS builder
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
FROM python:${PYTHON_VERSION}-slim AS runtime
LABEL org.opencontainers.image.source="https://github.com/yourname/orders" \
org.opencontainers.image.title="orders"
RUN useradd --uid 10001 --create-home app
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
COPY --chown=10001:10001 orders ./orders
COPY --chown=10001:10001 migrations ./migrations
COPY --chmod=755 bin/ /usr/local/bin/
USER 10001:10001
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --start-interval=1s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
# 同一个镜像,多种进程类型(12-Factor):api(默认)、orders-worker、orders-migrate、orders-report
CMD ["gunicorn", "-b", "0.0.0.0:8000", "-w", "2", "--graceful-timeout", "20", "--access-logfile", "-", "orders.api:app"]
ORDERS_EOF
mkdir -p app
cat > app/requirements.txt <<'ORDERS_EOF'
flask==3.1.*
gunicorn==23.*
psycopg[binary]==3.2.*
psycopg-pool==3.2.*
redis==5.*
pika==1.3.*
azure-storage-blob==12.*
azure-identity==1.*
azure-servicebus==7.*
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-migrate <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.migrate "$@"
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-report <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.report "$@"
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-worker <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.worker "$@"
ORDERS_EOF
mkdir -p app/migrations
cat > app/migrations/001_init.sql <<'ORDERS_EOF'
CREATE TABLE IF NOT EXISTS orders (
id bigserial PRIMARY KEY,
item text NOT NULL,
qty integer NOT NULL CHECK (qty > 0),
status text NOT NULL DEFAULT 'pending',
idempotency_key text UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz
);
CREATE TABLE IF NOT EXISTS daily_reports (
day date PRIMARY KEY,
orders integer NOT NULL,
items integer NOT NULL,
generated_at timestamptz NOT NULL
);
ORDERS_EOF
mkdir -p app/migrations
cat > app/migrations/002_expand_customer_email.sql <<'ORDERS_EOF'
-- 扩展(expand)阶段:只新增可空列,旧版本应用不受影响
ALTER TABLE orders ADD COLUMN IF NOT EXISTS customer_email text;
CREATE INDEX IF NOT EXISTS ix_orders_created_at ON orders (created_at);
ORDERS_EOF
mkdir -p app/migrations-contract
cat > app/migrations-contract/003_contract_customer_email.sql <<'ORDERS_EOF'
-- 收缩(contract)阶段:确认所有运行中的版本都会写 customer_email 之后,才移动到 migrations/ 执行
UPDATE orders SET customer_email = 'unknown@example.com' WHERE customer_email IS NULL;
ALTER TABLE orders ALTER COLUMN customer_email SET NOT NULL;
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/__init__.py <<'ORDERS_EOF'
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/api.py <<'ORDERS_EOF'
"""订单 API:旁路缓存、幂等创建、异步处理、文件上传。"""
import json, os, socket, uuid
from flask import Flask, jsonify, request, abort
import psycopg
import redis as redislib
from . import config, db, queueing, storage
from .log import get_logger, info
log = get_logger("api")
app = Flask(__name__)
cache = redislib.Redis.from_url(config.REDIS_URL, socket_timeout=0.5, socket_connect_timeout=0.5)
db.ensure_open()
def cache_get(key):
try:
v = cache.get(key)
return json.loads(v) if v else None
except redislib.RedisError:
log.warning("cache unavailable, falling back to database") # 缓存故障不影响正确性
return None
def cache_set(key, value, ttl=config.CACHE_TTL):
try:
cache.setex(key, ttl, json.dumps(value, default=str))
except redislib.RedisError:
pass
def cache_del(*keys):
try:
cache.delete(*keys)
except redislib.RedisError:
pass
@app.get("/healthz")
def healthz(): # 存活:只检查进程自身
return "ok"
@app.get("/readyz")
def readyz():
"""就绪:依赖可用才接流量。用独立的短连接 + connect_timeout,
避免探针在“数据库无响应”时卡在池中的连接上(连接池的 timeout 只管“借连接”,不管查询)。"""
try:
with psycopg.connect(config.DATABASE_URL, connect_timeout=2) as conn:
conn.execute("SELECT 1")
except Exception as e:
log.warning("not ready: %s", e)
return "database unavailable", 503
return "ready"
@app.post("/api/orders")
def create_order():
body = request.get_json(silent=True) or {}
item, qty = body.get("item"), body.get("qty")
if not item or not isinstance(qty, int) or qty <= 0:
abort(400, "item 与正整数 qty 为必填项")
key = request.headers.get("Idempotency-Key") or str(uuid.uuid4())
with db.pool.connection() as conn:
row = conn.execute(
"""INSERT INTO orders (item, qty, customer_email, idempotency_key)
VALUES (%s, %s, %s, %s)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id, status""",
(item, qty, body.get("email"), key)).fetchone()
created = row is not None
if not created: # 客户端重试:返回第一次创建的订单,不重复下单
row = conn.execute("SELECT id, status FROM orders WHERE idempotency_key=%s", (key,)).fetchone()
if created:
queueing.publish({"order_id": row["id"]}) # 生产中可用“发件箱”模式保证写库与发消息的一致性
cache_del("stats")
info(log, "order accepted", order_id=row["id"], created=created)
return jsonify(id=row["id"], status=row["status"], created=created), 202 if created else 200
@app.get("/api/orders/<int:order_id>")
def get_order(order_id):
key = f"order:{order_id}"
hit = cache_get(key)
if hit:
return jsonify(hit | {"cache": "hit"})
with db.pool.connection() as conn:
row = conn.execute("SELECT * FROM orders WHERE id=%s", (order_id,)).fetchone()
if not row:
abort(404)
if row["status"] != "pending": # 只缓存“稳定”的数据,待处理订单状态会变化
cache_set(key, row)
return jsonify(row | {"cache": "miss"})
@app.get("/api/orders")
def list_orders():
with db.pool.connection() as conn:
rows = conn.execute("SELECT id, item, qty, status, created_at FROM orders ORDER BY id DESC LIMIT 20").fetchall()
return jsonify(rows)
@app.get("/api/stats")
def stats():
hit = cache_get("stats")
if hit:
return jsonify(hit | {"cache": "hit", "served_by": socket.gethostname(), "version": config.APP_VERSION})
with db.pool.connection() as conn:
row = conn.execute("""SELECT count(*) AS orders, coalesce(sum(qty),0) AS items,
count(*) FILTER (WHERE status='processed') AS processed FROM orders""").fetchone()
cache_set("stats", row, ttl=10)
return jsonify(row | {"cache": "miss", "served_by": socket.gethostname(), "version": config.APP_VERSION})
@app.post("/api/files")
def upload_file():
f = request.files.get("file")
if not f:
abort(400, "缺少 file")
name = f"{uuid.uuid4().hex}-{os.path.basename(f.filename or 'upload.bin')}"
storage.upload(name, f.stream, f.mimetype or "application/octet-stream")
info(log, "file uploaded", blob=name)
return jsonify(name=name, url=storage.download_url(name)), 201
@app.get("/api/files/<name>/url")
def file_url(name):
return jsonify(url=storage.download_url(name))
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/config.py <<'ORDERS_EOF'
"""12-Factor:所有配置都来自环境变量。"""
import os
DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://orders:orders@localhost:5432/orders")
DB_POOL_SIZE = int(os.getenv("DB_POOL_SIZE", "5"))
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
CACHE_TTL = int(os.getenv("CACHE_TTL", "60"))
QUEUE_BACKEND = os.getenv("QUEUE_BACKEND", "none") # rabbitmq | servicebus | none
QUEUE_NAME = os.getenv("QUEUE_NAME", "orders")
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@localhost:5672/")
SERVICEBUS_NAMESPACE = os.getenv("SERVICEBUS_NAMESPACE", "") # <ns>.servicebus.windows.net
MAX_RETRIES = int(os.getenv("MAX_RETRIES", "3"))
STORAGE_CONNECTION_STRING = os.getenv("STORAGE_CONNECTION_STRING", "") # 本机 Azurite
STORAGE_ACCOUNT_URL = os.getenv("STORAGE_ACCOUNT_URL", "") # Azure:https://<acct>.blob.core.windows.net
BLOB_CONTAINER = os.getenv("BLOB_CONTAINER", "files")
BLOB_PUBLIC_BASE = os.getenv("BLOB_PUBLIC_BASE", "") # 本机经网关访问 Azurite 时改写 URL
APP_VERSION = os.getenv("APP_VERSION", "dev")
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/db.py <<'ORDERS_EOF'
"""数据库连接池:每个进程一个池,池大小 × 进程数 × 副本数 必须小于数据库 max_connections。"""
from psycopg_pool import ConnectionPool
from psycopg.rows import dict_row
from . import config
pool = ConnectionPool(config.DATABASE_URL, min_size=1, max_size=config.DB_POOL_SIZE,
kwargs={"row_factory": dict_row,
"options": "-c statement_timeout=5000"}, # 服务端:单条语句最长 5 秒
open=False)
def ensure_open():
if pool.closed:
pool.open(wait=True, timeout=10)
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/log.py <<'ORDERS_EOF'
"""结构化(JSON)日志输出到 stdout。"""
import json, logging, sys, time
class JsonFormatter(logging.Formatter):
def format(self, record):
d = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "level": record.levelname,
"logger": record.name, "msg": record.getMessage()}
d.update(getattr(record, "extra_fields", {}))
if record.exc_info:
d["exc"] = self.formatException(record.exc_info)
return json.dumps(d, ensure_ascii=False)
def get_logger(name):
log = logging.getLogger(name)
if not log.handlers:
h = logging.StreamHandler(sys.stdout)
h.setFormatter(JsonFormatter())
log.addHandler(h)
log.setLevel(logging.INFO)
log.propagate = False
return log
def info(log, msg, **fields):
log.info(msg, extra={"extra_fields": fields})
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/migrate.py <<'ORDERS_EOF'
"""极简迁移工具:按文件名顺序执行 migrations/*.sql,每个文件一个事务;
用 PostgreSQL 咨询锁保证多个副本同时启动时只有一个在迁移。生产中可用 Alembic / Flyway。"""
import glob, os, sys
import psycopg
from . import config
from .log import get_logger, info
log = get_logger("migrate")
LOCK_ID = 727274
DIR = os.getenv("MIGRATIONS_DIR", os.path.join(os.path.dirname(__file__), "..", "migrations"))
def main():
with psycopg.connect(config.DATABASE_URL, autocommit=True) as conn:
conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
try:
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations
(version text PRIMARY KEY, applied_at timestamptz DEFAULT now())""")
done = {r[0] for r in conn.execute("SELECT version FROM schema_migrations")}
for path in sorted(glob.glob(os.path.join(DIR, "*.sql"))):
ver = os.path.basename(path)
if ver in done:
continue
with conn.transaction():
conn.execute(open(path, encoding="utf-8").read())
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (ver,))
info(log, "applied", version=ver)
info(log, "up to date", applied=len(done))
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
if __name__ == "__main__":
sys.exit(main())
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/queueing.py <<'ORDERS_EOF'
"""消息队列抽象:本机 RabbitMQ,Azure 上 Service Bus;业务代码不感知差异。"""
import json, signal
from . import config
from .log import get_logger, info
log = get_logger("queue")
# ---------------- RabbitMQ ----------------
def _rabbit_channel():
import pika
conn = pika.BlockingConnection(pika.URLParameters(config.RABBITMQ_URL))
ch = conn.channel()
# 死信:失败超过重试次数的消息进入 orders.dlq
ch.exchange_declare("orders.dlx", "fanout", durable=True)
ch.queue_declare(f"{config.QUEUE_NAME}.dlq", durable=True)
ch.queue_bind(f"{config.QUEUE_NAME}.dlq", "orders.dlx")
ch.queue_declare(config.QUEUE_NAME, durable=True,
arguments={"x-dead-letter-exchange": "orders.dlx"})
return conn, ch
def publish(message: dict):
body = json.dumps(message)
if config.QUEUE_BACKEND == "rabbitmq":
import pika
conn, ch = _rabbit_channel()
try:
ch.basic_publish("", config.QUEUE_NAME, body,
pika.BasicProperties(delivery_mode=2, content_type="application/json"))
finally:
conn.close()
elif config.QUEUE_BACKEND == "servicebus":
from azure.identity import DefaultAzureCredential
from azure.servicebus import ServiceBusClient, ServiceBusMessage
with ServiceBusClient(config.SERVICEBUS_NAMESPACE, DefaultAzureCredential()) as sb:
with sb.get_queue_sender(config.QUEUE_NAME) as sender:
sender.send_messages(ServiceBusMessage(body, content_type="application/json"))
info(log, "published", backend=config.QUEUE_BACKEND, message=message)
def consume(handler):
"""handler(dict) 抛出异常表示处理失败。收到 SIGTERM 后处理完当前消息再退出(优雅停机)。"""
stopping = {"flag": False}
def _stop(signum, frame):
stopping["flag"] = True
info(log, "SIGTERM received, finishing current message")
signal.signal(signal.SIGTERM, _stop)
if config.QUEUE_BACKEND == "rabbitmq":
import pika
conn, ch = _rabbit_channel()
ch.basic_qos(prefetch_count=1)
for method, props, body in ch.consume(config.QUEUE_NAME, inactivity_timeout=1):
if stopping["flag"]:
break
if method is None:
continue
retries = int((props.headers or {}).get("x-retry", 0))
try:
handler(json.loads(body))
ch.basic_ack(method.delivery_tag) # 处理成功后才确认
except Exception:
log.exception("handler failed")
if retries + 1 >= config.MAX_RETRIES:
ch.basic_nack(method.delivery_tag, requeue=False) # → 死信队列
info(log, "dead-lettered", retries=retries + 1)
else:
ch.basic_publish("", config.QUEUE_NAME, body, pika.BasicProperties(
delivery_mode=2, headers={"x-retry": retries + 1}))
ch.basic_ack(method.delivery_tag)
ch.cancel(); conn.close()
elif config.QUEUE_BACKEND == "servicebus":
from azure.identity import DefaultAzureCredential
from azure.servicebus import ServiceBusClient
with ServiceBusClient(config.SERVICEBUS_NAMESPACE, DefaultAzureCredential()) as sb:
with sb.get_queue_receiver(config.QUEUE_NAME, max_wait_time=5) as receiver:
while not stopping["flag"]:
for msg in receiver.receive_messages(max_message_count=1, max_wait_time=5):
try:
handler(json.loads(str(msg)))
receiver.complete_message(msg)
except Exception:
log.exception("handler failed")
# 放弃后 Service Bus 自动重投,超过 MaxDeliveryCount 进入死信子队列
receiver.abandon_message(msg)
else:
raise SystemExit("QUEUE_BACKEND=none:没有可消费的队列")
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/report.py <<'ORDERS_EOF'
"""定时任务:生成某天的订单日报(写入数据库并上传 CSV)。可重复运行(幂等 upsert)。"""
import csv, io, os, sys
from datetime import date, timedelta
from . import db, storage
from .log import get_logger, info
log = get_logger("report")
def main():
day = date.fromisoformat(os.getenv("REPORT_DAY")) if os.getenv("REPORT_DAY") else date.today() - timedelta(days=1)
db.ensure_open()
with db.pool.connection() as conn:
rows = conn.execute("""SELECT item, count(*) AS orders, sum(qty) AS items FROM orders
WHERE created_at::date = %s GROUP BY item ORDER BY item""", (day,)).fetchall()
total_o = sum(r["orders"] for r in rows); total_i = sum(r["items"] for r in rows)
conn.execute("""INSERT INTO daily_reports (day, orders, items, generated_at) VALUES (%s,%s,%s,now())
ON CONFLICT (day) DO UPDATE SET orders=EXCLUDED.orders, items=EXCLUDED.items,
generated_at=now()""", (day, total_o, total_i))
buf = io.StringIO(); w = csv.writer(buf); w.writerow(["item", "orders", "items"])
for r in rows:
w.writerow([r["item"], r["orders"], r["items"]])
name = f"reports/{day.isoformat()}.csv"
storage.container().upload_blob(name, buf.getvalue().encode(), overwrite=True)
info(log, "report generated", day=str(day), orders=total_o, blob=name)
db.pool.close()
if __name__ == "__main__":
sys.exit(main())
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/storage.py <<'ORDERS_EOF'
"""对象存储:本机 Azurite(连接字符串),Azure 上 Blob Storage + 托管标识(用户委托 SAS)。"""
from datetime import datetime, timedelta, timezone
from azure.storage.blob import (BlobServiceClient, BlobSasPermissions, generate_blob_sas)
from . import config
_client = None
def client() -> BlobServiceClient:
global _client
if _client is None:
if config.STORAGE_CONNECTION_STRING:
_client = BlobServiceClient.from_connection_string(config.STORAGE_CONNECTION_STRING)
else:
from azure.identity import DefaultAzureCredential
_client = BlobServiceClient(config.STORAGE_ACCOUNT_URL, credential=DefaultAzureCredential())
return _client
def container():
c = client().get_container_client(config.BLOB_CONTAINER)
if not c.exists():
c.create_container()
return c
def upload(name: str, data, content_type: str):
from azure.storage.blob import ContentSettings
container().upload_blob(name, data, overwrite=False,
content_settings=ContentSettings(content_type=content_type))
def download_url(name: str, minutes: int = 10) -> str:
"""生成短期只读 SAS:浏览器直接从存储下载,不经过 API。"""
svc = client()
start = datetime.now(timezone.utc) - timedelta(minutes=1)
expiry = datetime.now(timezone.utc) + timedelta(minutes=minutes)
kwargs = dict(account_name=svc.account_name, container_name=config.BLOB_CONTAINER,
blob_name=name, permission=BlobSasPermissions(read=True), expiry=expiry, start=start)
if config.STORAGE_CONNECTION_STRING:
kwargs["account_key"] = svc.credential.account_key # 本机 Azurite:账户密钥 SAS
else:
kwargs["user_delegation_key"] = svc.get_user_delegation_key(start, expiry) # Azure:用户委托 SAS
sas = generate_blob_sas(**kwargs)
if config.BLOB_PUBLIC_BASE: # 本机:Azurite 使用路径式地址,经网关 /blob/ 转发
return f"{config.BLOB_PUBLIC_BASE.rstrip('/')}/{svc.account_name}/{config.BLOB_CONTAINER}/{name}?{sas}"
return f"{svc.url.rstrip('/')}/{config.BLOB_CONTAINER}/{name}?{sas}"
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/worker.py <<'ORDERS_EOF'
"""后台 Worker:消费订单消息并处理。处理逻辑是幂等的——同一消息被投递两次也只处理一次。"""
import time
from . import db, queueing
from .log import get_logger, info
log = get_logger("worker")
def handle(msg):
order_id = msg["order_id"]
with db.pool.connection() as conn:
row = conn.execute("SELECT item FROM orders WHERE id=%s", (order_id,)).fetchone()
if row and row["item"] == "poison":
raise ValueError("模拟无法处理的“毒消息”")
time.sleep(0.5) # 模拟耗时处理
cur = conn.execute("""UPDATE orders SET status='processed', processed_at=now()
WHERE id=%s AND status='pending'""", (order_id,))
info(log, "order processed", order_id=order_id, changed=cur.rowcount)
def main():
db.ensure_open()
info(log, "worker started")
queueing.consume(handle)
db.pool.close()
info(log, "worker stopped gracefully")
if __name__ == "__main__":
main()
ORDERS_EOF
mkdir -p azure
cat > azure/deploy.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# 第六课:把 orders 部署到 Azure(Container Apps + PostgreSQL 灵活服务器 + Azure Managed Redis
# + Service Bus + Blob Storage + Key Vault),全部通过用户分配托管标识访问,无连接字符串中的长期密钥(Redis/PG 密码存 Key Vault)。
# 用法:bash azure/deploy.sh 清理:az group delete -n $RG --yes --no-wait
set -euo pipefail
: "${LOC:=canadacentral}"; : "${RG:=rg-docker-hour6}"
SUFFIX=${SUFFIX:-$(openssl rand -hex 3)}
ACR=acrorders$SUFFIX; ENV=cae-orders; ID=id-orders; KV=kv-orders-$SUFFIX
PG=pg-orders-$SUFFIX; REDIS=redis-orders-$SUFFIX; SB=sb-orders-$SUFFIX; ST=storders$SUFFIX
DB_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')
echo "RG=$RG LOC=$LOC SUFFIX=$SUFFIX" | tee ~/hour6.env
az extension add -n containerapp --upgrade -y -o none
az extension add -n redisenterprise --upgrade -y -o none
az group create -n $RG -l $LOC -o none
# ---------- 身份 ----------
az identity create -g $RG -n $ID -o none
ID_RID=$(az identity show -g $RG -n $ID --query id -o tsv)
ID_PID=$(az identity show -g $RG -n $ID --query principalId -o tsv)
ID_CID=$(az identity show -g $RG -n $ID --query clientId -o tsv)
# ---------- 镜像 ----------
az acr create -g $RG -n $ACR --sku Basic -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \
--role AcrPull --scope $(az acr show -n $ACR --query id -o tsv) -o none
az acr build -r $ACR -t orders:1.0 ./app --no-logs
az acr build -r $ACR -t orders-web:1.0 ./web --no-logs
# ---------- 数据:PostgreSQL 灵活服务器 ----------
az postgres flexible-server create -g $RG -n $PG -l $LOC --version 17 \
--tier Burstable --sku-name Standard_B1ms --storage-size 32 \
--admin-user orders --admin-password "$DB_PASSWORD" \
--public-access 0.0.0.0 --yes -o none # 0.0.0.0 = 允许 Azure 内部服务访问;生产用 VNet 集成/私有终结点
az postgres flexible-server db create -g $RG -s $PG -d orders -o none
PG_HOST=$(az postgres flexible-server show -g $RG -n $PG --query fullyQualifiedDomainName -o tsv)
# ---------- 缓存:Azure Managed Redis ----------
az redisenterprise create -g $RG --cluster-name $REDIS -l $LOC --sku Balanced_B0 \
--clustering-policy EnterpriseCluster --access-keys-auth Enabled -o none
REDIS_HOST=$(az redisenterprise show -g $RG --cluster-name $REDIS --query hostName -o tsv)
REDIS_KEY=$(az redisenterprise database list-keys -g $RG --cluster-name $REDIS --query primaryKey -o tsv)
# ---------- 队列:Service Bus ----------
az servicebus namespace create -g $RG -n $SB -l $LOC --sku Standard -o none
az servicebus queue create -g $RG --namespace-name $SB -n orders --max-delivery-count 5 -o none
SB_ID=$(az servicebus namespace show -g $RG -n $SB --query id -o tsv)
for r in "Azure Service Bus Data Sender" "Azure Service Bus Data Receiver"; do
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal --role "$r" --scope $SB_ID -o none
done
# ---------- 对象存储:Blob ----------
az storage account create -g $RG -n $ST -l $LOC --sku Standard_LRS --kind StorageV2 \
--allow-blob-public-access false --allow-shared-key-access false --min-tls-version TLS1_2 -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \
--role "Storage Blob Data Contributor" --scope $(az storage account show -g $RG -n $ST --query id -o tsv) -o none
# ---------- 机密:Key Vault(RBAC 模式) ----------
az keyvault create -g $RG -n $KV -l $LOC --enable-rbac-authorization true -o none
KV_ID=$(az keyvault show -n $KV --query id -o tsv)
az role assignment create --assignee $(az ad signed-in-user show --query id -o tsv) --role "Key Vault Secrets Officer" --scope $KV_ID -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" --scope $KV_ID -o none
sleep 30 # 等待 RBAC 生效
az keyvault secret set --vault-name $KV -n database-url -o none \
--value "postgresql://orders:${DB_PASSWORD}@${PG_HOST}:5432/orders?sslmode=require"
az keyvault secret set --vault-name $KV -n redis-url -o none --value "rediss://:${REDIS_KEY}@${REDIS_HOST}:10000/0"
KV_URI=https://$KV.vault.azure.net/secrets
# ---------- 运行:Container Apps ----------
# 连接预算(B1ms 只有 35 个用户连接,且 Burstable 不支持内置 PgBouncer):
# api 5 副本 × 2 gunicorn 进程 × 池 2 = 20;worker 4 × 1 × 2 = 8;两个作业各 ≤ 2 → 合计 ≤ 32 < 35
az containerapp env create -g $RG -n $ENV -l $LOC -o none
IMG=$ACR.azurecr.io/orders:1.0
SECRETS="database-url=keyvaultref:$KV_URI/database-url,identityref:$ID_RID redis-url=keyvaultref:$KV_URI/redis-url,identityref:$ID_RID"
COMMON_ENV="DATABASE_URL=secretref:database-url REDIS_URL=secretref:redis-url AZURE_CLIENT_ID=$ID_CID \
QUEUE_BACKEND=servicebus SERVICEBUS_NAMESPACE=$SB.servicebus.windows.net \
STORAGE_ACCOUNT_URL=https://$ST.blob.core.windows.net APP_VERSION=1.0 DB_POOL_SIZE=2"
# 1) 迁移作业(手动触发,每次发布前执行一次)
az containerapp job create -g $RG -n job-migrate --environment $ENV --trigger-type Manual \
--replica-timeout 600 --replica-retry-limit 1 --parallelism 1 --replica-completion-count 1 \
--image $IMG --registry-server $ACR.azurecr.io --registry-identity $ID_RID --mi-user-assigned $ID_RID \
--secrets $SECRETS --env-vars $COMMON_ENV --command orders-migrate \
--cpu 0.25 --memory 0.5Gi -o none
az containerapp job start -g $RG -n job-migrate -o none
echo "等待迁移完成…"; sleep 60
az containerapp job execution list -g $RG -n job-migrate --query "[0].properties.status" -o tsv
# 2) API(内部入口:只允许同一环境内的 web 访问)
az containerapp create -g $RG -n ca-orders-api --environment $ENV --image $IMG \
--registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
--ingress internal --target-port 8000 --min-replicas 1 --max-replicas 5 \
--cpu 0.5 --memory 1Gi --secrets $SECRETS --env-vars $COMMON_ENV -o none
# 3) Worker(无入口;按 Service Bus 队列长度用 KEDA 扩缩,可缩到 0)
az containerapp create -g $RG -n ca-orders-worker --environment $ENV --image $IMG \
--registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
--command orders-worker --min-replicas 0 --max-replicas 4 \
--scale-rule-name sb-orders --scale-rule-type azure-servicebus \
--scale-rule-metadata "queueName=orders" "namespace=$SB" "messageCount=5" \
--scale-rule-identity $ID_RID \
--cpu 0.25 --memory 0.5Gi --secrets $SECRETS --env-vars $COMMON_ENV -o none
# 4) 每日报表(定时作业,cron 为 UTC)
az containerapp job create -g $RG -n job-report --environment $ENV --trigger-type Schedule \
--cron-expression "15 6 * * *" --replica-timeout 900 --replica-retry-limit 2 \
--parallelism 1 --replica-completion-count 1 \
--image $IMG --registry-server $ACR.azurecr.io --registry-identity $ID_RID --mi-user-assigned $ID_RID \
--secrets $SECRETS --env-vars $COMMON_ENV --command orders-report \
--cpu 0.25 --memory 0.5Gi -o none
# 5) Web(外部入口,ACA 托管 HTTPS;/api 反向代理到内部 API)
az containerapp create -g $RG -n ca-orders-web --environment $ENV --image $ACR.azurecr.io/orders-web:1.0 \
--registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
--ingress external --target-port 8080 --min-replicas 1 --max-replicas 3 \
--cpu 0.25 --memory 0.5Gi --env-vars API_UPSTREAM=http://ca-orders-api -o none
FQDN=$(az containerapp show -g $RG -n ca-orders-web --query properties.configuration.ingress.fqdn -o tsv)
cat >> ~/hour6.env <<EOV
ACR=$ACR ENV=$ENV KV=$KV PG=$PG REDIS=$REDIS SB=$SB ST=$ST FQDN=$FQDN
EOV
echo "完成:https://$FQDN"
ORDERS_EOF
mkdir -p gateway
cat > gateway/nginx.conf <<'ORDERS_EOF'
# 网关:HTTPS 终止、HTTP→HTTPS 跳转、限流、静态 SPA、反向代理 API 与 Blob
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
log_format json escape=json '{"time":"$time_iso8601","remote":"$remote_addr","method":"$request_method",'
'"uri":"$request_uri","status":$status,"bytes":$body_bytes_sent,"rt":$request_time,'
'"upstream":"$upstream_addr","urt":"$upstream_response_time","rid":"$request_id"}';
server {
listen 80;
return 301 https://$host:8443$request_uri;
}
server {
listen 443 ssl;
http2 on;
ssl_certificate /etc/nginx/certs/tls.crt;
ssl_certificate_key /etc/nginx/certs/tls.key;
ssl_protocols TLSv1.2 TLSv1.3;
access_log /dev/stdout json;
client_max_body_size 10m;
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options nosniff always;
resolver 127.0.0.11 valid=10s ipv6=off; # Docker 内嵌 DNS:每 10 秒重新解析,发现扩缩后的副本
set $api http://api:8000;
set $blob http://azurite:10000;
location / {
root /usr/share/nginx/html;
try_files $uri /index.html;
}
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_set_header Host $host;
proxy_set_header X-Request-ID $request_id;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_connect_timeout 3s;
proxy_read_timeout 30s;
proxy_pass $api;
}
location /blob/ { # 仅本机演示:Azure 上浏览器直连 Blob 端点
rewrite ^/blob/(.*)$ /$1 break;
proxy_set_header Host azurite:10000; # SAS 签名与 Host 无关,但 Azurite 按路径识别账户
proxy_pass $blob;
}
}
ORDERS_EOF
mkdir -p web
cat > web/.dockerignore <<'ORDERS_EOF'
Dockerfile
ORDERS_EOF
mkdir -p web
cat > web/Dockerfile <<'ORDERS_EOF'
# Azure 上的前端 + 反向代理(ACA 负责 HTTPS 终止,所以这里只监听 8080 的 HTTP)
FROM nginx:1.29-alpine
COPY nginx-aca.conf.template /etc/nginx/templates/default.conf.template
COPY index.html /usr/share/nginx/html/index.html
EXPOSE 8080
ORDERS_EOF
mkdir -p web
cat > web/index.html <<'ORDERS_EOF'
<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8"><title>Orders Demo</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>body{font-family:system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem}
fieldset{margin:1rem 0}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccc;padding:4px 8px}
.pending{color:#b45309}.processed{color:#047857}pre{background:#f4f4f5;padding:.5rem;overflow:auto}</style></head>
<body>
<h1>Orders Demo</h1>
<fieldset><legend>下单(带 Idempotency-Key)</legend>
<input id="item" value="book"> × <input id="qty" type="number" value="1" min="1" style="width:4em">
<button onclick="order()">下单</button> <button onclick="order(true)">重复提交同一请求</button></fieldset>
<fieldset><legend>统计(Redis 缓存 10 秒)</legend><button onclick="stats()">刷新</button><pre id="stats"></pre></fieldset>
<fieldset><legend>上传文件(Blob + 短期 SAS)</legend><input type="file" id="file"> <button onclick="upload()">上传</button> <span id="link"></span></fieldset>
<h2>最近订单</h2><table><thead><tr><th>ID</th><th>商品</th><th>数量</th><th>状态</th></tr></thead><tbody id="rows"></tbody></table>
<script>
let lastKey = null;
async function order(repeat){
const key = repeat && lastKey ? lastKey : crypto.randomUUID(); lastKey = key;
const r = await fetch('/api/orders',{method:'POST',headers:{'Content-Type':'application/json','Idempotency-Key':key},
body:JSON.stringify({item:item.value,qty:+qty.value})});
alertBox(await r.json()); load();
}
function alertBox(o){ stats_.textContent = JSON.stringify(o,null,2) }
const stats_ = document.getElementById('stats');
async function stats(){ alertBox(await (await fetch('/api/stats')).json()) }
async function load(){
const rows = await (await fetch('/api/orders')).json();
document.getElementById('rows').innerHTML = rows.map(o=>`<tr><td>${o.id}</td><td>${o.item}</td><td>${o.qty}</td><td class="${o.status}">${o.status}</td></tr>`).join('');
}
async function upload(){
const fd = new FormData(); fd.append('file', file.files[0]);
const j = await (await fetch('/api/files',{method:'POST',body:fd})).json();
link.innerHTML = `<a href="$%7Bj.url%7D" target="_blank">下载(10 分钟内有效)</a>`;
}
load(); setInterval(load, 2000);
</script></body></html>
ORDERS_EOF
mkdir -p web
cat > web/nginx-aca.conf.template <<'ORDERS_EOF'
# nginx 官方镜像启动时用 envsubst 把 ${API_UPSTREAM} 替换为环境变量(只替换已定义的变量)
server {
listen 8080;
client_max_body_size 10m;
add_header X-Content-Type-Options nosniff always;
location = /healthz { return 200 "ok\n"; }
location / {
root /usr/share/nginx/html;
try_files $uri /index.html;
}
location /api/ {
proxy_pass ${API_UPSTREAM}; # 例如 http://ca-orders-api(同一 ACA 环境内的内部入口)
proxy_set_header X-Request-ID $request_id;
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_read_timeout 30s;
}
}
ORDERS_EOF
chmod +x gen-cert.sh azure/deploy.sh app/bin/*
echo "已生成 $D:$(find . -type f | wc -l) 个文件"
bash orders-bootstrap-part6.sh # creates ~/orders cd ~/orders && cp .env.example .env sed -i "s/change-me-db/$(openssl rand -hex 12)/; s/change-me-mq/$(openssl rand -hex 12)/" .env ./gen-cert.sh # self-signed certificate (explained in Module 3) docker compose pull --ignore-buildable # pre-pull the postgres/redis/rabbitmq/nginx/azurite images tree -a . 2>/dev/null || find . -type f | sort # use find when tree is not installed
.
├── compose.yaml # 9 services: migrate api worker report gateway postgres redis rabbitmq azurite
├── .env.example # passwords and the Azurite connection string (.env is not committed)
├── gen-cert.sh
├── app/ # one image, four process types: api / orders-worker / orders-migrate / orders-report
│ ├── Dockerfile
│ ├── bin/orders-{migrate,worker,report}
│ ├── migrations/001_init.sql, 002_expand_customer_email.sql
│ ├── migrations-contract/003_contract_customer_email.sql
│ └── orders/{api,worker,migrate,report,queueing,storage,db,config,log}.py
├── gateway/nginx.conf # HTTPS, rate limiting, routing
├── web/ # SPA (index.html) + nginx template and Dockerfile for Azure
└── azure/deploy.sh # final lab: one-shot deployment to Azure
Step 3: warm-up (30 seconds, answer from memory)
1. A container exits with code 137 after docker stop. What does that tell you? (hour 2)
The process did not handle SIGTERM and exit within the grace period, so it was killed with SIGKILL (128 + 9). The Worker in Module 4 of this lesson has to solve exactly this problem.
2. What is the difference between a "revision" and a "replica" in Container Apps? (hour 3)
A revision is an immutable snapshot of one version of the app's configuration/image; a replica is a running instance of a revision. Scaling changes the number of replicas; a release creates a new revision.
3. Why should production deployments reference an image digest rather than a mutable tag? (hour 5)
A tag can be overwritten, so new replicas created during scale-out might pull a different image; a digest guarantees that every replica in every region runs the same bytes. The multi-region deployment in Module 7 relies on this too.
Module 1 · Architecture design method
- Use 12-Factor to check whether a service fits containers and horizontal scaling, and locate the 6 key factors in the orders project.
- Draw the order system's reference architecture and state each part's role, failure impact and Azure managed replacement.
- Write a one-page ADR (Architecture Decision Record) and use a trade-off table to choose "self-host / managed / don't add it".
What: this hour's "order system"
A user orders on a web page → the API writes to the database and publishes a message → a worker processes it asynchronously → a daily scheduled report; users can also upload attachments. Small, yet it has the five patterns of nearly every business system.
Why: container design principles (the 6 key 12-Factor rules)
| Principle | Meaning | In this project |
|---|---|---|
| III Config | Config lives in environment variables, not in the image | orders/config.py reads only os.environ; one image runs locally and on Azure |
| IV Backing services | Database, cache and queue are replaceable attached resources | Change the URL to switch from the Postgres container to Azure PostgreSQL |
| VI Stateless processes | Processes keep no state locally | Sessions and cache in Redis; files in Blob (Module 6), so the API scales out freely |
| VIII Concurrency | Scale via "process type × count" | One image, four process types: api, worker, migrate, report |
| IX Disposability | Fast startup, graceful shutdown | gunicorn --graceful-timeout; on SIGTERM the worker finishes its current message, then exits |
| XI Logs / XII Admin processes | Logs to stdout; one-off tasks like migrations use the same image | JSON logs; orders-migrate as a one-off service / ACA Job |
How: a lightweight design process
- Write the non-functional requirements: availability (e.g. 99.9%), latency (P95 < 300 ms), no data loss, peak traffic, compliance.
- Draw the data flow: separate the synchronous path (user waits) from the asynchronous one (user does not).
- Choose each part and record an ADR: self-host or managed? Consistency needs? How does it degrade on failure?
- Do a failure analysis: assume each part is down in turn; is the behavior acceptable? (Module 8 review checklist)
When: when not to make it this complex
An internal tool with a few dozen users needs just one API container + one managed database. Add queues, caches and gateways only when requirements drive them: slow work → queue; read pressure or latency → cache; several backends / shared TLS and rate limiting → gateway.
Trade-off table: every part must answer four questions
| Part | Need it solves | What users see if it fails | Operating cost | Alternative without it |
|---|---|---|---|---|
| Redis cache | Hot-read latency, database read load | Slower (falls back to the database) | Low (managed) | Database indexes / read replicas |
| RabbitMQ / Service Bus | Slow work no longer blocks ordering; smooths peaks | Ordering fails or stays pending | Medium | Synchronous processing (fine at low volume) |
| nginx gateway | Unified TLS, rate limiting, routing | Whole site down (single point) | Low | Platform ingress (ACA ingress / ALB) |
| Object storage | User files shared across replicas | Uploads/downloads fail; ordering works | Low | None (not the container filesystem) |
| Local (Compose) | Azure managed replacement | Why switch |
|---|---|---|
| gateway (nginx) | ACA ingress (managed TLS) + optional Front Door / Application Gateway (WAF) | Auto certificate renewal, global load balancing, WAF |
| postgres container | Azure Database for PostgreSQL flexible server | Auto backups, PITR, high availability, patching |
| redis container | Azure Managed Redis (Azure Cache for Redis retires on 2028-09-30) | High availability, Entra ID authentication |
| rabbitmq container | Azure Service Bus | Dead-lettering, sessions, managed identity; native KEDA support |
| azurite | Azure Blob Storage | Same SDK, same code |
| migrate / report services | Container Apps Jobs (Manual / Schedule) | Execution history, retries, timeouts |
Design flow: from requirements to compose.yaml
Interactive simulator: from requirements to architecture
Pick a scenario and play. The normal one walks the five design steps; the failure ones show where four common design mistakes surface (output is illustrative).
12-Factor self-check
Tick what your service satisfies to see its scale-out/container readiness and next steps.
Commands used in this module
| Command | Purpose | Design link |
|---|---|---|
docker compose config -q | Validate compose.yaml and variables (non-zero exit on error) | Expands anchors and ${VAR:?} required variables |
docker compose config --services | List all services (including profiles) | Check the parts list against the diagram |
docker compose up -d --build | Build and start the whole system | api / worker start only after migrate succeeds |
docker compose ps -a --format 'table {{.Service}}\t{{.Status}}' | Status, including exited one-off services | One-off processes (XII) should exit 0 |
docker compose run --rm report | Run the scheduled job from its profile | Same image, different process type (VIII) |
docker compose exec api env | grep -E 'DATABASE|REDIS|QUEUE' | See the config the process received | Config from environment variables (III), not the image |
One image, four process types (compose.yaml excerpt)
x-app: &app # YAML anchor: shared config written once
image: orders:1.0
build: ./app
environment: &app-env
DATABASE_URL: postgresql://orders:${DB_PASSWORD:?run cp .env.example .env}@postgres:5432/orders
REDIS_URL: redis://redis:6379/0
QUEUE_BACKEND: rabbitmq
…
restart: unless-stopped
stop_grace_period: 30s
services:
migrate: { <<: *app, command: ["orders-migrate"], restart: "no", … }
api: { <<: *app, deploy: { replicas: 2 }, depends_on: { migrate: { condition: service_completed_successfully } } }
worker: { <<: *app, command: ["orders-worker"], deploy: { replicas: 2 } }
report: { <<: *app, command: ["orders-report"], profiles: [jobs] }
ADR template (docs/adr/0003-queue.md)
# ADR-0003: Process orders asynchronously through a message queue Status: Accepted (2026-11-15) ## Context Post-order processing (inventory, notifications) takes 2 s on average, with peaks of 200 orders/s; synchronous processing pushes API P95 > 3 s. ## Decision After writing to the database the API publishes a message to a queue and a worker processes it asynchronously; RabbitMQ locally, Service Bus on Azure. ## Alternatives 1. Synchronous processing (simple, but high latency and a cascade failure at peak) 2. Database polling table (no new component, but scales poorly, lock contention) 3. Kafka / Event Hubs (very high throughput, but needs per-partition processing and complex operations; beyond the requirement) ## Consequences + API latency drops to < 100 ms; workers scale independently − Eventual consistency: order status starts as pending; idempotent consumers and dead-letter handling are required (see Module 4)
Lab 1: start the system and check its parts against the diagram (about 4 min)
docker compose up -d --build
docker compose ps --format 'table {{.Service}}\t{{.Status}}'
SERVICE STATUS api Up 20 seconds (healthy) api Up 20 seconds (healthy) ... worker Up 20 seconds worker Up 20 seconds
migrate has exited, so it is not listed: docker compose ps -a migrate shows Exited (0).
docker compose logs migrate
docker compose ps -a migrate --format '{{.Service}} {{.State}} {{.ExitCode}}'
migrate-1 | {"ts": "…", "level": "INFO", "logger": "migrate", "msg": "applied", "version": "001_init.sql"}
migrate-1 | ...
migrate-1 | {"ts": "…", "level": "INFO", "logger": "migrate", "msg": "up to date", "applied": 0}
migrate exited 0Open https://<VM-IP>:8443 (trust the self-signed certificate), or run ssh -L 8443:localhost:8443 user@VM locally and open https://localhost:8443. A new order goes from pending to processed in about 1 second.
docker image inspect orders:1.0 --format '{{json .Config.Env}}' | jq -r '.[]' | grep -vE '^(PATH|LANG|GPG_KEY|PYTHON)'
docker compose config --services | sort | tr '\n' ' '; echo
PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 api azurite gateway migrate postgres rabbitmq redis report worker
The image holds only generic runtime variables; DATABASE_URL etc. come from compose.yaml, so the same image deploys to Azure unchanged (final lab).
The lesson of "Kubernetes + Kafka first"
A startup adopted Kafka, a service mesh and self-managed K8s with 3 services and a few thousand orders a day; two engineers spent half their time on the platform. Redone from requirements with ADRs: Container Apps + managed PostgreSQL + Service Bus; maintenance fell to 1–2 hours a week. Architecture should meet the non-functional requirements with the fewest parts, each justified by an ADR.
Case 2: "ghost dependencies" without ADRs
Problem: a team inherited Memcached running beside Redis; nobody knew why or dared remove it. Two years later, when it went out of support, they found only a long-retired report used it. Approach: one ADR per part (context, decision, alternatives, consequences) in the code repo; a quarterly review asks "is the need still there?" Limitation: ADRs record decisions, not runtime dependencies (you still need a service inventory and monitoring).
Case 3: "stateless" only in the test environment
Problem: in development the API ran 1 replica with in-memory sessions; in production with 3 replicas users kept getting logged out. Approach: keep sessions in Redis (or use stateless tokens) and smoke test in CI with --scale api=2 so multiple replicas are the default. Limitation: sticky sessions hide the problem for a while, but state is lost when a replica is replaced.
Common errors and fixes
required variable DB_PASSWORD is missing a value: run cp .env.example .env
compose.yaml requires it via ${DB_PASSWORD:?…}. Copy .env as instructed and change the password.
api stays in Created and never starts
api waits for migrate (service_completed_successfully). Check docker compose logs migrate: usually the password differs from the one initialized in the postgres volume (changing .env does not update an old volume). In development, rebuild with docker compose down -v.
The rabbitmq health check is slow to pass
RabbitMQ needs 20–40 seconds on first start; the healthcheck allows 12 retries × 10 seconds. Small-memory VMs are slower.
service "api" depends on undefined service "migrate": invalid compose project
A service others depend on was deleted, renamed or put in a disabled profile. docker compose config -q catches this before startup; keep depended-on one-off services out of profiles.
1. Without starting containers, list every service in compose.yaml and its image.
docker compose config --format json | jq -r '.services | to_entries[] | "\(.key)\t\(.value.image // "build")"'
2. Find services sharing the orders image but with a different command.
docker compose config --format json | jq -r '.services | to_entries[] | select(.value.image=="orders:1.0") | "\(.key)\t\(.value.command // ["(default CMD)"] | join(" "))"'The product manager wants an SMS right after each order, and a colleague suggests calling the SMS gateway directly from the API. Evaluate this with this module's method.
① Requirements: the SMS gateway's P95 latency and availability vs the order endpoint's target. ② Data flow: SMS is on the async "user doesn't wait" path. ③ ADR: synchronous call vs enqueue for a worker; the latter needs idempotency (one SMS per order) and dead-lettering (Module 4). ④ Failure analysis: a failing SMS gateway fails ordering if synchronous, but only delays the SMS if async. Usually: reuse the existing queue and send asynchronously.
Verified teaching videos
- The Twelve-Factor App (Chinese translation; English original at 12factor.net)
- Azure Architecture Center: application architecture guide
- Architectural Decision Records (adr.github.io)
No verified high-quality video on 12-Factor and ADRs was found, so official docs are linked instead.
Video storyboard (about 60 seconds)
A storyboard and narration for a video tool (this page cannot generate video/MP3).
Visual: a whiteboard reads "99.9%, P95 300 ms, peak 200 orders/s", beside an empty diagram.
Narration: architecture starts from requirements, not tools.
Visual: the data flow splits into solid lines ("user waits") and dashed lines ("user doesn't"); each new part pops up an ADR card.
Narration: every part must answer what it solves, what happens when it breaks, and who maintains it.
Visual: one orders image splits into four processes: api, worker, migrate, report.
Narration: one image, four process types, all config from environment variables.
Module 2 · Scenario ①: Three-tier web app (SPA + API + PostgreSQL + Redis)
- Explain connection pools and calculate "pool size × processes × replicas < database connection limit".
- Implement cache-aside: read-through, TTL, invalidate-on-write and graceful degradation if Redis fails.
- Distinguish liveness (
/healthz) from readiness (/readyz) and how each behaves when the database stops responding. - Use an Idempotency-Key so duplicate submissions do not create duplicate orders.
What: three tiers
Presentation tier (SPA, static files from nginx) → application tier (stateless API, N replicas) → data tier (PostgreSQL is the source of truth; Redis a disposable accelerator).
Why: what problem each design point solves
| Design | Problem | Approach |
|---|---|---|
| Connection pool | A new connection per request costs TCP + TLS + auth (a few to tens of ms), and each PostgreSQL connection is a backend process using memory | psycopg_pool.ConnectionPool(max_size=5): reuse connections in-process. Total = pool limit × gunicorn processes × replicas, kept below the database's available connections |
| Cache-aside | Hot reads overwhelm the database | Check Redis first → on a miss, query the database and write back with a TTL; delete related keys after a write. Cache only stable data (not pending orders, which will change) |
| Degradable cache | A Redis failure takes the site down | Cache calls catch RedisError (0.5 s timeout) and fall back to the database: the cache affects performance only, never correctness |
| Liveness vs readiness | During a brief database outage, a failing liveness probe restarts the container repeatedly (no help) | /healthz checks only the process itself; /readyz checks the database on its own short-lived connection (2 s timeout), returning 503 on failure → the platform stops routing to that replica rather than restarting it |
| Idempotency key | Client retries after a timeout → duplicate order | The client generates one UUID per business operation; a unique constraint + ON CONFLICT DO NOTHING; a duplicate gets the first result (200 instead of 202) |
| 202 Accepted | Processing takes time | Return after the database write and publish; the Worker updates the status (Module 4) |
How: load-balancing API replicas
In Compose, deploy.replicas: 2 creates orders-api-1 and orders-api-2; Docker's embedded DNS returns all replica IPs for the service name api (DNS round-robin). nginx re-resolves every 10 seconds (Module 3), so scaling needs no gateway restart.
When: when do you need a cache?
It fits read-heavy data that tolerates brief staleness (statistics, catalogs, configuration). Do not cache strongly consistent reads (balances, stock deductions), or use read replicas. With a cache, also plan the invalidation strategy and cache avalanche / stampede (many keys expiring together → jitter TTLs; hot keys → rebuild under a mutex).
Interactive simulator: the journey of one request
Pick a scenario and play. The request passes the gateway, API, Redis and PostgreSQL; failure scenarios show where it degrades or errors (output is from a local run or an example).
Connection budget calculator
Drag the sliders to see whether total connections exceed the database limit (numbers match the Azure Flexible Server docs).
Code highlights
app/orders/api.py (excerpt)
cache = redislib.Redis.from_url(config.REDIS_URL, socket_timeout=0.5, socket_connect_timeout=0.5)
def cache_get(key):
try:
v = cache.get(key)
return json.loads(v) if v else None
except redislib.RedisError:
log.warning("cache unavailable, falling back to database") # a cache failure does not affect correctness
return None
@app.get("/api/orders/<int:order_id>")
def get_order(order_id):
key = f"order:{order_id}"
hit = cache_get(key)
if hit:
return jsonify(hit | {"cache": "hit"})
with db.pool.connection() as conn:
row = conn.execute("SELECT * FROM orders WHERE id=%s", (order_id,)).fetchone()
if not row:
abort(404)
if row["status"] != "pending": # only cache "stable" data
cache_set(key, row)
return jsonify(row | {"cache": "miss"})
@app.post("/api/orders")
def create_order():
body = request.get_json(silent=True) or {}
item, qty = body.get("item"), body.get("qty")
if not item or not isinstance(qty, int) or qty <= 0:
abort(400, "item and a positive integer qty are required")
key = request.headers.get("Idempotency-Key") or str(uuid.uuid4())
with db.pool.connection() as conn:
row = conn.execute(
"""INSERT INTO orders (item, qty, customer_email, idempotency_key)
VALUES (%s, %s, %s, %s)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id, status""",
(item, qty, body.get("email"), key)).fetchone()
created = row is not None
if not created: # client retry: return the order created the first time
row = conn.execute("SELECT id, status FROM orders WHERE idempotency_key=%s", (key,)).fetchone()
if created:
queueing.publish({"order_id": row["id"]})
cache_del("stats")
return jsonify(id=row["id"], status=row["status"], created=created), 202 if created else 200
@app.get("/healthz")
def healthz(): # liveness: check only the process itself
return "ok"
@app.get("/readyz")
def readyz():
"""Readiness: use a separate short-lived connection + connect_timeout=2 so the probe never hangs on a pooled connection
(the pool timeout only covers "borrowing a connection", not the query; when the database is frozen the query waits forever)."""
try:
with psycopg.connect(config.DATABASE_URL, connect_timeout=2) as conn:
conn.execute("SELECT 1")
except Exception as e:
log.warning("not ready: %s", e)
return "database unavailable", 503
return "ready"
app/Dockerfile (multi-stage, non-root, health check)
# syntax=docker/dockerfile:1
# check=error=true
ARG PYTHON_VERSION=3.13
FROM python:${PYTHON_VERSION}-slim AS builder
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
FROM python:${PYTHON_VERSION}-slim AS runtime
RUN useradd --uid 10001 --create-home app
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
COPY --chown=10001:10001 orders ./orders
COPY --chown=10001:10001 migrations ./migrations
COPY --chmod=755 bin/ /usr/local/bin/
USER 10001:10001
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --start-interval=1s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
CMD ["gunicorn", "-b", "0.0.0.0:8000", "-w", "2", "--graceful-timeout", "20", "--access-logfile", "-", "orders.api:app"]
Commands used in this module
| Command | Description |
|---|---|
docker compose up -d --scale api=3 | Scale api to 3 replicas (overrides deploy.replicas) |
docker compose exec postgres psql -U orders -c "SELECT count(*) FROM pg_stat_activity WHERE datname='orders'" | Current connections (verifies the pool) |
docker compose exec redis redis-cli --scan --pattern 'order:*' | List cache keys (never KEYS * in production) |
docker compose exec redis redis-cli TTL stats | Remaining TTL (seconds); -2 = no such key |
docker compose exec redis redis-cli INFO stats | grep keyspace | Hit/miss counters keyspace_hits / keyspace_misses |
docker compose stop redis / start redis | Rehearse a cache failure |
docker compose pause postgres | Freeze the database (simulates "unresponsive"; closer to a real timeout than stop) |
Lab 2: idempotency, caching, scaling and graceful degradation (about 6 minutes)
B=https://localhost:8443; C="curl -sk"
$C -X POST $B/api/orders -H 'Content-Type: application/json' -H 'Idempotency-Key: k-001' -d '{"item":"book","qty":2}' -w ' %{http_code}\n'
$C -X POST $B/api/orders -H 'Content-Type: application/json' -H 'Idempotency-Key: k-001' -d '{"item":"book","qty":2}' -w ' %{http_code}\n'
$C -X POST $B/api/orders -H 'Content-Type: application/json' -d '{"item":"pen","qty":0}' -o /dev/null -w '%{http_code}\n'
{"created":true,"id":1,"status":"pending"}
202
{"created":false,"id":1,"status":"pending"}
200
400sleep 2
$C $B/api/orders/1 | jq -c '{status,cache}'
$C $B/api/orders/1 | jq -c '{status,cache}'
$C $B/api/stats | jq -c; $C $B/api/stats | jq -c
docker compose exec redis redis-cli TTL stats
{"status":"processed","cache":"miss"}
{"status":"processed","cache":"hit"}
{"cache":"miss","items":2,"orders":1,"processed":1,"served_by":"3f2a…","version":"1.0"}
{"cache":"hit","items":2,"orders":1,"processed":1,"served_by":"9c1d…","version":"1.0"}
(integer) 8
The two served_by hostnames may differ: different replicas, shared cache.
docker compose up -d --scale api=4 --no-recreate for i in $(seq 1 20); do $C $B/api/stats | jq -r .served_by; done | sort | uniq -c docker compose exec postgres psql -U orders -tc "SELECT count(*) FROM pg_stat_activity WHERE datname='orders'"
5 3f2a…
...
5 e44f…
9
Connections ≈ those open per gunicorn process (pool min_size=1, growing to 5) + the worker's. Upper bound = 5 × 2 × 4 = 40 (api) + worker.
docker compose stop redis
$C $B/api/stats -o /dev/null -w 'stats without redis: %{http_code} %{time_total}s\n'
docker compose logs api --since 30s | grep -m1 'cache unavailable'
docker compose start redis
docker compose pause postgres
docker compose exec api python -c "import urllib.request as u;print(u.urlopen('http://127.0.0.1:8000/healthz').status)"
docker compose exec api python -c "import urllib.request as u;u.urlopen('http://127.0.0.1:8000/readyz')" 2>&1 | tail -1
docker compose unpause postgres
docker compose up -d --scale api=2
stats without redis: 200 0.02s … "level": "WARNING", "logger": "api", "msg": "cache unavailable, falling back to database" 200 urllib.error.HTTPError: HTTP Error 503: SERVICE UNAVAILABLE
(Verified: with the database frozen, /readyz returns 503 after 2.0 seconds. The first version used a pooled connection and hung 30 seconds until gunicorn timed out, hence a probe needs its own timeout.) The pool also sets a server-side statement_timeout=5000 so slow queries cannot hold connections.
Redis down: works, slower (all reads hit the database). Database unresponsive: liveness 200 (no restart), readiness 503 (no traffic).
Cloud comparison: managed data tier (final lab excerpt)
az postgres flexible-server create -g $RG -n $PG -l $LOC --version 17 \
--tier Burstable --sku-name Standard_B1ms --storage-size 32 \
--admin-user orders --admin-password "$DB_PASSWORD" --public-access 0.0.0.0 --yes
az postgres flexible-server db create -g $RG -s $PG -d orders
az extension add -n redisenterprise --upgrade
az redisenterprise create -g $RG --cluster-name $REDIS -l $LOC --sku Balanced_B0 \
--clustering-policy EnterpriseCluster --access-keys-auth Enabled
az redisenterprise database list-keys -g $RG --cluster-name $REDIS --query primaryKey -o tsv
# Connection strings go into Key Vault; the app references them via keyvaultref + managed identity (hour 3, Module 6)
az keyvault secret set --vault-name $KV -n database-url \
--value "postgresql://orders:${DB_PASSWORD}@${PG_HOST}:5432/orders?sslmode=require"
az keyvault secret set --vault-name $KV -n redis-url --value "rediss://:${REDIS_KEY}@${REDIS_HOST}:10000/0"
| Point | Notes (verified 2026-11) |
|---|---|
| PostgreSQL versions | Flexible Server supports 14–18 (CLI already lists 19; 13 and older in extended support) |
| Connection limit | Standard_B1ms: max_connections 50, 35 available to users (15 reserved); B2s: 429 / 414. The Burstable tier cannot use the built-in PgBouncer, so keep pool × processes × replicas tightly controlled |
| Managed Redis | Port 10000 (TLS, rediss://); new instances default to Entra ID enabled, access keys disabled; this example enables keys for simplicity. Production: redis-entraid + managed identity; EnterpriseCluster gives a single endpoint for ordinary clients (OSSCluster needs a cluster-mode client) |
| Azure Cache for Redis | Basic/Standard/Premium retire on 2028-09-30; new projects should use Azure Managed Redis |
| Networking | --public-access 0.0.0.0 allows Azure services only, fine for a lab; production uses VNet integration or private endpoints |
from redis_entraid.cred_provider import create_from_default_azure_credential
credential_provider = create_from_default_azure_credential(("https://redis.azure.com/.default",))
r = redis.Redis(host=redis_host, port=10000, ssl=True, credential_provider=credential_provider)
"Scaling out took the system down"
On Black Friday, ops scaled the API from 10 to 40 replicas; minutes later the database reported FATAL: remaining connection slots are reserved and every API returned 500. Cause: 4 processes × pool 10 = 40 connections per replica, so 40 replicas needed 1600, far over the limit. Fix: pool of 3, PgBouncer (transaction mode), and a connection-budget check in the scaling runbook. The stateless tier scales freely; the stateful tier does not, so budget connections before scaling.
Case 2: the readiness probe pulled the whole site out
Problem: A team's /readyz checked the database, Redis, Blob and a third-party fraud-check API. A 5-minute fraud-check outage failed readiness on every replica, leaving the ingress no healthy backend: the whole site returned 503, though ordering did not need fraud checks. Approach: readiness checks only dependencies essential to serving (here, the database); others degrade in code and alert. Limitation: review dependency tiers regularly; tier each new dependency at go-live.
Case 3: "double orders" from mobile retries
Problem: On mobile networks, timed-out POSTs were auto-retried, creating second orders though the first had succeeded; support handled dozens of refunds a day. Approach: the app generates a UUID Idempotency-Key on "Submit" and reuses it on retry; the backend uses a unique constraint + ON CONFLICT DO NOTHING, returning the first result to duplicates. Limitation: keys need a retention period (e.g. 24 hours) and cleanup, and must be passed along across service calls (the Worker calling the courier API in Module 4).
Common errors and fixes
FATAL: sorry, too many clients already / remaining connection slots are reserved
Connections exceeded the limit. Group pg_stat_activity by application_name / client_addr; shrink the pool, cut processes, or add PgBouncer (built into Flexible Server from General Purpose up).
psycopg_pool.PoolTimeout: couldn't get a connection after 30.00 sec
All pooled connections are busy (slow queries, or a leak from not using with pool.connection()). Find slow queries, set statement_timeout, and match pool size to gunicorn threads.
Data updated but the page shows the old value
The write path did not delete the cache key, or changing data was cached. Delete the cache after the database write succeeds, and give every key a TTL as a safety net.
API requests stall for seconds while Redis is down
socket_timeout / socket_connect_timeout are unset, so the client waits long by default. This example uses 0.5 seconds.
A /readyz request hangs 30 seconds, then gunicorn reports WORKER TIMEOUT
The check borrowed a pooled connection; the pool's timeout covers only borrowing, not the query, so a frozen database blocks forever. Verified here: with a separate short-lived connection + connect_timeout=2, the probe returns 503 after 2.0 seconds.
1. Count connections to the orders database by client address to find who holds the most.
docker compose exec postgres psql -U orders -c "SELECT client_addr, state, count(*) FROM pg_stat_activity WHERE datname='orders' GROUP BY 1,2 ORDER BY 3 DESC"
2. Calculate the Redis cache hit ratio.
docker compose exec redis redis-cli INFO stats | awk -F: '/keyspace_hits/{h=$2}/keyspace_misses/{m=$2}END{printf "hit ratio %.1f%%\n", h*100/(h+m)}'Before a big sale you plan to scale the API from 4 to 20 replicas; the database is an Azure B2s (414 user connections). Each replica runs 2 gunicorn processes with a pool limit of 5. Feasible? What should you check?
20 × 2 × 5 = 200 < 414, so the budget works, but add the Worker, migration jobs and admin connections, and keep 20% headroom. More importantly, check database CPU and IOPS: connections are not capacity; if Redis fails every read hits the database. Recommended: load testing (hour 7) + an ACA max replica count so autoscaling cannot exhaust the budget.
Verified teaching videos
- Azure Architecture Center: Cache-Aside pattern
- PostgreSQL Flexible Server: connection limits
- Azure Managed Redis: Python + Entra ID quickstart
Video storyboard (about 60 seconds)
Visual: 40 API replicas open connections at once, a queue forms at the database, and
too many clients pops up.Narration: the stateless tier scales freely; the stateful tier does not.
Visual: the request tries Redis first, goes to the database on a miss, and drops the result into Redis with a 60-second countdown.
Narration: cache-aside: read the cache, on a miss read the database and write back; delete the cache after a database write.
Visual: the same form is submitted twice; the unique constraint stops the second, which gets the first order number back.
Narration: idempotency keys make retries safe.
Module 3 · Scenario ②: Gateway and HTTPS
- Explain a gateway's responsibilities and why only it publishes ports.
- Read and change nginx config: TLS, HTTP→HTTPS redirect, path routing, rate limiting, body limit, timeouts, JSON access logs.
- Understand nginx's "DNS caching trap" in Docker and how
resolver 127.0.0.11fixes it. - Azure equivalents: ACA managed certificates, Front Door / Application Gateway + WAF (Module 7 uses Front Door for multi-region failover).
What: what a gateway does
| Responsibility | nginx configuration in this project |
|---|---|
| TLS termination | listen 443 ssl, TLS 1.2/1.3 only; plain HTTP to backends internally |
| HTTP → HTTPS | Port 80 gets a 301 redirect; HSTS header added |
| Routing | / → static SPA; /api/ → api service; /blob/ → azurite (local demo only) |
| Protecting the backends | Rate limit 10 r/s (burst 20) → 429; body limit 10 MB → 413; connect timeout 3 s, read timeout 30 s |
| Observability | $request_id passed to the backend as X-Request-ID; JSON access log with upstream address and timing |
Why: why a single entry point
- Minimal exposure: only gateway publishes ports (8443/8080); api, postgres and redis have no
ports:. - Centralized certificates: one place to update.
- Cross-cutting concerns: rate limiting, security headers, logging and CORS live in one place.
How: the nginx DNS caching trap
With proxy_pass http://api:8000;, nginx resolves api only at startup. Recreate or scale api (new IPs) → nginx uses old IPs → 502 Bad Gateway. Fix: resolver 127.0.0.11 valid=10s; plus a variable upstream (set $api http://api:8000; proxy_pass $api;) so nginx re-resolves.
When: choosing between nginx, Caddy and Traefik
| nginx | Caddy | Traefik | |
|---|---|---|---|
| Certificates | Manual / certbot | Automatic HTTPS (Let's Encrypt) | Automatic HTTPS |
| Configuration | Files, fullest feature set | Minimal Caddyfile | Auto-discovery from container labels |
| Best for | Fine control, performance | Small single-host sites | Many frequently changing containers |
Caddy equivalent: example.com { reverse_proxy /api/* api:8000; root * /srv; file_server } (it needs a public domain name to obtain a certificate).
X-Forwarded-For is always the real IP" — clients can forge it; trust only the part added by known proxies.Interactive simulator: a request through the gateway
Play a scenario to see nginx's checks in order and the final status (matches gateway/nginx.conf; "tested" = local run).
Gateway routing simulator (free-form)
Build a request and see how nginx handles it (rules match gateway/nginx.conf).
Key code
gateway/nginx.conf
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
log_format json escape=json '{"time":"$time_iso8601","remote":"$remote_addr","method":"$request_method",'
'"uri":"$request_uri","status":$status,"bytes":$body_bytes_sent,"rt":$request_time,'
'"upstream":"$upstream_addr","urt":"$upstream_response_time","rid":"$request_id"}';
server {
listen 80;
return 301 https://$host:8443$request_uri;
}
server {
listen 443 ssl;
http2 on; # syntax for nginx 1.25.1+
ssl_certificate /etc/nginx/certs/tls.crt;
ssl_certificate_key /etc/nginx/certs/tls.key;
ssl_protocols TLSv1.2 TLSv1.3;
access_log /dev/stdout json;
client_max_body_size 10m;
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options nosniff always;
resolver 127.0.0.11 valid=10s ipv6=off; # Docker embedded DNS: re-resolve every 10 s
set $api http://api:8000;
set $blob http://azurite:10000;
location / {
root /usr/share/nginx/html;
try_files $uri /index.html; # SPA: unknown paths fall back to index.html
}
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_set_header Host $host;
proxy_set_header X-Request-ID $request_id;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_connect_timeout 3s;
proxy_read_timeout 30s;
proxy_pass $api;
}
location /blob/ { # local demo only: on Azure the browser talks to the Blob endpoint directly
rewrite ^/blob/(.*)$ /$1 break;
proxy_set_header Host azurite:10000;
proxy_pass $blob;
}
}
compose.yaml: only the gateway publishes ports
gateway:
image: nginx:1.29-alpine
ports: ["8443:443", "8080:80"]
volumes:
- ./gateway/nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./gateway/certs:/etc/nginx/certs:ro
- ./web:/usr/share/nginx/html:ro
depends_on: [api]
gen-cert.sh
openssl req -x509 -newkey rsa:2048 -nodes -days 30 \ -keyout gateway/certs/tls.key -out gateway/certs/tls.crt \ -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
Commands used in this module
| Command | Description |
|---|---|
docker compose exec gateway nginx -t | Check config syntax (after every change) |
docker compose exec gateway nginx -s reload | Reload config gracefully, keeping connections |
curl -skI https://localhost:8443/ | Response headers only (HSTS, nosniff); -k skips self-signed cert verification |
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://localhost:8080/x | Verify the 301 redirect |
openssl s_client -connect localhost:8443 -servername localhost </dev/null 2>/dev/null | openssl x509 -noout -subject -dates | Certificate subject and validity |
docker compose logs gateway --no-log-prefix --since 1m | jq -c 'select(.status>=400)' | Filter failed requests (JSON log; add -R 'fromjson?' to skip non-JSON lines) |
Lab 3: redirect, certificate, rate limiting, body limit and the DNS trap (about 5 minutes)
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://localhost:8080/api/stats
curl -skI https://localhost:8443/ | grep -iE 'strict|nosniff'
openssl s_client -connect localhost:8443 -servername localhost </dev/null 2>/dev/null | openssl x509 -noout -subject -enddate
301 https://localhost:8443/api/stats strict-transport-security: max-age=31536000 x-content-type-options: nosniff subject=CN=localhost notAfter=Dec 15 … 2026 GMT
seq 1 50 | xargs -P 25 -I{} curl -sk -o /dev/null -w '%{http_code}\n' https://localhost:8443/api/stats | sort | uniq -c
22 200
28 429
rate=10r/s + burst=20 + nodelay: about 21 pass at once (burst 20 + the current one; timing may admit 1–2 more, hence 22); the rest get 429 immediately.
head -c 11M /dev/zero > big.bin
curl -sk -o /dev/null -w '%{http_code}\n' -F file=@big.bin https://localhost:8443/api/files
docker compose logs gateway --no-log-prefix --since 1m | grep -m1 '"status":413'
413
{"time":"…","remote":"172.18.0.1","method":"POST","uri":"/api/files","status":413,…,"rid":"5c1e…"}sed -e 's#set $api http://api:8000;##' -e 's#proxy_pass $api;#proxy_pass http://api:8000;#' gateway/nginx.conf > /tmp/static.conf
docker run -d --name ng-static --network orders_default -p 9443:443 \
-v /tmp/static.conf:/etc/nginx/conf.d/default.conf:ro -v $PWD/gateway/certs:/etc/nginx/certs:ro nginx:1.29-alpine
curl -sk -o /dev/null -w 'before: %{http_code}\n' https://localhost:9443/api/stats
docker compose up -d --force-recreate --scale api=2 api # api containers recreated; IPs may change
curl -sk -o /dev/null -w 'static : %{http_code}\n' --max-time 5 https://localhost:9443/api/stats # may be 502/504
curl -sk -o /dev/null -w 'dynamic: %{http_code}\n' https://localhost:8443/api/stats # normal 200
docker rm -f ng-static
ng-static (static resolution) keeps the old IP; gateway (resolver + variable) works. It may take a few tries (IPs are sometimes reused). Takeaway: use resolver + variable for nginx upstreams in containers.
Cloud mapping: entry-point options on Azure
| Option | Best for | Notes |
|---|---|---|
| ACA built-in ingress | Most apps | Envoy TLS; custom domain + free managed certificate; IP allow list; no rate limiting / WAF |
| Azure Front Door (Standard/Premium) | Global users, WAF/CDN | Edge TLS, WAF rate-limit rules, static caching; origin can accept only Front Door traffic |
| Application Gateway (WAF v2) | Regional, VNet-internal | L7 load balancing + WAF; can front internal ACA |
| API Management | Public APIs | Keys/subscriptions, quotas, rate limits, versions |
The final lab uses ca-orders-web (external ingress; nginx serves the SPA and proxies /api/ to ca-orders-api, internal ingress, not internet-reachable). ACA handles TLS, so web listens only on 8080:
server {
listen 8080;
client_max_body_size 10m;
location = /healthz { return 200 "ok\n"; }
location / { root /usr/share/nginx/html; try_files $uri /index.html; }
location /api/ {
proxy_pass ${API_UPSTREAM}; # substituted by envsubst at startup, e.g. http://ca-orders-api
proxy_set_header X-Request-ID $request_id;
proxy_read_timeout 30s;
}
}
az containerapp create -g $RG -n ca-orders-api … --ingress internal --target-port 8000 az containerapp create -g $RG -n ca-orders-web … --ingress external --target-port 8080 \ --env-vars API_UPSTREAM=http://ca-orders-api # custom domain + free managed certificate az containerapp hostname add -g $RG -n ca-orders-web --hostname shop.example.com az containerapp hostname bind -g $RG -n ca-orders-web --hostname shop.example.com --environment $ENV --validation-method CNAME
The official nginx image renders /etc/nginx/templates/*.template into conf.d via envsubst (only defined env vars; nginx variables like $uri stay). In one environment, an internal-ingress app is reachable by app name.
An expired certificate takes the whole site down
A certificate renewed by hand by a colleague who had left expired; every client got NET::ERR_CERT_DATE_INVALID. Fix: managed certificates (ACA / Front Door auto-renew) or Key Vault auto-rotation; alert below 21 days left; keep a certificate inventory with owners in the runbook.
Case 2: rate limiting throttles an entire company's egress IP
Problem: a B2B system rate-limited per client IP at 10 r/s; hundreds of a customer's staff behind one egress NAT all got 429 each morning. Later, behind a load balancer, $remote_addr was always the LB. Approach: set_real_ip_from + real_ip_header X-Forwarded-For (known proxies only); limit signed-in users by user ID / API key (API Management or the app). Limitation: keep per-IP limits as the first defense for anonymous traffic.
Case 3: DNS caching makes scale-out "do nothing"
Problem: api went from 2 to 6 replicas, yet only two were busy: hard-coded proxy_pass http://api:8000 resolved only the original addresses at startup. Approach: resolver 127.0.0.11 valid=10s + a variable upstream, or platform ingress (ACA / ALB) discovery. Limitation: DNS round robin ignores load and health; in production rely on platform load balancing and readiness probes.
Common errors and fixes
502 Bad Gateway, log shows connect() failed (111: Connection refused) while connecting to upstream
Upstream not ready or wrong port: is docker compose ps api healthy, on 8000? If api was recreated, check for resolver + variable.
no resolver defined to resolve api
A variable upstream requires resolver 127.0.0.11.
unknown directive "http2"
nginx is older than 1.25.1: write listen 443 ssl http2; or upgrade (this hour uses nginx:1.29-alpine).
The backend sees the protocol as http and builds wrong redirect URLs
The backend must trust X-Forwarded-Proto (Flask: werkzeug.middleware.proxy_fix.ProxyFix), but only from the gateway.
Rate limiting throttles all users together
Behind a load balancer, $binary_remote_addr is always the LB's IP. Use set_real_ip_from + real_ip_header X-Forwarded-For to recover the client IP (trust only known proxy ranges).
curl: (60) SSL certificate problem: self-signed certificate
The self-signed certificate is untrusted. In labs use -k or --cacert gateway/certs/tls.crt; in production use a trusted CA or platform-managed certificate, and never disable verification in code.
1. Show days left before the certificate expires (for alerting).
end=$(openssl s_client -connect localhost:8443 -servername localhost </dev/null 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2) echo $(( ( $(date -d "$end" +%s) - $(date +%s) ) / 86400 )) days
2. Count status codes in the gateway's JSON log over the last 5 minutes.
docker compose logs gateway --no-log-prefix --since 5m | jq -R 'fromjson? | .status' | sort | uniq -c
orders is going global, needs a WAF and edge access, and later multi-region. Which entry point?
Azure Front Door Standard/Premium as global entry: edge TLS, WAF (Premium has managed rule sets), static caching; origin is the ACA external ingress, accepting only Front Door traffic. In-region keep nginx (SPA + proxy) or use ACA ingress directly. Multi-region: origin-group priority routing for active/passive failover (Module 7). Front Door (classic) retires on 2027-03-31; new projects use Standard/Premium.
Verified teaching videos
- nginx: ngx_http_limit_req_module
- Official nginx image: templates and environment variables
- Azure Container Apps: ingress overview
Video storyboard (about 60 seconds)
Visual: a request passes four gateway checkpoints: "TLS handshake", "rate-limit turnstile", "size scale", "route sorting".
Narration: The gateway is the only entry point; cross-cutting concerns live here.
Visual: api is recreated with a new address; nginx still holds the old one and the request hits a wall: 502. An nginx that checks the phone book every 10 seconds gets through.
Narration: In containers, give nginx upstreams a resolver plus a variable.
Visual: local nginx fades into ACA ingress and Front Door icons.
Narration: In the cloud, hand certificates and WAF to a managed entry point.
Module 4 · Scenario ③: Async and scheduled jobs
- Explain at-least-once delivery and why consumers must be idempotent.
- Ack only after success; retry N times, then dead-letter (DLQ).
- Implement graceful shutdown: on SIGTERM, finish the current message, then exit.
- Schedule jobs with a Compose one-off service + host cron; Azure: Service Bus + KEDA + Container Apps Jobs.
What: a queue decouples "accepting" from "processing"
The API only writes the order and publishes a message (milliseconds); the worker processes at its own pace. At peak, messages wait in the queue instead of dragging the API down: load leveling.
Why: five essentials of reliable consumption
| Essential | How | What happens if you don't |
|---|---|---|
| Durability | Queue durable=True, message delivery_mode=2 | Messages lost on RabbitMQ restart |
| Manual ack | Only after success call basic_ack;prefetch_count=1 | Auto-ack loses the message on a crash; a large prefetch lets one worker hoard messages |
| Idempotent consumption | UPDATE … SET status='processed' WHERE id=%s AND status='pending' | Queues are "at least once": a crash before ack redelivers the message and you ship or charge twice |
| Retries + dead letters | On failure republish with an x-retry header; on the 3rd failure nack(requeue=False) → via orders.dlx into orders.dlq | A "poison message" loops forever, blocking workers and normal messages |
| Graceful shutdown | On SIGTERM, finish the current message, then exit; stop_grace_period: 30s | SIGKILLed mid-processing during a release or scale-in |
How: scheduled jobs
Same image, process type orders-report: summarize the previous day, upsert into daily_reports, upload a CSV to Blob. Upserts make re-runs safe (re-entrant): schedulers retry and people re-run missed days.
- Single host: host
cron/ systemd timer runsdocker compose run --rm report; no crond beside a long-running process in a container. - Azure: a Container Apps Job (
--trigger-type Schedule, cron in UTC) with run history, timeouts and retries.
When: which queue to choose
| RabbitMQ / Service Bus | Redis lists / Streams | Kafka / Event Hubs | |
|---|---|---|---|
| Model | Task queue (deleted on consume), dead letters, delays, priorities | Lightweight, handy if Redis is already there | Replayable event log, ordered per partition |
| Good for | Background jobs, commands | Small, low-stakes jobs | High-throughput event streams, many consumers |
outbox row in the same transaction, forwarded by a background process) or a job that republishes long-pending orders.Interactive simulator: the life of a message
Play a scenario from publish to ack (or dead letter); failures show redelivery, dead-lettering, forced kills and cold starts.
Live simulation: queue / retries / dead letters / scaling
Runs automatically in this module: each worker handles one message per 0.7 s (prefetch=1).
Key code
app/orders/queueing.py (RabbitMQ consumer part)
def _rabbit_channel():
conn = pika.BlockingConnection(pika.URLParameters(config.RABBITMQ_URL))
ch = conn.channel()
ch.exchange_declare("orders.dlx", "fanout", durable=True) # dead-letter exchange
ch.queue_declare(f"{config.QUEUE_NAME}.dlq", durable=True)
ch.queue_bind(f"{config.QUEUE_NAME}.dlq", "orders.dlx")
ch.queue_declare(config.QUEUE_NAME, durable=True,
arguments={"x-dead-letter-exchange": "orders.dlx"})
return conn, ch
def consume(handler):
stopping = {"flag": False}
def _stop(signum, frame):
stopping["flag"] = True
info(log, "SIGTERM received, finishing current message")
signal.signal(signal.SIGTERM, _stop)
conn, ch = _rabbit_channel()
ch.basic_qos(prefetch_count=1)
for method, props, body in ch.consume(config.QUEUE_NAME, inactivity_timeout=1):
if stopping["flag"]:
break
if method is None: # no message within 1 s: loop back and check the stop flag
continue
retries = int((props.headers or {}).get("x-retry", 0))
try:
handler(json.loads(body))
ch.basic_ack(method.delivery_tag) # ack only after successful processing
except Exception:
log.exception("handler failed")
if retries + 1 >= config.MAX_RETRIES:
ch.basic_nack(method.delivery_tag, requeue=False) # → dead-letter queue
else:
ch.basic_publish("", config.QUEUE_NAME, body, pika.BasicProperties(
delivery_mode=2, headers={"x-retry": retries + 1}))
ch.basic_ack(method.delivery_tag)
ch.cancel(); conn.close()
app/orders/worker.py (idempotent handling)
def handle(msg):
order_id = msg["order_id"]
with db.pool.connection() as conn:
row = conn.execute("SELECT item FROM orders WHERE id=%s", (order_id,)).fetchone()
if row and row["item"] == "poison":
raise ValueError("simulated unprocessable 'poison message'")
time.sleep(0.5) # simulate slow processing
cur = conn.execute("""UPDATE orders SET status='processed', processed_at=now()
WHERE id=%s AND status='pending'""", (order_id,))
info(log, "order processed", order_id=order_id, changed=cur.rowcount) # duplicate message: changed=0
compose.yaml (worker and scheduled job)
worker:
<<: *app
command: ["orders-worker"]
healthcheck: { disable: true } # the image's HTTP healthcheck does not apply to the worker
deploy: { replicas: 2 }
report:
<<: *app
command: ["orders-report"]
restart: "no"
profiles: [jobs] # not started by up; triggered only with run
This retry republishes immediately: fine for a demo. Production needs backoff (RabbitMQ: TTL delay queue + DLX back; Service Bus: abandon so the platform redelivers up to MaxDeliveryCount, or scheduled messages). The Service Bus path is the servicebus branch of queueing.py: complete_message / abandon_message; past MaxDeliveryCount, messages go to the dead-letter subqueue.
Commands used in this module
| Command | Description |
|---|---|
docker compose exec rabbitmq rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers | Depth, unacked, consumers |
docker compose exec rabbitmq rabbitmq-diagnostics -q ping | Healthcheck command |
http://localhost:15672 (bound to 127.0.0.1 only) | Management UI; remotely via ssh -L 15672:localhost:15672 |
docker compose up -d --scale worker=4 --no-recreate | Add consumers |
docker compose stop -t 30 worker | SIGTERM, wait ≤ 30 s, then SIGKILL |
docker compose run --rm -e REPORT_DAY=2026-11-14 report | Run / backfill the job by hand |
crontab -e | Host scheduling (see lab) |
Lab 4: backlog, scale-out, poison messages, graceful shutdown and the daily report (about 6 minutes)
B=https://localhost:8443; C="curl -sk"
docker compose stop worker
for i in $(seq 1 10); do $C -X POST $B/api/orders -H 'Content-Type: application/json' -d "{\"item\":\"item$i\",\"qty\":1}" -o /dev/null; done
docker compose exec rabbitmq rabbitmqctl list_queues name messages_ready consumers
... name messages_ready consumers orders.dlq 0 0 orders 10 0
docker compose up -d --scale worker=4 --no-recreate sleep 3; docker compose logs worker --no-log-prefix --since 10s | grep -c 'order processed' docker compose exec rabbitmq rabbitmqctl list_queues name messages_ready consumers
10 orders.dlq 0 0 orders 0 4
$C -X POST $B/api/orders -H 'Content-Type: application/json' -d '{"item":"poison","qty":1}'
sleep 3
docker compose logs worker --no-log-prefix --since 10s | grep -E 'handler failed|dead-lettered' | cut -c1-120
docker compose exec rabbitmq rabbitmqctl list_queues name messages_ready
{"ts": "…", "level": "ERROR", "logger": "queue", "msg": "handler failed", "exc": "Traceback (most recent call last):\n Fi…
… (3 times in total)
{"ts": "…", "level": "INFO", "logger": "queue", "msg": "dead-lettered", "retries": 3}
orders.dlq 1
orders 0
Normal orders are unaffected. Dead letters need a human: after the fix, shovel them back to the main queue (management UI Shovel or a script); alert on DLQ depth > 0.
for i in $(seq 1 6); do $C -X POST $B/api/orders -H 'Content-Type: application/json' -d '{"item":"slow","qty":1}' -o /dev/null; done
docker compose stop -t 30 worker
docker compose logs worker --no-log-prefix --since 20s | grep -E 'SIGTERM|stopped gracefully' | head -4
docker compose up -d --scale worker=2
{… "msg": "SIGTERM received, finishing current message"}
{… "msg": "worker stopped gracefully"}
…
The worker's PID 1 is Python (the script uses exec), so it gets SIGTERM. Exit code should be 0, not 137: docker compose ps -a worker.
docker compose run --rm -e REPORT_DAY=$(date +%F) report docker compose exec postgres psql -U orders -c "SELECT * FROM daily_reports" # run daily at 06:15 (host time zone), appending output to a log ( crontab -l 2>/dev/null; echo "15 6 * * * cd $HOME/orders && docker compose run --rm report >> $HOME/orders-report.log 2>&1" ) | crontab - crontab -l | tail -1
{"ts": "…", "level": "INFO", "logger": "report", "msg": "report generated", "day": "2026-11-15", "orders": 18, "blob": "reports/2026-11-15.csv"}
day | orders | items | generated_at
------------+--------+-------+-------------------------------
2026-11-15 | 18 | 18 | 2026-11-15 …Cloud equivalent: Service Bus + KEDA scaling + Container Apps Jobs
az servicebus namespace create -g $RG -n $SB -l $LOC --sku Standard
az servicebus queue create -g $RG --namespace-name $SB -n orders --max-delivery-count 5
for r in "Azure Service Bus Data Sender" "Azure Service Bus Data Receiver"; do
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \
--role "$r" --scope $(az servicebus namespace show -g $RG -n $SB --query id -o tsv)
done
# Worker: no ingress, scales on queue length, can scale to 0 (--scale-rule-identity needs the containerapp extension)
az containerapp create -g $RG -n ca-orders-worker --environment $ENV --image $IMG \
--registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
--command orders-worker --min-replicas 0 --max-replicas 4 \
--scale-rule-name sb-orders --scale-rule-type azure-servicebus \
--scale-rule-metadata "queueName=orders" "namespace=$SB" "messageCount=5" \
--scale-rule-identity $ID_RID \
--secrets $SECRETS --env-vars $COMMON_ENV QUEUE_BACKEND=servicebus SERVICEBUS_NAMESPACE=$SB.servicebus.windows.net AZURE_CLIENT_ID=$ID_CID
# Scheduled report: cron is in UTC
az containerapp job create -g $RG -n job-report --environment $ENV --trigger-type Schedule \
--cron-expression "15 6 * * *" --replica-timeout 900 --replica-retry-limit 2 \
--parallelism 1 --replica-completion-count 1 --image $IMG \
--registry-server $ACR.azurecr.io --registry-identity $ID_RID --mi-user-assigned $ID_RID \
--secrets $SECRETS --env-vars $COMMON_ENV --command orders-report
az containerapp job start -g $RG -n job-report # manual backfill run
az containerapp job execution list -g $RG -n job-report -o table
| Point | Notes (checked against official docs, 2026-11) |
|---|---|
| Managed-identity scaling | Managed identity works for Azure Queue Storage, Service Bus and Event Hubs scale rules; CLI/ARM only, not the portal. The official CLI example covers azure-queue; here it is applied to azure-servicebus |
| KEDA defaults | Polling interval 30 s; cooldown 300 s (only for the last replica → 0) |
| AZURE_CLIENT_ID | Required when the app's DefaultAzureCredential uses a user-assigned identity |
| Event job vs long-running worker | Long (minutes) or isolated messages: a --trigger-type Event job (each execution takes a batch and exits); short tasks: a long-running worker is more efficient |
| Dead letters | Beyond --max-delivery-count, messages go to orders/$deadletterqueue; alert on its count |
2,000 duplicate shipments
A retailer's shipping worker was OOM-killed after calling the courier API but before acking; redelivery booked the shipment again. With no idempotency, one night produced 2,000 duplicate waybills. Fix: order number as idempotency key (the courier API supports them too); "check state before acting, update it atomically after"; raise the memory limit, monitor OOM kills. A queue only guarantees at least once; "exactly once" has to come from idempotency in the business layer.
Case 2: "Did it go out?" Dual-write gaps
Problem: the API committed, then published. During RabbitMQ maintenance, hundreds of orders were saved but never published, stuck pending until customers complained. Approach: transactional outbox: orders and outbox in one transaction; a background process forwards rows and marks them sent; plus a sweeper and alert for "pending over 10 minutes". Limitation: the outbox is at-least-once too (crash between forward and mark resends), so consumers stay idempotent.
Case 3: the cost of scaling to 0
Problem: to save money the notification worker ran with min-replicas 0. The first night-time "password reset" email took almost a minute (KEDA polling + image pull + startup), so users clicked three more times. Approach: split queues by latency: 1 replica for latency-sensitive ones, scale-to-0 for batch/report; make emails idempotent on "user + type + time window". Limitation: 1 replica bills continuously; record the trade-off in an ADR.
Common errors and fixes
pika.exceptions.AMQPConnectionError (when the worker starts)
RabbitMQ is not ready. The worker depends on rabbitmq: service_healthy; runtime disconnects recover via restart: unless-stopped.
PRECONDITION_FAILED - inequivalent arg 'x-dead-letter-exchange'
The queue exists with different arguments, which cannot be changed: delete it (losing messages) or set the DLX via a policy.
Messages pile up but all workers are "busy"
A large prefetch lets a few workers hold messages, or processing slowed. Check messages_unacknowledged and downstream latency (database, external APIs).
Worker exits with code 137 on shutdown
It was SIGKILLed after the grace period: the entrypoint uses sh -c instead of exec (SIGTERM never reaches Python), or one message outlasts stop_grace_period.
ACA worker does not scale out
Check KEDA errors in ContainerAppSystemLogs_CL: identity lacks Data Receiver, namespace given as FQDN (metadata takes the name), or --scale-rule-identity missing.
ACA scheduled job did not run at the expected time
Schedule job cron is in UTC: 06:15 Beijing time is 15 22 * * * (previous day). Check actual run times with az containerapp job execution list; record the time-zone convention in an ADR.
1. Refresh ready/unacked counts of all queues every 2 seconds and watch workers drain a backlog.
watch -n2 "docker compose exec -T rabbitmq rabbitmqctl -q list_queues name messages_ready messages_unacknowledged consumers"
2. Confirm the worker exits gracefully (exit code 0, not 137).
docker compose stop -t 30 worker
docker compose ps -a worker --format '{{.Name}} {{.State}} {{.ExitCode}}'3,000 messages suddenly hit the DLQ and worker logs are full of KeyError: 'order_id'. Your steps?
① Stop the bleeding: is the main queue consumed, is the DLQ growing? ② Locate: sample DLQ bodies, find the field renamed to orderId, trace the upstream publisher; ③ Fix: accept both formats (or roll back upstream); ④ Recover: shovel DLQ messages back (idempotency prevents double runs); ⑤ Prevent: version messages, contract tests, alert on DLQ depth > 0. See incident drill 5 in Module 8.
Verified teaching videos
- RabbitMQ: Consumer Acknowledgements and Publisher Confirms
- RabbitMQ: Dead Letter Exchanges
- Azure Container Apps: Set scaling rules
- Azure Container Apps: Jobs
- Azure Architecture Center: Transactional Outbox pattern
Video storyboard (about 60 seconds)
Visual: the API drops an order envelope into the queue and leaves; a worker opens letters one by one and stamps them "acknowledged".
Narration: accepting is decoupled from processing; at peak, messages wait instead of dragging the API down.
Visual: a "poison letter" bounces back three times, then slides into a red dead-letter box; an alarm lights.
Narration: retries need a cap; beyond it the message waits in dead letters for a human.
Visual: the SIGTERM bell rings; the worker stamps the letter in hand, turns off the light and leaves.
Narration: graceful shutdown: finish the current message, then exit.
Module 5 · Scenario ④: Database migrations and releases
- Run migrations as a separate one-off job, not at app startup, with an advisory lock against concurrency.
- Use expand/contract to split a breaking schema change into backward-compatible steps.
- Run a backup → restore → verify drill; know Azure point-in-time restore (PITR), groundwork for RPO / RTO in Module 7.
What: what the migration tool does
orders/migrate.py (about 30 lines): take a PostgreSQL advisory lock → create schema_migrations → run unapplied migrations/*.sql in name order, one transaction per file (failure rolls back the file) → record the version → unlock. Alembic, Flyway, Liquibase and Atlas work the same way.
Why: why not migrate when the API starts
- Replicas start together → migrate together → conflicts (the lock is only a safety net).
- Slow migrations → startup probe timeouts → restart loops.
- A failed migration should block the release, not strand half the replicas.
So in Compose, migrate is a one-off service that api/worker depend on via service_completed_successfully; on Azure it is a Container Apps Manual Job the pipeline awaits before updating the apps.
How: expand/contract
During a release old and new versions run together (rolling update, canary, rollback), so the schema must suit both v(N) and v(N+1). Example: add a required customer_email to orders:
| Step | Database | Application | Can we roll back to the previous version? |
|---|---|---|---|
| 1 Expand | ADD COLUMN customer_email text (nullable) | v1 still runs, ignores the new column | ✓ |
| 2 Release v2 | — | v2 writes the new column; tolerates NULL on read | ✓ (v1 ignores the new column) |
| 3 Backfill | UPDATE … WHERE customer_email IS NULL (in batches for big tables) | — | ✓ |
| 4 Contract | SET NOT NULL (or drop the old column) | Confirm no v1 remains | ✗ no rollback to v1 after this |
Here 002_expand_customer_email.sql is in migrations/; 003_contract_customer_email.sql waits in migrations-contract/ until every instance is upgraded. A rename works the same: add new column → dual-write → backfill → switch reads → drop old column.
When: which operations are dangerous
| Operation | Risk | Safe approach |
|---|---|---|
| NOT NULL / volatile default on a big table | Table rewrite or long lock | Add nullable, backfill in batches; on PG 11+ a constant default does not rewrite |
CREATE INDEX | Blocks writes | CREATE INDEX CONCURRENTLY (not inside a transaction; run separately) |
| Dropping/renaming a column | Old version errors at once | Expand/contract; drop last |
| Any DDL | While waiting for a lock it blocks every query behind it | SET lock_timeout = '5s' before migrating; retry on failure |
DROP TABLE instantly; PITR protects against human error (Module 7).Interactive simulator: a release with database changes
Play a release path: normal is expand → release → backfill → contract; failure paths show common migration incidents ("tested" = local run).
Tip: use "Next step" and ask each time: do v1 and v2 both work now? Is rollback safe here?
Code highlights
app/orders/migrate.py
LOCK_ID = 727274
DIR = os.getenv("MIGRATIONS_DIR", os.path.join(os.path.dirname(__file__), "..", "migrations"))
def main():
with psycopg.connect(config.DATABASE_URL, autocommit=True) as conn:
conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,)) # only one migration process at a time
try:
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations
(version text PRIMARY KEY, applied_at timestamptz DEFAULT now())""")
done = {r[0] for r in conn.execute("SELECT version FROM schema_migrations")}
for path in sorted(glob.glob(os.path.join(DIR, "*.sql"))):
ver = os.path.basename(path)
if ver in done:
continue
with conn.transaction(): # one transaction per file
conn.execute(open(path, encoding="utf-8").read())
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (ver,))
info(log, "applied", version=ver)
info(log, "up to date", applied=len(done))
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
CREATE TABLE IF NOT EXISTS orders ( id bigserial PRIMARY KEY, item text NOT NULL, qty integer NOT NULL CHECK (qty > 0), status text NOT NULL DEFAULT 'pending', idempotency_key text UNIQUE, created_at timestamptz NOT NULL DEFAULT now(), processed_at timestamptz ); CREATE TABLE IF NOT EXISTS daily_reports ( day date PRIMARY KEY, orders integer NOT NULL, items integer NOT NULL, generated_at timestamptz NOT NULL );
-- expand: only add a nullable column ALTER TABLE orders ADD COLUMN IF NOT EXISTS customer_email text; CREATE INDEX IF NOT EXISTS ix_orders_created_at ON orders (created_at);
-- contract: run only after every instance -- writes customer_email UPDATE orders SET customer_email = 'unknown@example.com' WHERE customer_email IS NULL; ALTER TABLE orders ALTER COLUMN customer_email SET NOT NULL;
Commands used in this module
| Command | Description |
|---|---|
docker compose run --rm migrate | Run migrations by hand (idempotent: applied ones are skipped) |
docker compose exec postgres psql -U orders -c 'TABLE schema_migrations' | Applied versions |
docker compose exec -T postgres pg_dump -U orders -Fc orders > orders.dump | Custom-format backup (-T disables the TTY so the binary stays intact) |
docker compose exec -T postgres pg_restore -U orders -d orders_restore --no-owner < orders.dump | Restore into another DB |
pg_dump --version | pg_dump version should be ≥ server version |
az postgres flexible-server restore -g RG -n NEW --source-server SRC --restore-time "2026-11-15T09:00:00Z" | Azure PITR to a new server |
az containerapp job execution list -g RG -n job-migrate --query "[0].properties.status" -o tsv | Latest migration job run status (Running / Succeeded / Failed) |
Protective settings (top of every migration file)
SET lock_timeout = '5s'; -- fail if waiting for a lock takes over 5 s, instead of queuing every later query SET statement_timeout = '15min'; -- keep a migration from accidentally running for hours -- backfill big tables in batches, each batch its own transaction: -- UPDATE orders SET customer_email = … WHERE id BETWEEN $1 AND $2 AND customer_email IS NULL;
Lab 5: concurrent migrations, contract, and backup/restore (about 5 minutes)
docker compose exec postgres psql -U orders -c 'TABLE schema_migrations' for i in 1 2 3; do docker compose run --rm -d migrate; done; sleep 8 docker compose logs migrate --no-log-prefix --since 15s | grep -c '"up to date"'
version | applied_at ------------------------------+------------------------------- 001_init.sql | 2026-11-15 … 002_expand_customer_email.sql| 2026-11-15 … 3
cp app/migrations-contract/003_contract_customer_email.sql app/migrations/ docker compose build migrate && docker compose run --rm migrate docker compose exec postgres psql -U orders -c '\d orders' | grep customer_email
{… "msg": "applied", "version": "003_contract_customer_email.sql"}
customer_email | text | | not null |
Now orders without an email fail (the sample front end still acts like v1): exactly "no rolling back to v1 after contract". To continue the lab, undo this step:
rm app/migrations/003_contract_customer_email.sql && docker compose build migrate docker compose exec postgres psql -U orders -c 'ALTER TABLE orders ALTER COLUMN customer_email DROP NOT NULL'
docker compose exec -T postgres pg_dump -U orders -Fc orders > orders-$(date +%F).dump ls -lh orders-*.dump docker compose exec postgres createdb -U orders orders_restore docker compose exec -T postgres pg_restore -U orders -d orders_restore --no-owner < orders-$(date +%F).dump for db in orders orders_restore; do docker compose exec postgres psql -U orders -d $db -tAc "SELECT '$db', count(*), max(id) FROM orders"; done docker compose exec postgres dropdb -U orders orders_restore
-rw-rw-r-- 1 azureuser azureuser 12K Nov 15 … orders-2026-11-15.dump orders|19|19 orders_restore|19|19
A backup whose restore has never been rehearsed is not a backup. In production, schedule the restore drill and record RTO (time to recover) and RPO (maximum data loss).
Cloud comparison: the migration step in the pipeline and managed backups
az containerapp job update -g $RG -n job-migrate --image $ACR.azurecr.io/orders:$SHA -o none
EXEC=$(az containerapp job start -g $RG -n job-migrate --query name -o tsv)
for i in $(seq 1 60); do
S=$(az containerapp job execution show -g $RG -n job-migrate --job-execution-name $EXEC --query properties.status -o tsv)
echo "migration: $S"; [ "$S" = "Succeeded" ] && break
[ "$S" = "Failed" ] && { echo "migration failed, stopping the release"; exit 1; }
sleep 10
done
[ "$S" = "Succeeded" ] || exit 1
az containerapp update -g $RG -n ca-orders-api --image $ACR.azurecr.io/orders:$SHA -o none
az containerapp update -g $RG -n ca-orders-worker --image $ACR.azurecr.io/orders:$SHA -o none
| Azure capability | Description |
|---|---|
| Automatic backups | Flexible Server keeps 7 days by default (1–35 configurable), with point-in-time restore to a new server |
| Restore drills | az postgres flexible-server restore … --restore-time restores to a temporary server; verify, then delete |
| High availability | General Purpose / Memory Optimized support same-zone or zone-redundant standby (not Burstable; see Module 7) |
| Long-term retention | Beyond 35 days: long-term backup (Azure Backup) or periodic exports |
job start returns the execution's name/id; job execution show --job-execution-name queries one execution (per the CLI reference).
One ALTER TABLE takes the whole site down for 20 minutes
A developer ran ALTER TABLE orders ADD COLUMN … NOT NULL DEFAULT gen_random_uuid() on a 300-million-row table. The volatile default rewrote it under an ACCESS EXCLUSIVE lock; all queries queued, the pool ran dry, the site returned 502. Fix: a migration review checklist (no big-table rewrites, mandatory lock_timeout, CONCURRENTLY indexes) and staging timing tests at production scale.
Case 2: backups always "succeeded", but the restore failed
Problem: a nightly pg_dump job had "succeeded" for three years. After an accidental delete, the team found the binary dumps were made via docker compose exec with a TTY: line endings rewritten, every file corrupt. Approach: export with exec -T; weekly auto-restore to a temporary database, compare row counts and checksums, record the RTO; keep PITR too. Limitation: drills cost servers and time; budget for them.
Case 3: the "phantom 500s" of a column rename
Problem: a release renamed phone to mobile, migrating first; for the 10-minute rolling update every old instance failed with column "phone" does not exist. Approach: expand/contract: "add new column → dual-write → backfill → switch reads → drop old column next release". Limitation: dual-write adds complexity; the ADR defines done criteria per step.
Common errors and fixes
api never starts; migrate exits with code 1
Check the SQL error in docker compose logs migrate, fix the file and rerun docker compose up -d; never modify an already-applied migration — add a new file instead.
The migration hangs
Another migration holds the advisory lock, or DDL waits for a table lock. SELECT pid, state, wait_event_type, query FROM pg_stat_activity WHERE datname='orders'; use lock_timeout to make it fail fast.
CREATE INDEX CONCURRENTLY cannot run inside a transaction block
This tool wraps each file in a transaction. Concurrent index builds need a non-transactional migration mode (Alembic and Flyway both support one).
pg_restore: error: input file appears to be a text format dump or a corrupt file
Load plain-text dumps with psql; binary exports via docker compose exec need -T.
ERROR: canceling statement due to lock timeout
lock_timeout working as designed: the DDL gives up after 5 seconds instead of blocking the site. Find the long transaction holding the lock (SELECT pid, now()-xact_start, query FROM pg_stat_activity WHERE state <> 'idle' ORDER BY 2 DESC) and retry the migration job off-peak.
1. See who currently holds the migration advisory lock (LOCK_ID = 727274).
docker compose exec postgres psql -U orders -c "SELECT l.pid, a.application_name, a.state, now()-a.query_start AS running FROM pg_locks l JOIN pg_stat_activity a USING (pid) WHERE l.locktype='advisory' AND l.objid=727274"
2. Right after a backup, check the file is readable (list its contents, no restore).
docker compose exec -T postgres pg_restore --list < orders-$(date +%F).dump | head -5
Change orders.qty from integer to numeric(10,2) on 200 million rows with zero downtime. Steps?
A direct ALTER COLUMN TYPE rewrites the table under an exclusive lock: not an option. Expand/contract: ① add nullable qty_dec numeric(10,2); ② v2 writes both, reads the new one (old as fallback); ③ backfill in rate-limited batches, one transaction each; ④ after verification, v3 uses only the new column; ⑤ next release, drop the old column and (optionally) rename. Set lock_timeout on every step; time it in staging at production scale.
Documentation and video
No verifiable high-quality video on expand/contract zero-downtime migrations was found; authoritative docs:
- PostgreSQL: Explicit locking and advisory locks
- PostgreSQL: CREATE INDEX CONCURRENTLY
- Martin Fowler: Parallel Change (expand/contract)
- PostgreSQL Flexible Server: Backup and restore
Video storyboard (about 60 seconds)
Visual: three migration processes rush the database; one gets the "advisory lock" key, the others wait, then find "already up to date".
Narration: Migrations are a separate one-off job; the advisory lock ensures only one runs at a time.
Visual: v1 and v2 run side by side while the schema changes step by step: nullable column, backfill, NOT NULL last.
Narration: Old and new versions run together during a release, so every schema change must suit both.
Visual: a backup is restored to a new database; a timer shows "RTO 4 minutes".
Narration: A backup whose restore has never been rehearsed is not a backup.
Module 6 · Scenario ⑤: File uploads and object storage
- Explain why uploads must not live in the container file system or a local volume (replicas + replaceability).
- Implement it: the API writes uploads to Blob and returns a short-lived read-only SAS link; the browser downloads straight from storage.
- Tell an account-key SAS from a user delegation SAS; on Azure, disable shared keys and use managed identity only.
- Know production practices: direct upload of large files (write SAS), malware scanning, lifecycle policies and storage redundancy (LRS / ZRS / GZRS, Module 7).
What: object storage
Blob storage is a flat "container / name → bytes + metadata" store with no real directories (the slash in reports/2026-11-15.csv is part of the name). Locally, Azurite (Microsoft's official emulator) runs the same azure-storage-blob SDK and code; only the connection differs.
Why: not the container file system or a volume
| Option | Problem |
|---|---|
| Container writable layer | Lost on container recreation; a file uploaded on replica A is invisible to replica B |
| Local named volume | One host only; no cross-host scaling; backup, permissions and CDN are on you |
| Database bytea/BLOB | Bloats the database, slows backup/replication, eats connections and memory |
| Object storage | ✓ Unlimited capacity, high durability (LRS keeps three copies), pay per use, lifecycle policies, browser-reachable |
The database stores only the reference (blob name, size, type, owner); bytes live in Blob.
How: SAS (shared access signature)
- A SAS is signed parameters appended to the URL: permission
sp=r, startst, expiryse, signaturesig. Changing any parameter invalidates it (403). - Account-key SAS: signed with the account key. A leaked key exposes the whole account; bulk revocation means rotating the key. Local Azurite uses this.
- User delegation SAS: the app's managed identity (Entra ID) obtains a user delegation key (valid up to 7 days) and signs with it; no account key, so shared-key access can be disabled. Recommended on Azure.
- Keep SAS short-lived (10 minutes here) and minimal (read-only); set
st1 minute back for clock skew.
When: upload through the API vs direct upload
| Upload through the API (this example) | Direct client upload (write SAS) | |
|---|---|---|
| Flow | Browser → gateway → API → Blob | API issues a write-only SAS → browser PUTs to Blob → notifies the API |
| Pros | Simple; the API can inspect content and restrict types | Large files skip API bandwidth and memory; parallel block upload |
| Cons | Large files tie up API processes; capped by the gateway's client_max_body_size | Needs storage CORS; validate asynchronously after upload (size, type, malware) |
| Good for | Avatars, attachments < 10 MB | Video, large files, mobile |
Interactive simulator: upload and download
Play a scenario to see the browser, API, Entra ID and Blob interact; failures map to real error codes in "Troubleshooting" ("tested" = from Azurite).
Code highlights
app/orders/storage.py
def client() -> BlobServiceClient:
global _client
if _client is None:
if config.STORAGE_CONNECTION_STRING: # local Azurite
_client = BlobServiceClient.from_connection_string(config.STORAGE_CONNECTION_STRING)
else: # Azure: managed identity, no keys
from azure.identity import DefaultAzureCredential
_client = BlobServiceClient(config.STORAGE_ACCOUNT_URL, credential=DefaultAzureCredential())
return _client
def download_url(name: str, minutes: int = 10) -> str:
svc = client()
start = datetime.now(timezone.utc) - timedelta(minutes=1) # tolerate clock skew
expiry = datetime.now(timezone.utc) + timedelta(minutes=minutes)
kwargs = dict(account_name=svc.account_name, container_name=config.BLOB_CONTAINER,
blob_name=name, permission=BlobSasPermissions(read=True), expiry=expiry, start=start)
if config.STORAGE_CONNECTION_STRING:
kwargs["account_key"] = svc.credential.account_key # local: account-key SAS
else:
kwargs["user_delegation_key"] = svc.get_user_delegation_key(start, expiry) # Azure: user delegation SAS
sas = generate_blob_sas(**kwargs)
if config.BLOB_PUBLIC_BASE: # local: Azurite uses path-style addresses, forwarded through the gateway's /blob/
return f"{config.BLOB_PUBLIC_BASE.rstrip('/')}/{svc.account_name}/{config.BLOB_CONTAINER}/{name}?{sas}"
return f"{svc.url.rstrip('/')}/{config.BLOB_CONTAINER}/{name}?{sas}"
app/orders/api.py (upload)
@app.post("/api/files")
def upload_file():
f = request.files.get("file")
if not f:
abort(400, "missing file")
name = f"{uuid.uuid4().hex}-{os.path.basename(f.filename or 'upload.bin')}" # never trust the client's file name
storage.upload(name, f.stream, f.mimetype or "application/octet-stream") # streamed upload, not read into memory in one piece
return jsonify(name=name, url=storage.download_url(name)), 201
compose.yaml and .env
azurite:
image: mcr.microsoft.com/azure-storage/azurite
command: ["azurite-blob", "--blobHost", "0.0.0.0", "--location", "/data", "--skipApiVersionCheck"]
volumes: [blobdata:/data]
AZURITE_CONN=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://azurite:10000/devstoreaccount1;
This is the fixed dev account key from the Azurite docs; it works only with the local emulator. --skipApiVersionCheck lets newer SDKs talk to the emulator.
Commands used in this module
| Command | Description |
|---|---|
curl -sk -F file=@a.pdf https://localhost:8443/api/files | Multipart upload |
docker compose exec api python -c "from orders import storage; print([b.name for b in storage.container().list_blobs()])" | List blobs (via the app's config and SDK) |
az storage blob list --account-name ST -c files --auth-mode login -o table | Azure: list with your Entra identity (Storage Blob Data Reader or higher) |
az storage blob generate-sas --account-name ST -c files -n x --permissions r --expiry 2026-11-15T12:00Z --auth-mode login --as-user --full-uri | Azure: generate a user delegation SAS |
az storage account update -g RG -n ST --allow-shared-key-access false | Disable account keys (then only Entra ID / user delegation SAS work) |
Lab 6: upload, SAS, tampering and sharing across replicas (about 5 minutes)
echo "hello blob" > hello.txt
J=$(curl -sk -F file=@hello.txt https://localhost:8443/api/files); echo "$J" | jq .
U=$(echo "$J" | jq -r .url)
curl -sk "$U"; echo
curl -sk -o /dev/null -w 'no SAS: %{http_code}\n' "${U%%\?*}"
{
"name": "2bc374fc…-hello.txt",
"url": "https://localhost:8443/blob/devstoreaccount1/files/2bc374fc…-hello.txt?st=…&se=…&sp=r&sv=2026-10-06&sr=b&sig=…"
}
hello blob
no SAS: 403T=$(echo "$U" | sed -E 's/se=([0-9]{4})/se=2099/')
curl -sk "$T" | grep -o '<Code>[^<]*'
<Code>AuthorizationFailure
The signature covers permissions and times, so the client cannot extend or escalate them.
docker compose up -d --force-recreate --scale api=2 api curl -sk "$U"; echo docker compose exec api python -c "from orders import storage; print([b.name for b in storage.container().list_blobs()])"
hello blob ['2bc374fc…-hello.txt', 'reports/2026-11-15.csv']
The report job's CSV (Module 4) is here too: process types share files via object storage, not a shared volume.
Cloud comparison: Blob Storage + managed identity
az storage account create -g $RG -n $ST -l $LOC --sku Standard_LRS --kind StorageV2 \ --allow-blob-public-access false --allow-shared-key-access false --min-tls-version TLS1_2 az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \ --role "Storage Blob Data Contributor" --scope $(az storage account show -g $RG -n $ST --query id -o tsv) # The app only needs: STORAGE_ACCOUNT_URL=https://$ST.blob.core.windows.net AZURE_CLIENT_ID=$ID_CID (no keys at all)
| Production point | Description |
|---|---|
| Roles | Storage Blob Data Contributor covers read/write and "generate user delegation key"; read-only: Data Reader + Storage Blob Delegator |
| Disable shared keys | --allow-shared-key-access false breaks all account-key SAS; only Entra ID / user delegation SAS remain |
| Malicious files | Microsoft Defender for Storage on-upload malware scanning; or a quarantine container first, moved once the scan passes |
| Lifecycle | Lifecycle policy: cool tier after 30 days, delete after 365 days; reports can get an immutable (WORM) policy |
| Direct upload | Issue a short-lived write-only (sp=cw) SAS for one blob name; storage CORS allows only your domain |
| Network | Private endpoint + public access disabled; browser downloads then need public reachability or Front Door |
A public container leaked customers' ID card photos
For easy front-end display, a team made the upload container public-read with predictable names (user-123-id.jpg); a security researcher enumerated the URLs and downloaded tens of thousands of ID card photos. Fix: account-level --allow-blob-public-access false, random names, short-lived read-only SAS, access logs and unusual-download alerts. Private by default, grant on demand, keep it short.
Case 2: one leaked connection string
Problem: a developer put an account-key connection string in a front-end config; an attacker listed and downloaded the whole account. Rotating the key killed every SAS it signed, breaking legitimate links (403) too. Approach: managed identity + user delegation SAS, --allow-shared-key-access false; key-type credentials only in Key Vault. Limits: some older tools and integrations need account keys; inventory them first.
Case 3: large files brought down the upload service
Problem: users began uploading 500 MB videos; relayed through the API, they exhausted gunicorn processes and memory, and order requests timed out. Approach: the API issues short-lived write-only (sp=cw) SAS for one blob name; the browser uploads blocks to Blob, and a completion event (Event Grid / a queue) triggers async validation and virus scanning. Limits: needs storage CORS; files stay quarantined until validated.
Common errors and fixes
AuthorizationFailure / Server failed to authenticate the request (Azurite)
Wrong account key in the connection string. The default Azurite key ends with …K1SZFPTOtr/KBHBeksoGMGw==; copy it from the official docs (typing it from memory caused this very error while writing this lesson).
AuthorizationPermissionMismatch (Azure)
The managed identity lacks a data-plane role (Owner/Contributor are management-plane), or a new assignment hasn't propagated yet (wait a few minutes).
KeyBasedAuthenticationNotPermitted
Shared keys are disabled, but the code still uses a connection string / account-key SAS. Switch to DefaultAzureCredential + user delegation SAS.
SAS link occasionally returns 403 AuthenticationFailed … Signed expiry time … / start time
Client and server clocks disagree. Move st 1 minute back, or omit it.
Uploading an 11 MB file returns 413
The gateway's client_max_body_size 10m applies (Module 3); use direct upload for large files.
1. Parse a SAS URL into permission, start and expiry.
echo "$U" | tr '?&' '\n\n' | grep -E '^(sp|st|se|sr|sv)='
2. (Azure) Check that the storage account has shared keys and public access disabled.
az storage account show -g $RG -n $ST --query "{sharedKey:allowSharedKeyAccess, public:allowBlobPublicAccess, tls:minimumTlsVersion}" -o tableSupport must briefly share one invoice with an external auditor who has no Azure account. What do you do?
After a permission check, the backend issues a user delegation SAS: read-only (sp=r), one blob (sr=b), lifetime as needed (e.g. 24 hours; the delegation key caps it at 7 days), optionally IP-restricted; log who issued it, to whom, when. Never a public container or account-key SAS. Revoking the user delegation key revokes early (and kills every SAS it signed).
Docs and video
No verifiable, high-quality video on current "user delegation SAS + managed identity" practice was found; official docs:
- Use the Azurite emulator for local development
- Create a user delegation SAS with Python
- Prevent Shared Key authorization
- Defender for Storage: malware scanning
Video storyboard (about 60 seconds)
Visual: two API replicas with local folders; the upload hits A, the download hits B: 404.
Narration: files can't live in the container; replicas can't see each other's, and recreation loses them.
Visual: the API gets a "delegation key" from Entra ID and signs the link for ten minutes; someone changes the time to 2099 and storage returns 403.
Narration: a short-lived, read-only, tamper-proof signature.
Visual: the storage account's "shared key" switch turns off, leaving managed identity as the only door.
Narration: on Azure, disable account keys; use identity only.
Module 7 · Scenario ⑥: High availability and disaster recovery
- Reason about availability by failure domain (replica → availability zone → region → human error), express requirements as RTO / RPO, and distinguish high availability (HA) from disaster recovery (DR).
- Name the Azure redundancy option for each orders layer: a zone-redundant ACA environment, Front Door priority failover, ACR geo-replication, and for PostgreSQL Flexible Server zone-redundant HA / cross-region read replicas / geo-redundant backup; with prerequisites, costs and limits.
- Compare AWS: ECS across AZs and AZ rebalancing, Route 53 failover routing, ECR cross-region replication, RDS Multi-AZ (instance / cluster) and Aurora.
- Choose a DR strategy (backup & restore / pilot light / warm standby / multi-site active-active) and write a drillable DR runbook.
What: failure domains and two metrics
| Failure domain | Typical event | Countermeasure | Covered in |
|---|---|---|---|
| Process / replica | OOM, crash, single node failure | Multiple replicas + probes + platform auto-replacement | Modules 2, 4 |
| Availability zone (AZ) | Data centers lose power or network | Zone redundancy: compute, data and storage across several AZs, automatic failover | This module |
| Region | Region-wide outage, major network incident | Multi-region: images, data replicas, compute and a global entry point in a second region; usually a human decision | This module |
| Human error / data corruption | Dropped table, bad migration, ransomware | Backups and point-in-time restore: replication copies the mistake too | Module 5, this module |
- RTO (Recovery Time Objective): how soon service must be back after a failure: "detect + decide + fail over + warm up + DNS/connection convergence".
- RPO (Recovery Point Objective): how much data (in time) you can afford to lose. Synchronous replication ≈ 0; asynchronous = replication lag; backup restore = time since the last usable backup/log.
- High availability (HA): handles replica and AZ failures in one region automatically; users barely notice. Disaster recovery (DR): handles region-level failures and data disasters, usually with a human decision, some data loss and downtime.
Why: orders' single points of failure today
For cost and simplicity, the final lab's azure/deploy.sh deploys a single-region, non-zone-redundant system:
| Component (final lab) | Current state | When an AZ fails | When the region fails |
|---|---|---|---|
ACA environment cae-orders | No VNet, no zone redundancy | All replicas may be in the failed zone; down until the platform rebuilds them elsewhere | Unavailable |
| PostgreSQL B1ms (Burstable) | Burstable: no HA; a single server | Database down (data safe in ZRS backups) | Unavailable; without geo-redundant backup, wait for the region to recover |
| ACR Basic | One region; geo-replication requires Premium | Handled by the managed service | New replicas can't pull images → no scale-out, no deployment elsewhere |
| Blob, Service Bus, Managed Redis | Default SKU / redundancy | Per each one's redundancy setting (e.g. storage LRS vs ZRS) | Per each one's geo options |
How: add redundancy layer by layer (Azure first)
| Layer | Zone level (same region) | Region level (second region) | Prerequisites · cost · limits (verified 2026-11) |
|---|---|---|---|
| Compute ACA | Zone-redundant environment: replicas spread across AZs automatically; failed-zone replicas are removed and probes usually reroute traffic within about 30 seconds | Another environment in the second region, same app digest | Set only at environment creation, never toggled later; requires a VNet (workload profiles subnet ≥ /27, legacy Consumption-only ≥ /23); replicas spread across zones only with min replicas ≥ 2; no extra charge |
| Ingress | ACA ingress is zone-redundant with the environment | Front Door Standard/Premium: origin group priority routing (1–5, 1 highest) for primary/standby, health probes decide origin health; Traffic Manager (DNS level) is an alternative | Front Door (classic) retires 2027-03-31; origins should accept only Front Door traffic |
| Images ACR | Geo-replicas are always zone-redundant | Geo-replication: one registry, one global endpoint (myregistry.azurecr.io), every replica read-write (active-active); the global endpoint routes to healthy replicas automatically | Requires Premium; eventually consistent: a pull elsewhere right after a push may give manifest unknown; storage billed per replica; with the home region down, control plane and ACR Tasks are unavailable, push/pull unaffected |
| Data PostgreSQL Flexible Server | Zone-redundant HA: hot standby in another AZ, sync replication, automatic forced failover on AZ failure, typically 60–120 seconds, RPO 0 | Cross-region read replicas (up to 5, async, lag usually several minutes or more) + virtual endpoints; on region failure promote manually (forced), typically 1–3 minutes, losing unreplicated data; or restore a geo-redundant backup into the paired region (larger RTO/RPO) | HA: General Purpose / Memory Optimized only, not Burstable; the standby costs the same as the primary; read replicas can't have HA (enable it after promotion); geo-redundant backup is chosen only at server creation; SLA: zone-redundant HA 99.99%, same-zone HA 99.95%, no HA 99.9% |
| Files Blob | ZRS (zone-redundant storage) | GZRS / RA-GZRS (geo-replicated to the paired region) | Higher redundancy, higher unit price; geo-replication is asynchronous |
When: which DR strategy to pick
| Strategy | What the second region normally has | RTO / RPO (order of magnitude) | Cost | Suits |
|---|---|---|---|---|
| Backup & restore | Backups only (geo-redundant backups, image replicas) | Hours / minutes to hours | Lowest | Internal systems tolerating half a day of downtime |
| Pilot light | Continuous data replication (read replica) + images; compute off or minimal | Tens of minutes / minutes | Low | Default for most business systems |
| Warm standby | Data replication + an always-running scaled-down app copy | Minutes / seconds to minutes | Medium | Customer-facing core business |
| Multi-site (active-active) | Both regions serve; data multi-writer or partitioned | Near 0 / near 0 (depends on the data tier) | Highest; most complex | Global business, strict SLAs; needs a multi-writer database and conflict handling, beyond this course |
Suggested path for orders: ① Primary-region zone redundancy first (zone-redundant ACA environment + min 2 replicas, PostgreSQL General Purpose with zone-redundant HA, Blob ZRS); the main cost is the database standby. ② Then pilot light / warm standby: ACR Premium geo-replication, PostgreSQL cross-region read replica + virtual endpoint, a second-region ACA environment (min replicas 0–1), Front Door priority routing. ③ Drill quarterly; record real RTO / RPO.
DROP TABLE hits the standby instantly; only PITR undoes mistakes. ② "A zone-redundant environment is enough": with min replicas 1, nothing spreads across zones. ③ "The read replica takes over automatically": Azure does not auto-promote cross-region replicas, and the promoted server has no HA. ④ "Geo-replicated images can always be pulled": replication is eventually consistent; deploy by digest or regions may run different images. ⑤ "Failover is just a DNS change": secrets (Key Vault), managed-identity role assignments, firewall rules, queues and caches must exist in the second region too; drills expose these most.Architecture: orders across two regions (pilot light / warm standby)
Comparison: Azure vs AWS
| Layer | Azure (this course's main path) | AWS (compare with hour 4) |
|---|---|---|
| Compute across AZs | ACA zone-redundant environment: set at creation, VNet, min replicas ≥ 2, no extra cost | ECS service subnets span several AZs; Fargate spreads tasks across AZs best-effort; AZ rebalancing is enabled for eligible services since 2025-09-05 (new services default to ENABLED), not supported with settings such as maximumPercent of 100% |
| In-region load balancing | ACA built-in ingress | ALB (cross-AZ) |
| Global entry / failover | Front Door priority routing + health probes; Traffic Manager (DNS) | Route 53 failover routing (primary/secondary records + health checks); CloudFront origin group failover; Global Accelerator |
| Images across regions | ACR geo-replication (Premium): one registry, global endpoint, active-active, eventually consistent | ECR replication (registry-level rules): cross-region/cross-account, filtered by repository prefix; only images pushed after setup are replicated (backfill existing ones); repository settings aren't replicated by default (use repository creation templates); most images finish within 30 minutes; the destination is a separate registry address |
| Database, AZ level | PostgreSQL Flexible Server zone-redundant HA (sync, 60–120 seconds) | RDS Multi-AZ instance (1 non-readable standby); Multi-AZ cluster (2 readable standbys, semi-synchronous, 3 AZs); Aurora (6 storage copies across 3 AZs, failover usually < 60 seconds, often < 30 seconds) |
| Database, region level | Cross-region read replica + virtual endpoint; geo-redundant backup → paired-region restore | Cross-region read replicas; Aurora Global Database (async replication to secondary regions); cross-region backup replication |
| Object storage | Blob ZRS / GZRS / RA-GZRS | S3 (multi-AZ by default) + Cross-Region Replication (CRR) |
Interactive simulator: failure and failover
Pick a cloud and failure type, then play: detection, failover, recovery and the resulting RTO / RPO (timings are typical orders of magnitude from the docs; output is illustrative).
RTO / RPO calculator
Enter each runbook step's duration and compare with the business target; these are estimates, real values come from drills.
Azure: zone redundancy (examples, not run in a real environment)
# 1) VNet and infrastructure subnet (workload profiles environment ≥ /27; subnet delegated to Microsoft.App/environments) az network vnet create -g $RG -n vnet-orders -l $LOC --address-prefix 10.10.0.0/16 -o none az network vnet subnet create -g $RG --vnet-name vnet-orders -n infra \ --address-prefixes 10.10.0.0/23 --delegations Microsoft.App/environments -o none SUBNET=$(az network vnet subnet show -g $RG --vnet-name vnet-orders -n infra --query id -o tsv) # 2) Zone-redundant environment: cannot be turned on or off after creation az containerapp env create -g $RG -n cae-orders-zr -l $LOC \ --infrastructure-subnet-resource-id $SUBNET --zone-redundant az containerapp env show -g $RG -n cae-orders-zr --query properties.zoneRedundant # 3) Existing apps don't move to the new environment: recreate them in cae-orders-zr (same parameters as the final lab, --environment cae-orders-zr); # replicas spread across AZs only with min replicas ≥ 2 — shown here for the recreated ca-orders-api az containerapp update -g $RG -n ca-orders-api --min-replicas 2 --max-replicas 5 -o none
true
# Burstable does not support HA: move to General Purpose first (restarts the server, pick a quiet period)
az postgres flexible-server update -g $RG -n $PG --tier GeneralPurpose --sku-name Standard_D2ds_v5
az postgres flexible-server update -g $RG -n $PG --zonal-resiliency Enabled --standby-zone 2
az postgres flexible-server show -g $RG -n $PG --query "{ha:highAvailability.mode, state:highAvailability.state, zone:availabilityZone, standby:highAvailability.standbyAvailabilityZone}" -o table
# Drill: planned failover (Planned); simulate an unplanned failure with Forced (non-production only)
az postgres flexible-server restart -g $RG -n $PG --failover Planned
Ha State Zone Standby ------------- ------- ------ --------- ZoneRedundant Healthy 1 2
Note: the current CLI enables HA with --zonal-resiliency Enabled (with --zone / --standby-zone; add --allow-same-zone if zone capacity is short); older tutorials use --high-availability ZoneRedundant. Trust az postgres flexible-server update -h and check query field names against the actual JSON.
Azure: region level (second region canadaeast)
# ACR: geo-replication needs Premium; storage is billed per replica az acr update -n $ACR --sku Premium -o none az acr replication create -r $ACR -l canadaeast -o none az acr replication list -r $ACR -o table # PostgreSQL: cross-region read replica (async) + read-write virtual endpoint (follows the new primary after promotion) az postgres flexible-server replica create -g $RG -n $PG-dr --source-server $PG -l canadaeast az postgres flexible-server virtual-endpoint create -g $RG --server-name $PG -n orders-ve \ --endpoint-type ReadWrite --members $PG-dr # Drill (no data loss): planned switchover; in a real region outage use --promote-option forced (loses unreplicated data) az postgres flexible-server replica promote -g $RG -n $PG-dr --promote-mode switchover --promote-option planned
NAME LOCATION PROVISIONING STATUS ----------- ------------- -------------- -------- canadacentral canadacentral Succeeded Online canadaeast canadaeast Succeeded Online
az afd profile create -g $RG --profile-name afd-orders --sku Standard_AzureFrontDoor az afd endpoint create -g $RG --profile-name afd-orders --endpoint-name orders --enabled-state Enabled az afd origin-group create -g $RG --profile-name afd-orders --origin-group-name og-orders \ --probe-request-type GET --probe-protocol Https --probe-path /readyz --probe-interval-in-seconds 30 \ --sample-size 4 --successful-samples-required 3 --additional-latency-in-milliseconds 50 az afd origin create -g $RG --profile-name afd-orders --origin-group-name og-orders --origin-name primary \ --host-name $FQDN_PRIMARY --origin-host-header $FQDN_PRIMARY --priority 1 --weight 1000 --enabled-state Enabled az afd origin create -g $RG --profile-name afd-orders --origin-group-name og-orders --origin-name secondary \ --host-name $FQDN_DR --origin-host-header $FQDN_DR --priority 2 --weight 1000 --enabled-state Enabled az afd route create -g $RG --profile-name afd-orders --endpoint-name orders --route-name default \ --origin-group og-orders --supported-protocols Https --forwarding-protocol HttpsOnly --link-to-default-domain Enabled
Mind the probe semantics: a DR read replica still answers SELECT 1, so /readyz says "healthy"; hence priority routing, not weights: DR gets no traffic while the primary is healthy. Stricter: readiness checks pg_is_in_recovery() and returns 503 on a replica.
# At creation: --geo-redundant-backup Enabled; on a region failure, restore to a new server in the paired region az postgres flexible-server geo-restore -g $RG_DR -n $PG-geo --source-server $PG_ID -l canadaeast
AWS comparison (ECS / ECR / RDS from Hour 4, examples)
# ECS: subnets spanning three AZs + AZ rebalancing
aws ecs update-service --cluster $CLUSTER --service $SVC --desired-count 3 \
--availability-zone-rebalancing ENABLED \
--network-configuration "awsvpcConfiguration={subnets=[$SUBNET_A,$SUBNET_B,$SUBNET_C],securityGroups=[$SG],assignPublicIp=DISABLED}"
# ECR: registry-level replication rule (only images pushed afterwards are replicated)
aws ecr put-replication-configuration --replication-configuration \
'{"rules":[{"destinations":[{"region":"us-east-1","registryId":"111122223333"}],"repositoryFilters":[{"filter":"orders","filterType":"PREFIX_MATCH"}]}]}'
aws ecr describe-image-replication-status --repository-name orders --image-id imageTag=sha-3f9a2c1
# RDS: convert to a Multi-AZ instance deployment; drill with a forced-failover reboot
aws rds modify-db-instance --db-instance-identifier orders-db --multi-az --apply-immediately
aws rds reboot-db-instance --db-instance-identifier orders-db --force-failover
{
"replicationStatuses": [
{ "region": "us-east-1", "registryId": "111122223333", "status": "COMPLETE" }
]
}
Command overview
| Command | Purpose |
|---|---|
az containerapp env show … --query properties.zoneRedundant | Is the environment zone-redundant? |
az containerapp replica list -g RG -n APP -o table | Replica count (meaningful at ≥ 2) |
az acr replication list -r ACR -o table | Geo-replica status (anything but Online is trouble) |
az postgres flexible-server restart --failover Planned|Forced | HA failover drill |
az postgres flexible-server replica promote --promote-mode switchover --promote-option planned|forced | Cross-region failover |
aws ecs describe-services … --query 'services[0].availabilityZoneRebalancing' | ECS rebalancing setting |
aws rds describe-db-instances … --query 'DBInstances[0].[MultiAZ,AvailabilityZone,SecondaryAvailabilityZone]' | RDS Multi-AZ and current AZ |
Lab 7: measure RTO locally, then write an orders DR runbook (about 7 minutes)
Multi-region cloud deployment is expensive, so this lab simulates a region failover locally ("database lost → restore backup into a new database → switch connections"), measures the real recovery time and records it in a runbook. Commands not individually tested; outputs are examples.
B=https://localhost:8443; C="curl -sk"
docker compose exec -T postgres pg_dump -U orders -Fc orders > dr.dump # the latest "off-site backup"
$C -X POST $B/api/orders -H 'Content-Type: application/json' -d '{"item":"after-backup","qty":1}' -o /dev/null
T0=$(date +%s); echo "disaster at $(date +%T)"
docker compose stop api worker # simulate primary-region compute outage (the database itself stays; next step builds the "secondary region" DB)orders_dr and point the app at it via an override file.
docker compose exec postgres createdb -U orders orders_dr
docker compose exec -T postgres pg_restore -U orders -d orders_dr --no-owner < dr.dump
cat > compose.dr.yaml <<'EOF2'
services:
api: { environment: { DATABASE_URL: "postgresql://orders:${DB_PASSWORD}@postgres:5432/orders_dr" } }
worker: { environment: { DATABASE_URL: "postgresql://orders:${DB_PASSWORD}@postgres:5432/orders_dr" } }
EOF2
docker compose -f compose.yaml -f compose.dr.yaml up -d api worker
until $C -fs $B/api/stats -o /dev/null; do sleep 1; done
echo "RTO = $(( $(date +%s) - T0 )) s"
$C $B/api/stats | jq -c '{orders}'
RTO = 41 s
{"orders":18}
The after-backup order is missing from orders_dr: that's the RPO, writes after the latest usable copy. With a cloud cross-region read replica, RPO ≈ replication lag.
docker compose up -d api worker # without the override file, back to the orders database docker compose exec postgres dropdb -U orders orders_dr rm -f compose.dr.yaml dr.dump
docs/dr-runbook.md and fill in the RTO / RPO calculator estimates and your local measurements.
# orders disaster recovery runbook Targets: RTO ≤ 30 minutes, RPO ≤ 5 minutes (source: ADR-0007) ## Trigger (who may declare a disaster) - Primary-region Front Door origin unhealthy for 10 consecutive minutes, and Azure Service Health confirms a regional incident ## Failover steps 1. Freeze releases (pause pipelines) 2. Promote the PostgreSQL read replica: replica promote --promote-mode switchover --promote-option forced 3. Confirm the virtual endpoint points at the new primary; check the replication-lag record to estimate the lost data window 4. Secondary-region ACA: raise min replicas to 2; confirm the image digest matches the primary region 5. Confirm Front Door probes moved to the secondary region; run smoke.sh https://<Front Door domain> 6. Notify; enable HA on the new primary ## Failback (after the region recovers) - The old primary automatically becomes a read replica → planned switchover back during off-peak hours ## Drill log | Date | Type | Measured RTO | Measured RPO | Issues found |
Read-only check: your final-lab deployment's single points of failure (optional, needs the final lab deployed)
az containerapp env show -g $RG -n cae-orders --query "{zr:properties.zoneRedundant, vnet:properties.vnetConfiguration.infrastructureSubnetId}" -o table
az containerapp show -g $RG -n ca-orders-api --query "properties.template.scale.{min:minReplicas,max:maxReplicas}" -o table
az postgres flexible-server show -g $RG -n $PG --query "{tier:sku.tier, ha:highAvailability.mode, geo:backup.geoRedundantBackup}" -o table
az acr show -n $ACR --query sku.name -o tsv
Zr Vnet ----- ------ False Min Max ----- ----- 1 5 Tier Ha Geo --------- -------- -------- Burstable Disabled Disabled Basic
The four outputs are four single points of failure: non-zone-redundant environment, min 1 replica, Burstable without HA or geo-redundant backup, ACR Basic (no geo-replication). Score them as "Reliability" deductions in the Module 8 scorer.
Case 1: a zone-redundant environment with only one replica
Problem: the team built a zone-redundant Container Apps environment but set API min replicas to 1 to save money. When that replica's zone failed, the service was down until a replica was rebuilt in another zone and passed readiness. Approach: critical apps get min replicas ≥ 2 (more to survive multiple zone failures or shorten the wait), plus resource requests so replicas fit in other zones; check "zone redundancy + min replicas" together in reviews. Limitation: min replicas ≥ 2 bills continuously; use it for ingress and API, and let the worker scale on the queue.
Case 2: the secondary region had everything except secrets
Problem: in a DR drill, replica promotion and the Front Door switch went smoothly, but no secondary-region API replica started: Key Vault references pointed at the primary vault, the managed identity had no role assignments there, and Service Bus existed only in the primary region. Approach: IaC (Terraform / Bicep) instantiates one template per region; secrets exist in both regions (or in a vault reachable across regions); the drill checklist covers identity, secrets, network, queue and cache. Limitation: each region is more configuration to maintain, the hidden cost of multi-region.
Case 3: HA failover took 90 seconds, yet the app was down for 20 minutes
Problem: PostgreSQL zone-redundant HA failed over in 1–2 minutes, but the pool kept stale connections, nothing retried, and readiness checked only the process, so every replica returned 500 until restarted by hand. Approach: the pool rebuilds failed connections; database calls retry transient errors a bounded number of times with backoff (writes use idempotency keys); readiness checks the database with its own short connection (Module 2); rehearse in staging with --failover Forced. Limitation: retries amplify traffic; cap them and add jitter.
Common errors and fixes
Can't enable zone redundancy on an existing ACA environment (no option / command fails)
Cause: zone redundancy is set only at environment creation, can't be toggled afterwards, and requires a VNet infrastructure subnet.
Fix: create a new environment with --infrastructure-subnet-resource-id and --zone-redundant, redeploy the apps (by digest), then switch ingress.
Enabling PostgreSQL HA fails: the current compute tier does not support high availability
Cause: Burstable supports neither HA nor read replicas.
az postgres flexible-server show -g $RG -n $PG --query sku -o table
Fix: first update --tier GeneralPurpose --sku-name …, then --zonal-resiliency Enabled. If zone capacity is short, --allow-same-zone deploys in the same zone first; the platform moves it once capacity frees up.
manifest unknown: a just-pushed image fails to pull in another region
Cause: ACR geo-replication is eventually consistent and large images take time; a DNS switch mid-push can also leave manifest layers missing from a replica (blob unknown).
Fix: wait for replication before deploying (per-replica ACR webhook events, or retry pulls with backoff); for strict consistency, pin push and pull to one replica via regional endpoints; deploy by digest.
replica promote --promote-mode switchover fails: the replica has no virtual endpoint assigned
Cause: "promote to primary server (switchover)" requires the replica to be a virtual endpoint member.
az postgres flexible-server virtual-endpoint list -g $RG --server-name $PG -o table
Fix: first create / update the virtual endpoint and add the replica to --members; or --promote-mode standalone promotes it to an independent server (then change the connection string by hand).
Old images are missing in the ECR destination region
Cause: ECR replication only copies images pushed (or restored) after the rule was configured; repository policies, lifecycle policies and tag immutability aren't replicated by default either.
Fix: backfill or re-push existing images; standardize destination repository settings with repository creation templates; check status with describe-image-replication-status.
ECS tasks concentrate in one availability zone and rebalancing doesn't start
Cause: subnets cover only one zone; or the config fails rebalancing conditions (maximumPercent 100%, Classic Load Balancer, first placement strategy not spread by zone, etc.); or the service isn't steady yet.
aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].{rebal:availabilityZoneRebalancing,dep:deploymentConfiguration,net:networkConfiguration}'
Fix: give the service multi-zone subnets, set maximumPercent > 100, and check service events for SERVICE_REBALANCING_STOPPED.
Front Door returns 503 and both origins show "unhealthy"
Cause: wrong probe path (e.g. /api/readyz vs the app's /readyz), origin host header mismatch (ACA returns 404), or origin source restrictions that block Front Door.
Fix: verify externally with curl -sI https://origin/readyz; set --origin-host-header to the origin FQDN; restrict sources with the AzureFrontDoor.Backend service tag plus an X-Azure-FDID header check.
1. In one command, list the tier and HA mode of every PostgreSQL flexible server in the resource group.
az postgres flexible-server list -g $RG --query "[].{name:name, tier:sku.tier, ha:highAvailability.mode, zone:availabilityZone}" -o table2. Before deploying to the secondary region, confirm every ACR geo-replica is online.
az acr replication list -r $ACR --query "[?status.displayStatus!='Online'].name" -o tsv | grep -q . && echo "some replicas offline" || echo "all online"
Business requirement: RTO 30 minutes, RPO 5 minutes, limited budget. What level should orders reach?
No need for active-active. ① Primary region: zone-redundant ACA environment + API min 2 replicas; PostgreSQL General Purpose with zone-redundant HA (zone failure: RPO 0, 1–2 minute recovery). ② Region level, pilot light: ACR Premium geo-replication; PostgreSQL cross-region read replica + virtual endpoint (RPO ≈ replication lag; monitor to keep it < 5 minutes); secondary-region ACA environment and apps pre-deployed with min replicas 0; Front Door priority routing. ③ Runbook + quarterly drills recording measured RTO. Geo-redundant backup restore alone usually can't reliably meet a 5-minute RPO and 30-minute RTO.
Verified teaching videos
Official documentation
- Reliability in Azure Container Apps · Create a zone-redundant container app
- Reliability in Azure Database for PostgreSQL (HA, read replicas, backups)
- ACR geo-replication · Front Door origin routing methods
- Amazon ECR private image replication · ECS Availability Zone rebalancing
- RDS Multi-AZ · Aurora high availability · Route 53 DNS failover
Video storyboard (about 90 seconds)
No video/MP3 is generated here; this storyboard and narration script can feed a video tool.
Visual: four concentric circles light up in turn: replica, availability zone, region, human error, labeled multiple replicas, zone redundancy, multi-region, backups.
Narration: Design availability in layers by failure domain; each layer needs its own measure.
Visual: zone 1 goes dark, ACA replicas keep serving in zones 2 and 3; the PostgreSQL standby becomes primary, a timer shows 90 seconds, data loss 0.
Narration: In-region redundancy kicks in automatically: synchronous replication, zero RPO.
Visual: the primary region turns gray; following the runbook, the on-call engineer clicks "promote replica" and the Front Door arrow swings to the secondary region; a corner shows "2 minutes of data lost".
Narration: Cross-region failover needs a human decision; async replication may lose a little data.
Visual: someone runs DROP TABLE and primary and standby lose the table together; the timeline rewinds five minutes and a new server is restored.
Narration: HA can't save you from mistakes; backups and point-in-time restore can.
Module 8 · Architecture review and incident drill
- Run a failure mode analysis on orders: fail each component in turn and record user impact, existing mitigation and gap.
- Score the system on a condensed five-pillar Well-Architected checklist and find top-priority improvements (reliability and security first).
- Diagnose 7 incident drills from logs and command output, and practice symptom-to-diagnosis with the interactive troubleshooting tree.
- Know what hour 7 (deep troubleshooting, performance tuning, advanced topics) does next with this system.
Failure mode analysis (this system)
| Component failure | What users see | Mitigation in the design | What is still missing |
|---|---|---|---|
| 1 api replica crashes | Nothing | 2 replicas + health checks + gateway re-resolution | — |
| Redis down | Slower responses | Cache degradation, 0.5 s timeout | Database capacity for uncached traffic |
| RabbitMQ down | Order placement errors (publish fails) | Worker reconnects | Outbox pattern; highly available Service Bus on Azure |
| All workers stopped | Orders stuck in pending | Durable messages, processed after recovery | Queue depth alert |
| Database down | Whole site unavailable | Readiness probe returns 503 | Managed database + zone-redundant HA; backup/PITR drills (Module 7) |
| Blob unavailable | Upload/download fails, ordering works | Feature isolation | Retries, friendly message |
| Host down | Everything unavailable | — | Inherent to single-host Compose → ACA multi-replica + zone redundancy (Module 7) |
Review checklist (condensed five Well-Architected pillars)
| Pillar | Checks |
|---|---|
| Reliability | No single point of failure? Separate probes? Idempotency? Dead-lettering? Backups restorable? |
| Security | Only the gateway exposed? No keys (managed identity)? Secrets in Key Vault? Non-root? Private storage + short-lived SAS? |
| Cost | Workers scale to 0? Database SKU fits the connection budget? Lifecycle policies? |
| Operations | JSON logs + request ID? Separate migration job? One image, many processes? Alerts (DLQ, 5xx, restarts)? |
| Performance | Caching? Connection pooling? Slow work async? Large files uploaded directly? |
How: running a review
- Prepare: the latest architecture diagram (Module 1), ADR list and non-functional requirements (availability, RTO/RPO, latency).
- Analyze failure per component (table above): write impact as "what users see", not "the component errors".
- Score the five pillars (Animation tab scorer); fix reliability and security gaps first.
- Verify with drills: every design mitigation needs a drill proving it works — this lesson's failure-drill labs are that evidence.
- Output: a risk list (owner, due date) + new ADRs + next review date.
When: cadence of reviews and drills
Full review before go-live, then quarterly and before every major architecture change (new component, region or database). Drill more often: schedule the Modules 2–7 failure-drill scripts in staging and log results in the runbook.
Coming up in Hour 7
| Topic | Content |
|---|---|
| Deep troubleshooting | nsenter / docker debug, tcpdump, strace, /proc, OOM/cgroup events, DNS/MTU issues, zombie processes |
| Performance tuning | Load testing (k6), P95/P99, gunicorn processes/threads, pool tuning, slow queries, Redis hot keys |
| Build extensions | Remote BuildKit, cache backends, Bake matrices, multi-arch builds |
| Advanced networking | macvlan/ipvlan, IPv6, overlay troubleshooting, iptables/nftables rules |
| Developer experience | Dev Containers, Testcontainers tests, Compose Watch |
| GPU / AI workloads | NVIDIA Container Toolkit, --gpus, model-serving containers |
| Failure drills | Chaos experiments: latency injection, full disks, dependency timeouts |
Failure mode heat map: impact × current state
Knowledge map: six scenarios, one system
| Module | Patterns | Incidents prevented | Drill evidence |
|---|---|---|---|
| 2 | Connection budget, cache-aside + degradation, separate probes, idempotency keys | Scale-out swamping the database, cache failure downing the site, duplicate orders | Redis stopped → 200; database frozen → /readyz 503 in 2 s (tested) |
| 3 | Single entry point, TLS, rate limiting, dynamic DNS | Expired certs, traffic bursts, 502 after scaling | 50 concurrent → 22×200 / 28×429 (tested) |
| 4 | At-least-once + idempotency, retries + dead-lettering, graceful shutdown | Duplicate shipments, poison messages blocking the queue, half-done work during releases | Poison message to DLQ after 3 attempts |
| 5 | Migration job + advisory lock, expand/contract, restore drills | Old version errors during releases, long-lock downtime, bad backups | 3 concurrent migrations run only once (tested) |
| 6 | Object storage, short-lived read-only SAS, shared keys disabled | Lost files, data leaks | Tampered se → 403 (tested) |
| 7 | Zone redundancy, geo-replication, read replicas, runbooks | Zone / region outages, accidental deletion | Local RTO measurement, planned failover |
Interactive simulator: incident post-mortem timeline
Pick an incident and play: alert → locate → stop the bleeding → root cause → improvement. Each maps to an earlier module's design gap (output is illustrative).
Architecture review scorer
Tick what your system has for per-pillar scores and top-priority fixes (defaults reflect this lesson's Azure design; Module 7 items start unticked).
Review check commands
| Check | Local command | Azure command |
|---|---|---|
| Exposure | docker compose ps --format '{{.Service}} {{.Ports}}' | az containerapp list -g RG --query "[].{n:name,ext:properties.configuration.ingress.external}" -o table |
| Non-root | docker compose exec api id -u | Image USER 10001 (hour 2) |
| No secrets in images/code | docker image history --no-trunc orders:1.0 | grep -iE 'password|key' | az containerapp show … --query "properties.configuration.secrets[].keyVaultUrl" |
| Replicas and scaling | docker compose ps api worker | az containerapp show … --query properties.template.scale |
| Dead letters | rabbitmqctl list_queues name messages | az servicebus queue show … --query countDetails.deadLetterMessageCount |
| Backups and HA | ls -lh orders-*.dump | az postgres flexible-server show … --query "{ha:highAvailability.mode,retention:backup.backupRetentionDays}" |
One-shot review script (local)
#!/usr/bin/env bash
set -uo pipefail
ok(){ echo "✓ $*"; }; bad(){ echo "✗ $*"; }
[ "$(docker compose ps --format '{{.Ports}}' | grep -c '0.0.0.0')" -le 2 ] && ok "only the gateway publishes ports" || bad "extra published ports found"
[ "$(docker compose exec -T api id -u)" != 0 ] && ok "api is non-root" || bad "api runs as root"
[ "$(docker compose ps -q api | wc -l)" -ge 2 ] && ok "api ≥ 2 replicas" || bad "api has only 1 replica"
docker compose exec -T api python -c "import urllib.request as u;u.urlopen('http://127.0.0.1:8000/readyz',timeout=3)" 2>/dev/null && ok "readiness probe OK" || bad "readiness probe failed"
DLQ=$(docker compose exec -T rabbitmq rabbitmqctl -q list_queues name messages | awk '$1=="orders.dlq"{print $2}')
[ "${DLQ:-0}" -eq 0 ] && ok "dead-letter queue is empty" || bad "dead-letter queue has $DLQ messages"
ls orders-*.dump >/dev/null 2>&1 && ok "backup file exists" || bad "no backup file"
✓ only the gateway publishes ports ... ✓ dead-letter queue is empty ✗ no backup file
The port check counts IPv4 and IPv6 separately (8443 and 8080 may each appear once); adjust the threshold to your docker compose ps output. The RabbitMQ management port binds 127.0.0.1 only and isn't counted.
Lab 8: end-to-end smoke test + 7 incident drills + cleanup (about 6 minutes)
#!/usr/bin/env bash
set -euo pipefail
B=${1:-https://localhost:8443}; C="curl -skf"
KEY=$(cat /proc/sys/kernel/random/uuid)
ID=$($C -X POST $B/api/orders -H 'Content-Type: application/json' -H "Idempotency-Key: $KEY" -d '{"item":"smoke","qty":1}' | jq -r .id)
echo "order $ID created"
for i in $(seq 1 20); do
S=$($C $B/api/orders/$ID | jq -r .status); [ "$S" = processed ] && break; sleep 0.5
done
[ "$S" = processed ] && echo "✓ async processing ok" || { echo "✗ order still $S"; exit 1; }
DUP=$($C -X POST $B/api/orders -H 'Content-Type: application/json' -H "Idempotency-Key: $KEY" -d '{"item":"smoke","qty":1}' | jq -r .created)
[ "$DUP" = false ] && echo "✓ idempotency ok"
echo smoke > /tmp/smoke.txt; U=$($C -F file=@/tmp/smoke.txt $B/api/files | jq -r .url)
[ "$($C "$U")" = smoke ] && echo "✓ blob + SAS ok"
$C $B/api/stats | jq -c
chmod +x smoke.sh && ./smoke.sh
order 27 created
✓ async processing ok
✓ idempotency ok
✓ blob + SAS ok
{"cache":"miss","items":…,"orders":…,"processed":…,"served_by":"…","version":"1.0"}
It also runs against Azure (./smoke.sh https://$FQDN): the hour 5 pipeline's post-deployment smoke test and the acceptance step after a Module 7 DR failover.
docker compose --profile jobs down # keep the data volumes # docker compose --profile jobs down -v # also delete database, queue and Blob data crontab -l | grep -v orders-report | crontab - # remove the Module 4 cron job
Incident drills: read the evidence, find the root cause
The 7 scenarios map to Modules 2–7. Decide first, then check the suggested fix.
Case 1: the review checklist became a "box-ticking ritual"
Problem: A team's quarterly review was always green, until a database failure revealed "backups are restorable" had never been drilled; it was ticked because "the portal shows automatic backups". Approach: every item needs evidence (drill records, command output, monitoring screenshots) or counts as not met; key drills run as scheduled jobs. Limitation: evidence takes time; start a week before the review.
Case 2: nobody could answer "who do we call when the DLQ has messages"
Problem: The dead-letter alert went to a mailbox nobody read; three days later, support found many orders stuck in pending. Approach: Every alert needs an owner, a runbook link and an escalation path; the checklist gains an "alert actionability" item. Limitation: Too many alerts cause fatigue; alert only on symptoms needing a human (DLQ > 0, 5xx ratio, restart loops, replication lag).
Case 3: turning the six scenarios into a team template
Approach: A company turned the structure of orders (one image with many processes, a migration job, separate probes, idempotency keys, DLQ, SAS, zone-redundancy parameters) into a repository template and IaC modules, so new services meet most of the checklist by default and reviews focus on differences. Limitation: Someone must keep the template current (base images, dependencies, new cloud options), or it becomes "outdated best practice".
Interactive troubleshooting tree: entry / data layer / queue / migration / storage / HA
Common issues during reviews and drills
smoke.sh hangs on "order still pending"
The worker isn't running, or on Azure is cold-starting from 0 replicas (KEDA polls every 30 seconds). Locally: docker compose ps worker; Azure: az containerapp replica list -n ca-orders-worker; lengthen the wait loop if needed.
The SAS check in smoke.sh fails (downloaded content differs)
Locally: BLOB_PUBLIC_BASE and gateway /blob/ forwarding (Modules 3, 6); Azure: the identity's Storage Blob Data Contributor role and AZURE_CLIENT_ID.
Database data is still there after docker compose down
Expected: down keeps named volumes. Use down -v once you're sure; in production, back up before deleting data volumes.
1. List every service publishing host ports, with its ports (exposure surface).
docker compose ps --format json | jq -r 'select(.Publishers != null) | .Service + " " + ([.Publishers[] | select(.PublishedPort>0) | "\(.URL):\(.PublishedPort)"] | join(","))' | sort -u2. Show every container's restart count at once (find restart loops).
docker ps -a --filter label=com.docker.compose.project=orders -q | xargs docker inspect --format '{{.Name}} restarts={{.RestartCount}} exit={{.State.ExitCode}}'A review finds three gaps: ① the B1ms database has no HA; ② there is no outbox; ③ logs carry no request ID through to the worker. You have one week. How do you prioritize?
Rank by impact × likelihood × cost to fix: ① no database HA takes the whole site down and the fix is a tier upgrade plus HA (mostly cost), so it's first; ② without an outbox, orders stick in pending while the queue is down: ship a cheap "pending timeout sweep + republish" now, the outbox next iteration; ③ request ID propagation speeds troubleshooting but doesn't hit users directly, so it's last. Put all three on the risk list; record accepted risks in an ADR.
Verified teaching videos
Video storyboard (about 75 seconds)
Visual: each orders component flashes red in turn with a "what users see" bubble: slower, orders fail, whole site down.
Narration: Failure mode analysis: fail each component in turn and record the user impact.
Visual: five bars (reliability, security, cost, operations, performance) rise as boxes are ticked; a "fix first" flag pops up on the shortest.
Narration: Score the five pillars; close reliability and security gaps first.
Visual: an on-call engineer reads a log excerpt and clicks "Root cause: connection budget exceeded"; fix steps appear. Pull back: the next lesson's toolbox opens: tcpdump, k6, Testcontainers.
Narration: Diagnose root causes from evidence; next hour, we troubleshoot and tune this system in depth.
Command cheat sheet
Compose lifecycle
docker compose up -d --build | Build and start |
docker compose up -d --scale api=4 --no-recreate | Scale replicas |
docker compose ps -a --format 'table {{.Service}}\t{{.Status}}' | Status (incl. exited one-off services) |
docker compose logs -f --no-log-prefix api | Follow logs |
docker compose run --rm report | Run a one-off / profile service |
docker compose stop -t 30 worker | Graceful stop |
docker compose pause postgres | Freeze processes (drill) |
docker compose config -q | Validate compose.yaml and variables |
docker compose --profile jobs down [-v] | Stop and remove (-v deletes data volumes too) |
PostgreSQL
docker compose exec postgres psql -U orders | Interactive SQL |
… -c 'TABLE schema_migrations' | Applied migrations |
… -c "SELECT count(*) FROM pg_stat_activity WHERE datname='orders'" | Connection count |
docker compose exec -T postgres pg_dump -U orders -Fc orders > o.dump | Backup |
docker compose exec -T postgres pg_restore -U orders -d NEWDB --no-owner < o.dump | Restore |
SET lock_timeout='5s' | Stop migrations waiting long on locks |
Redis / RabbitMQ
docker compose exec redis redis-cli --scan --pattern 'order:*' | List cache keys |
docker compose exec redis redis-cli TTL stats / INFO stats | TTL, hit ratio |
rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers | Queue status |
rabbitmq-diagnostics -q ping | Health check |
ssh -L 15672:localhost:15672 VM | Remote management UI |
Gateway / TLS
docker compose exec gateway nginx -t | Check configuration |
docker compose exec gateway nginx -s reload | Graceful reload |
curl -skI https://localhost:8443/ | Response headers |
openssl s_client -connect H:443 -servername H </dev/null | openssl x509 -noout -dates | Certificate validity |
seq 50 | xargs -P25 -I{} curl -sk -o /dev/null -w '%{http_code}\n' URL | sort | uniq -c | Quick concurrency test |
Azure data and messaging
az postgres flexible-server create --version 17 --tier Burstable --sku-name Standard_B1ms | Managed PostgreSQL |
az postgres flexible-server restore -n NEW --source-server SRC --restore-time T | Point-in-time restore |
az redisenterprise create --sku Balanced_B0 --clustering-policy EnterpriseCluster | Managed Redis (port 10000) |
az servicebus queue create --max-delivery-count 5 | Queue + automatic dead-lettering |
az storage account create --allow-shared-key-access false --allow-blob-public-access false | Entra-only access |
Azure Container Apps
az containerapp create … --ingress internal | Internal API |
… --scale-rule-type azure-servicebus --scale-rule-identity ID | Scale on queue length (managed identity) |
az containerapp job create --trigger-type Manual|Schedule|Event | Migration / scheduled / event jobs |
az containerapp job start -n J | Trigger manually |
az containerapp job execution show -n J --job-execution-name E | Execution status |
az containerapp logs show -n APP --follow | Log stream |
HA and DR (Azure, examples)
az containerapp env create … --infrastructure-subnet-resource-id S --zone-redundant | Zone-redundant environment (creation only) |
az containerapp update … --min-replicas 2 | Needed to spread across zones |
az acr replication create -r ACR -l REGION | ACR geo-replication (Premium) |
az postgres flexible-server update … --zonal-resiliency Enabled --standby-zone 2 | Zone-redundant HA (not Burstable) |
az postgres flexible-server restart … --failover Planned|Forced | HA failover drill |
az postgres flexible-server replica create / promote | Cross-region read replica, promotion |
az afd origin create … --priority 1|2 | Front Door primary/secondary origins |
HA and DR (AWS equivalents, examples)
aws ecs update-service … --availability-zone-rebalancing ENABLED | ECS Availability Zone rebalancing |
aws ecr put-replication-configuration … | ECR cross-region / cross-account replication |
aws ecr describe-image-replication-status … | Replication status |
aws rds modify-db-instance … --multi-az --apply-immediately | RDS Multi-AZ DB instance |
aws rds reboot-db-instance … --force-failover | Failover drill |
| Route 53 failover records (PRIMARY / SECONDARY + health checks) | DNS-level primary/standby |
Design decisions at a glance
| Need | Pattern | Module |
|---|---|---|
| Think it through before building | Non-functional requirements → data flow → ADR → failure analysis | 1 |
| Read-heavy, high latency | Cache-aside + TTL + invalidate on write + degradation | 2 |
| Clients retry | Idempotency key + unique constraint | 2 |
| Several backends, one TLS endpoint, rate limiting | Gateway / reverse proxy | 3 |
| Slow operations, absorbing spikes | Queue + worker + dead-lettering + idempotent consumers | 4 |
| Periodic tasks | Re-entrant one-off process + external scheduler (cron / ACA Schedule job) | 4 |
| Schema changes | Separate migration job + expand/contract + lock_timeout | 5 |
| User files | Object storage + short-lived read-only SAS (user delegation) | 6 |
| Zone outage barely noticed | Zone-redundant compute (≥ 2 replicas) + zone-redundant HA database + ZRS storage | 7 |
| Recoverable region outage | Image geo-replication + cross-region read replica + global-entry priority routing + runbook and drills | 7 |
| Accidental deletion / data corruption | PITR, geo-redundant backups, regular restore drills | 5, 7 |
Quick troubleshooting table
| Symptom | Most likely cause | Look at first |
|---|---|---|
too many clients already | Connection budget exceeded | pg_stat_activity grouped by client |
| Gateway 502 | Upstream not ready / static DNS caching old IP | docker compose ps api, nginx resolver |
| Lots of 429s | Rate-limit threshold / real client IP not restored | remote in the gateway's JSON log |
| Orders stuck in pending | Worker down / publish failed / message in the DLQ | list_queues, worker logs |
| Worker exit code 137 | Signal not reaching Python / processing exceeds the grace period | Entrypoint uses exec? stop_grace_period |
| Old version reports "column does not exist" mid-release | Contracted too early | TABLE schema_migrations |
| Blob 403 | SAS expired/tampered, no data-plane role, shared key disabled | Error code (AuthenticationFailed / AuthorizationPermissionMismatch / KeyBasedAuthenticationNotPermitted) |
manifest unknown pulling in the secondary region | Geo-replication unfinished | az acr replication list, webhook |
| App keeps returning 500 after HA failover | Pool holds stale connections, no retry | App logs, readiness probe code |
Final lab: deploy the orders system to Azure + final quiz
- ca-orders-web (external ingress, managed HTTPS) → ca-orders-api (internal ingress) → PostgreSQL flexible server 17 / Azure Managed Redis
- api → Service Bus queue orders → ca-orders-worker (KEDA, 0–4 replicas)
- job-migrate (Manual), job-report (Schedule, 06:15 UTC)
- Blob Storage (shared key disabled); Key Vault holds database and Redis connection strings; one user-assigned managed identity, id-orders, for all access
- This is a single-region, non-zone-redundant deployment (to save cost); Module 7's read-only checks list its single points of failure, and extension challenge ⑤ hardens it.
azure/deploy.sh defaults to resource group rg-docker-hour6 and writes resource names to ~/hour6.env (overwritten each run), leaving Hours 3–5 resource groups and variable files alone.az login && az account show --query name -o tsv LOC=canadacentral RG=rg-docker-hour6 bash azure/deploy.sh 2>&1 | tee deploy.log source <(tr ' ' '\n' < ~/hour6.env | grep '=' | sed 's/^/export /')
Waiting for the migration to finish… Succeeded Done: https://ca-orders-web.<random>.canadacentral.azurecontainerapps.io
The script is the project's azure/deploy.sh (fragments explained under "Lab → Cloud equivalent" in Modules 2–6). If migration is not Succeeded: az containerapp job execution list -g $RG -n job-migrate -o table and check the log table ContainerAppConsoleLogs_CL.
./smoke.sh https://$FQDN
order 1 created
...
✓ blob + SAS ok
{"cache":"miss",…,"version":"1.0"}
The first order can take 30–60 seconds while the worker scales from 0 replicas (KEDA polls every 30 seconds); lengthen the script's wait loop if needed.
for i in $(seq 1 60); do curl -sk -X POST https://$FQDN/api/orders -H 'Content-Type: application/json' -d '{"item":"load","qty":1}' -o /dev/null & done; wait
for i in 1 2 3 4 5 6; do az containerapp replica list -g $RG -n ca-orders-worker --query "length(@)" -o tsv; sleep 20; done
0 2 4 4 1 0
API_FQDN=$(az containerapp show -g $RG -n ca-orders-api --query properties.configuration.ingress.fqdn -o tsv); echo $API_FQDN
curl -s -o /dev/null -w 'api from internet: %{http_code}\n' --max-time 5 https://$API_FQDN || true
az storage account show -g $RG -n $ST --query "{sharedKey:allowSharedKeyAccess, public:allowBlobPublicAccess}" -o table
az containerapp show -g $RG -n ca-orders-api --query "properties.configuration.secrets[].{name:name,kv:keyVaultUrl}" -o table
ca-orders-api.internal.<random>.canadacentral.azurecontainerapps.io api from internet: 000 (internal ingress: the FQDN contains .internal. and only resolves inside the environment) SharedKey Public ----------- -------- False False Name Kv ------------ ---------------------------------------------------- database-url https://kv-orders-xxxxxx.vault.azure.net/secrets/database-url redis-url https://kv-orders-xxxxxx.vault.azure.net/secrets/redis-url
az group delete -n $RG --yes # about 10–20 minutes az keyvault purge -n $KV # Key Vault soft-deletes by default (kept 90 days); without a purge the same name cannot be reused crontab -l | grep -v orders-report | crontab - rm -f ~/hour6.env
Acceptance checklist
Open-ended self-check (answer first, then expand the reference)
1. In three sentences, explain to a new colleague why the orders API can be scaled out freely but the database cannot.
The API is stateless (sessions in Redis, files in Blob, data in PostgreSQL), so any replica serves any request. The database is the source of truth: each connection is a process, connections are capped, and writes go only to the primary. So work out the connection budget before scaling the API; the database scales via bigger SKUs, read replicas and a pooling proxy.
2. How does orders (hardened per Module 7) behave in a zone outage and a region outage?
Zone outage: ACA shifts traffic to other zones (about 30 seconds) and PostgreSQL zone-redundant HA fails over automatically (usually 60–120 seconds, RPO 0); users see at most a brief error and retry. Region outage: per the runbook, on-call declares a disaster, force-promotes the cross-region replica (1–3 minutes, losing data within the replication lag), scales up the secondary region, and Front Door probes shift traffic; RTO is minutes to tens of minutes.
3. With only one improvement to reduce orders' business risk, what would you pick, and why?
No single right answer; justify it with failure analysis. Common picks: database zone-redundant HA (removes the site-wide single point), an outbox (no silent "placed but never processed" orders), or regular restore drills (proves backups work).
redis-entraid + access policy assignment) with --access-keys-auth Disabled. ③ Implement a transactional outbox. ④ Alert on DLQ depth, 5xx, worker restarts and database replication lag. ⑤ Harden per Module 7: VNet + zone-redundant environment, API min 2 replicas, PostgreSQL General Purpose + zone-redundant HA, and a --failover Forced drill in staging.Final quiz (12 questions covering all modules)
Sources & version notes
Versions and prerequisites
| Component | Version used / verified in this hour |
|---|---|
| Docker Engine / Compose | 29.x / v5.x (verified in Hours 1–5) |
| Python dependencies | flask 3.1, gunicorn 23, psycopg 3.2 + psycopg-pool 3.2, redis 5, pika 1.3, azure-storage-blob 12 (tested 12.31.1), azure-identity 1, azure-servicebus 7 |
| Images | python:3.13-slim, postgres:17, redis:7-alpine, rabbitmq:4-management, nginx:1.29-alpine, mcr.microsoft.com/azure-storage/azurite (Azurite 3.37.0 for local tests) |
| Azure CLI | 2.75+; Module 7 ACR commands assume 2.86+ (--region-endpoint-enabled renamed --global-endpoint-routing); containerapp extension (--scale-rule-identity is a preview parameter); redisenterprise extension |
| PostgreSQL flexible server | 17 here; the CLI lists major versions 12–19 (go by the portal); B1ms allows 35 user connections; Burstable has no built-in PgBouncer, HA or read replicas; the HA parameter is --zonal-resiliency Enabled (older form --high-availability) |
| Azure Managed Redis | Port 10000 (TLS); new instances default to Entra ID on, access keys off; SKUs such as Balanced_B0; clustering policy defaults to OSSCluster |
| Container Apps zone redundancy | Set at environment creation, immutable; needs a VNet (workload profiles ≥ /27, Consumption-only ≥ /23); min replicas ≥ 2; no extra charge (docs updated 2026-11) |
| ACR geo-replication | Premium; active-active, eventually consistent; geo-replicas are always zone-redundant; storage billed per replica; a home-region outage stops the control plane and ACR Tasks |
| Front Door | Standard / Premium; origin priority 1–5; (classic) retires 2027-03-31 |
| AWS | ECS Availability Zone rebalancing (enabled for eligible services since 2025-09-05); ECR replication (up to 25 destinations, only images pushed after setup, most within 30 minutes); RDS Multi-AZ DB instance / cluster; Aurora (6 storage copies across 3 AZs, failover usually < 60 seconds) |
Official documentation
- The Twelve-Factor App · Azure Well-Architected Framework
- Docker Compose: control startup order (service_completed_successfully) · Compose profiles
- Cache-Aside pattern · PostgreSQL flexible server limits
- Create Azure Managed Redis · Python + Entra ID · az redisenterprise
- nginx limit_req · nginx resolver
- RabbitMQ confirms · Dead letter exchanges
- ACA scale rules · ACA jobs · az containerapp job
- Azurite · User delegation SAS (Python)
- PostgreSQL advisory locks · Parallel Change
- Module 7: ACA reliability · Zone-redundant environments · ACR geo-replication · PostgreSQL reliability · az postgres flexible-server · Front Door routing methods
- Module 7 (AWS): ECR replication · ECS Availability Zone rebalancing · RDS Multi-AZ · Multi-AZ DB clusters · Aurora high availability
Video verification notes
- The titles and channels of these videos were verified on 2026-11-17 through the YouTube oEmbed endpoint: Fireship "100+ Docker Concepts you Need to Know", "Redis in 100 Seconds", "NGINX Explained in 100 Seconds", "RabbitMQ in 100 Seconds"; Microsoft Reactor "Kubernetes-Free Microservices: The Azure Container Apps Advantage"; ByteMonk "The Ultimate Guide to Disaster Recovery: RTO, RPO, & Failover!". Durations and publication dates are carried over from the 2026-11-15 record; the ByteMonk video's duration was not verified.
- No verifiable, high-quality video was found covering expand/contract migrations, user delegation SAS or current ACA zone-redundancy practice; official documentation and storyboard scripts are used instead.
Audio notes
The "Audio" tab reads scripts aloud via the browser's Web Speech API (en-US); nothing is uploaded. Each term is pronounced, then explained. Quality depends on installed voices; without an English voice, use any TTS tool.
Relationship to the previous Hour 6 (module numbering changes)
| Previous (7 modules) | New (8 modules) |
|---|---|
| #m1 Architecture design method (00–05) | #m1 (00–05, unchanged) |
| #m2 Three-tier web (05–17) | #m2 (05–13) |
| #m3 Gateway and HTTPS (17–27) | #m3 (13–20) |
| #m4 Async and scheduled jobs (27–37) | #m4 (20–28) |
| #m5 Migrations and releases (37–45) | #m5 (28–35) |
| #m6 Files and object storage (45–53) | #m6 (35–42) |
| — | #m7 High availability and disaster recovery (42–51, new) |
| #m7 Architecture review (53–60) | #m8 Architecture review and incident drill (51–60, expanded to 10 tabs) |
Test notes and known limitations
- Tested locally: migrations (incl. concurrency and contract), idempotent order creation, cache-aside, Redis-failure degradation, readiness 503 within 2 seconds with the database frozen, idempotent worker, retry → dead-letter logic (simulated channel), Azurite upload + SAS + 403 on tampering, daily report job, nginx redirect / 429 rate limit / 413 / Blob proxying, compose.yaml validation. Test environment: Python 3.13, PostgreSQL 16, Redis, Azurite 3.37, nginx 1.24 (with
http2 onremoved). - Not run in this environment: Docker image builds and a full Compose run (no Docker Hub access), real RabbitMQ, and all Azure and AWS commands (including every Module 7 command, the local RTO experiment and the Module 8 review script). They follow the official docs and CLI references; expected outputs are examples.
- Issues found and fixed in testing: wrong Azurite dev key (AuthorizationFailure); the readiness probe hung 30 seconds on a pooled connection; az CLI could parse
--args -mas an option (switched toorders-*entrypoint scripts); B1ms connection budget too small (pool size 2, worker cap 4). - English edition: page text, code comments and sample strings are translated, but the embedded/downloadable
orders-bootstrap-part6.shmatches the Chinese edition, so its comments and echo messages stay in Chinese (same code).