Docker Hour 6: Production Applications and Architecture Design

One "order system" (orders) ties together six common production scenarios: architecture decisions, code, Compose and Azure managed services, zone redundancy, multi-region disaster recovery and a full architecture review
Engine 29 · Compose v5PostgreSQL 17 · Redis 7 · RabbitMQ 4 · nginx 1.29 · AzuriteACA · PG Flexible Server · Managed Redis · Service Bus · BlobVerified against official docs · 2026-11-17
Learning objectives
  • 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

#TimeModuleCore contentAnimation / interactionLab
0Before classSetup: generate the sample projectOne script generates the orders project (30 files) and pulls images—Environment check
100–05Architecture design method12-Factor, reference architecture, ADRs, trade-off tables, one image, several process typesFrom requirements to architecture (four design mistakes) + 12-Factor self-checkerStart the whole system
205–13① Three-tier web ⭐Connection pools and budget, cache-aside and degradation, liveness/readiness probes, idempotency keysThe journey of one request (six cases) + connection budget calculatorIdempotency, caching, scaling replicas, graceful degradation
313–20② Gateway and HTTPSTLS termination, 301, rate limiting 429, 413, request IDs, resolver 127.0.0.11; ACA ingress / Front DoorA request through the gateway (six outcomes) + gateway routing simulatorCertificates, rate limiting, body size limit, DNS trap
420–28③ Async and scheduled jobsack, retries, dead-lettering, idempotent consumers, graceful shutdown, cron; Service Bus + KEDA + ACA JobsThe life of a message (six endings) + live queue simulatorBacklog, poison messages, graceful shutdown, daily report
528–35④ Database migrations and releasesOne-off migration job, advisory locks, expand/contract, lock_timeout, backup-restore drill, PITRA release with a schema change (six paths)Concurrent migrations, contract, backup → restore
635–42⑤ File uploads and object storageAzurite, short-lived read-only SAS, user delegation SAS, disabling Shared Key, direct uploadUpload and download (seven cases)Upload, SAS, tampering 403, sharing across replicas
742–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 drillsFailure and failover simulator (Azure / AWS × six failures) + RTO/RPO calculatorTabletop drill: write a DR runbook for orders
851–60Architecture review and incident drillFailure mode analysis, Well-Architected review scoring, 7 incident drills, interactive troubleshooting tree, preview of hour 7Incident postmortem timeline + review scorerEnd-to-end smoke test, incident drills, cleanup
—After classCheat sheet · Final labDeploy to Azure with azure/deploy.sh → smoke test → observe scaling → verify security → clean upFinal quiz (12 questions)Final lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / objectsLab
Architecture method (12-Factor, ADRs, failure analysis)✓·····✓✓docs/adr/*.md, compose.yaml anchorsM1 / M8
Connection pools, caching, probes, idempotency·✓·✓··✓✓pg_stat_activity, redis-cli, /readyzM2
Gateway, TLS, rate limiting··✓··✓✓✓nginx -t, openssl s_client, limit_reqM3
Queues, dead-lettering, graceful shutdown, scheduled jobs✓··✓···✓rabbitmqctl list_queues, KEDA, az containerapp jobM4
Migrations, expand/contract, backup and restore✓···✓·✓✓pg_advisory_lock, pg_dump -Fc, PITRM5
Object storage and SAS··✓··✓✓✓generate_blob_sas, --allow-shared-key-access falseM6
Zone redundancy and multi-region DR··✓·✓·✓✓--zone-redundant, az acr replication, --zonal-resiliency, replica promoteM7
Reviews, drills and smoke tests✓·····✓✓smoke.sh, Well-Architected checklistM8 / Final lab

What this lesson leaves out (and where to learn it)

TopicWhy not hereWhere to learn it
Writing multi-stage, non-root Dockerfiles with health checksHour 2; used as-is hereHour 2
Image CI, signing, promotion by digest, ACA traffic splitting / ECS blue/green rollbackRelease pipeline; here we only plug in the migration jobHour 5, Module 7
Basic deployment with ECS / ALB / ECRAWS appears here only as an architectural comparisonHour 4
Metrics, alert rules, SLOs and dashboardsHere we only list what to alert onPrometheus & Grafana in 8 + 1 Hours (Chinese)
Managing the whole infrastructure (including multi-region) with TerraformInfrastructure as code; here concepts use the CLITerraform in 8 Hours (Chinese)
Deep troubleshooting, load testing and performance tuning, chaos experimentsNeeds its own lessonHour 7

How to use this course

10 tabs per module
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".
Progress
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).
English audio
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.
How this relates to the first five hoursDockerfile practices: Hour 2; ACR, Container Apps and Key Vault references: Hour 3; ECR and ECS: Hour 4; image CI, signing, release and rollback: Hour 5. This lesson focuses on application architecture: the parts, how they work together, what happens when each fails, and surviving zone and region failures.
Cost and testing notesModules 1–6 and 8 run on one Ubuntu VM with Compose at no cloud cost; Module 7 is design and tabletop drills, its cloud commands were not run in a real environment, and outputs are examples. The final lab creates paid resources (PostgreSQL, Managed Redis, Service Bus); clean up right after. "Tested" outputs come from local tests (see Sources & version notes).

Module 0 · Setup: generate the sample project (before class)

One script generates the complete orders project; the core code has been tested locally
Before class ≈ 5 minJust one Linux VM
Prerequisites
  • 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.

Testing notesThe sample code was actually run and tested on Python 3.13 + PostgreSQL 16 + Redis + Azurite 3.37 + nginx: migrations (including 3 concurrent migration processes), idempotent order creation, cache hits / degradation when Redis fails, the readiness probe while the database is frozen, idempotent Worker processing, retry → dead-letter logic (simulated channel), SAS upload/download and tampering, rate limiting 429, and the daily report job. The RabbitMQ and Azure / AWS parts were written from the official docs and were not executed step by step in a real environment.

Module 1 · Architecture design method

00:00 – 05:00 · First decide what the system is made of and why, then write compose.yaml
5 minUsed all hour★★★★★
Learning objectives
  • 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".
Prerequisites: Hours 1–3 (Compose, Dockerfile, Container Apps basics). Importance: ★★★★★ (all later modules use this method)

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)

PrincipleMeaningIn this project
III ConfigConfig lives in environment variables, not in the imageorders/config.py reads only os.environ; one image runs locally and on Azure
IV Backing servicesDatabase, cache and queue are replaceable attached resourcesChange the URL to switch from the Postgres container to Azure PostgreSQL
VI Stateless processesProcesses keep no state locallySessions and cache in Redis; files in Blob (Module 6), so the API scales out freely
VIII ConcurrencyScale via "process type × count"One image, four process types: api, worker, migrate, report
IX DisposabilityFast startup, graceful shutdowngunicorn --graceful-timeout; on SIGTERM the worker finishes its current message, then exits
XI Logs / XII Admin processesLogs to stdout; one-off tasks like migrations use the same imageJSON logs; orders-migrate as a one-off service / ACA Job

How: a lightweight design process

  1. Write the non-functional requirements: availability (e.g. 99.9%), latency (P95 < 300 ms), no data loss, peak traffic, compliance.
  2. Draw the data flow: separate the synchronous path (user waits) from the asynchronous one (user does not).
  3. Choose each part and record an ADR: self-host or managed? Consistency needs? How does it degrade on failure?
  4. 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

PartNeed it solvesWhat users see if it failsOperating costAlternative without it
Redis cacheHot-read latency, database read loadSlower (falls back to the database)Low (managed)Database indexes / read replicas
RabbitMQ / Service BusSlow work no longer blocks ordering; smooths peaksOrdering fails or stays pendingMediumSynchronous processing (fine at low volume)
nginx gatewayUnified TLS, rate limiting, routingWhole site down (single point)LowPlatform ingress (ACA ingress / ALB)
Object storageUser files shared across replicasUploads/downloads fail; ordering worksLowNone (not the container filesystem)
Common misconceptions① "A more complete architecture is more professional" - every part adds a failure point and operational burden; a part with no requirement is a liability. ② "Go Kubernetes first so we can scale later" - scalability comes from stateless processes + externalized state, not the orchestrator. ③ "ADRs are documentation overhead" - one page, five minutes, and a year later "why a queue?" has an answer. ④ "12-Factor is outdated" - external config, statelessness and one-off admin processes are exactly what container platforms (ACA, ECS, K8s) assume.
BrowserSPA gatewaynginx · TLS · limit api × 2Flask + gunicorn rediscache postgressource of truth rabbitmqorders / dlq worker × 2async processing azurite (Blob)files / reports migrateone-off reportscheduled job
Figure 1-1 Order system reference architecture (local Compose). Solid = requests/messages, dashed = files and scheduled jobs
Local (Compose)Azure managed replacementWhy switch
gateway (nginx)ACA ingress (managed TLS) + optional Front Door / Application Gateway (WAF)Auto certificate renewal, global load balancing, WAF
postgres containerAzure Database for PostgreSQL flexible serverAuto backups, PITR, high availability, patching
redis containerAzure Managed Redis (Azure Cache for Redis retires on 2028-09-30)High availability, Entra ID authentication
rabbitmq containerAzure Service BusDead-lettering, sessions, managed identity; native KEDA support
azuriteAzure Blob StorageSame SDK, same code
migrate / report servicesContainer Apps Jobs (Manual / Schedule)Execution history, retries, timeouts

Design flow: from requirements to compose.yaml

① Requirements99.9% · P95 300ms ② Data flowsplit sync / async ③ Parts + ADRself-host/managed/none ④ Failure modeswhat if X dies? ⑤ compose.yaml→ Azure / AWS Failure analysis finds an unacceptable impact → back to data flow / part choice
Figure 1-2 Design is iterative: failure analysis (Module 8) feeds back into part choices

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).

Ready.
$ cat docs/requirements.md

12-Factor self-check

Tick what your service satisfies to see its scale-out/container readiness and next steps.

Commands used in this module

CommandPurposeDesign link
docker compose config -qValidate compose.yaml and variables (non-zero exit on error)Expands anchors and ${VAR:?} required variables
docker compose config --servicesList all services (including profiles)Check the parts list against the diagram
docker compose up -d --buildBuild and start the whole systemapi / worker start only after migrate succeeds
docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'Status, including exited one-off servicesOne-off processes (XII) should exit 0
docker compose run --rm reportRun the scheduled job from its profileSame image, different process type (VIII)
docker compose exec api env | grep -E 'DATABASE|REDIS|QUEUE'See the config the process receivedConfig 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)

Start the whole system
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).

Check dependency order and the one-off task
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 0
Open the web page

Open 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.

Check against 12-Factor: confirm the API image has no environment-specific config.
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.

Command-line exercises
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(" "))"'
Scenario analysis
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

▶
100+ Docker Concepts you Need to Know — Fireship
8:28 · 2024-03-12 · English · container and Compose concepts

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).

Shot 1 · 0–20s
Visual: a whiteboard reads "99.9%, P95 300 ms, peak 200 orders/s", beside an empty diagram.
Narration: architecture starts from requirements, not tools.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
Visual: one orders image splits into four processes: api, worker, migrate, report.
Narration: one image, four process types, all config from environment variables.
or score ≥ 70% on the "Quiz" tab

Module 2 · Scenario ①: Three-tier web app (SPA + API + PostgreSQL + Redis)

05:00 – 13:00 · The most common production shape: a stateless API scales out; all state lives in the data tier
8 minCore scenario ⭐★★★★★
Learning objectives
  • 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.
Prerequisites: Module 1; hour 2 Dockerfile health checks. Importance: ★★★★★ (Modules 4, 7 and 8 build on it)

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

DesignProblemApproach
Connection poolA new connection per request costs TCP + TLS + auth (a few to tens of ms), and each PostgreSQL connection is a backend process using memorypsycopg_pool.ConnectionPool(max_size=5): reuse connections in-process. Total = pool limit × gunicorn processes × replicas, kept below the database's available connections
Cache-asideHot reads overwhelm the databaseCheck 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 cacheA Redis failure takes the site downCache calls catch RedisError (0.5 s timeout) and fall back to the database: the cache affects performance only, never correctness
Liveness vs readinessDuring 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 keyClient retries after a timeout → duplicate orderThe 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 AcceptedProcessing takes timeReturn 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).

Common misconceptions① "The cache guarantees consistency" — cache-aside has a short stale window; strongly consistent reads must bypass it. ② "The more a readiness probe checks, the better" — then a non-critical failure (such as Blob) pulls the whole site from traffic; check only essential dependencies. ③ "A bigger pool is faster" — each PostgreSQL connection is a process; too many cause context switching and memory pressure. ④ "The server generates the idempotency key" — the client generates it per business operation and reuses it on retry.
BrowserGET /api/orders/7 gatewayDNS round-robin api-1 (pool ≤5) api-2 (pool ≤5) Redis① GET order:7 PostgreSQL② queried only on a miss ③ SETEXTTL 60s
Figure 2-1 Cache-aside read path: ① check the cache → ② on a miss, query the database → ③ write back to the cache
POST /api/ordersIdempotency-Key: k1 INSERT … ON CONFLICT(idempotency_key) DO NOTHING New row → publish → 202 Exists → original → 200 DEL statsinvalidate on write
Figure 2-2 Idempotent write path: the unique constraint turns a duplicate submission into a read of the first result

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).

Ready.
$ B=https://localhost:8443; C="curl -sk"

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

CommandDescription
docker compose up -d --scale api=3Scale 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 statsRemaining TTL (seconds); -2 = no such key
docker compose exec redis redis-cli INFO stats | grep keyspaceHit/miss counters keyspace_hits / keyspace_misses
docker compose stop redis / start redisRehearse a cache failure
docker compose pause postgresFreeze the database (simulates "unresponsive"; closer to a real timeout than stop)

Lab 2: idempotency, caching, scaling and graceful degradation (about 6 minutes)

Idempotent order creation
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
400
Cache-aside
sleep 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.

Scale out and watch connections
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.

Failure drill: Redis down → degrade; database unresponsive → readiness fails
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"
PointNotes (verified 2026-11)
PostgreSQL versionsFlexible Server supports 14–18 (CLI already lists 19; 13 and older in extended support)
Connection limitStandard_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 RedisPort 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 RedisBasic/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.

Command-line exercises
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)}'
Scenario analysis
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

▶
Redis in 100 Seconds — Fireship
2:26 · 2021-07-08 · English · Redis data structures and uses

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the "Quiz" tab

Module 3 · Scenario ②: Gateway and HTTPS

13:00 – 20:00 · One entry point: TLS, routing, rate limiting, security headers, request tracing
7 min★★★★☆
Learning objectives
  • 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.11 fixes it.
  • Azure equivalents: ACA managed certificates, Front Door / Application Gateway + WAF (Module 7 uses Front Door for multi-region failover).
Prerequisites: Module 2; Docker networking and the embedded DNS from hour 1. Importance: ★★★★☆

What: what a gateway does

Responsibilitynginx configuration in this project
TLS terminationlisten 443 ssl, TLS 1.2/1.3 only; plain HTTP to backends internally
HTTP → HTTPSPort 80 gets a 301 redirect; HSTS header added
Routing/ → static SPA; /api/ → api service; /blob/ → azurite (local demo only)
Protecting the backendsRate 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

nginxCaddyTraefik
CertificatesManual / certbotAutomatic HTTPS (Let's Encrypt)Automatic HTTPS
ConfigurationFiles, fullest feature setMinimal CaddyfileAuto-discovery from container labels
Best forFine control, performanceSmall single-host sitesMany 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).

Common misconceptions① "Internal HTTP needs a certificate per service" — terminating TLS at the entry of one Docker network / ACA environment is reasonable; add end-to-end TLS across network boundaries or for compliance (ACA offers peer-to-peer encryption). ② "App-level rate limiting is enough" — a saturated app cannot run it; the entry point is the first gate. ③ "X-Forwarded-For is always the real IP" — clients can forge it; trust only the part added by known proxies.
ClientHTTPS :8443 gateway (nginx) ① terminate TLS (tls.crt/.key)② limit_req 10r/s → 429③ client_max_body_size → 413④ add X-Request-ID⑤ upstream via 127.0.0.11⑥ JSON access log → stdout / → SPA static /api/ → api:8000 /blob/ → azurite Internal networkno ports, unreachable HTTP :8080 → 301
Figure 3-1 Gateway processing order and routing

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).

Ready.
$ curl -sk -w '%{http_code}\n' https://localhost:8443/api/stats

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

CommandDescription
docker compose exec gateway nginx -tCheck config syntax (after every change)
docker compose exec gateway nginx -s reloadReload 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/xVerify the 301 redirect
openssl s_client -connect localhost:8443 -servername localhost </dev/null 2>/dev/null | openssl x509 -noout -subject -datesCertificate 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)

Redirect, certificate and security headers
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
Rate limiting: 50 concurrent requests
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.

Body limit and request ID
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…"}
DNS caching trap demo (optional)
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

OptionBest forNotes
ACA built-in ingressMost appsEnvoy TLS; custom domain + free managed certificate; IP allow list; no rate limiting / WAF
Azure Front Door (Standard/Premium)Global users, WAF/CDNEdge TLS, WAF rate-limit rules, static caching; origin can accept only Front Door traffic
Application Gateway (WAF v2)Regional, VNet-internalL7 load balancing + WAF; can front internal ACA
API ManagementPublic APIsKeys/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.

Command-line exercises
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
Scenario analysis
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 Explained in 100 Seconds — Fireship
2:05 · 2020-10-16 · English · reverse proxy and load balancing concepts

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
Visual: local nginx fades into ACA ingress and Front Door icons.
Narration: In the cloud, hand certificates and WAF to a managed entry point.
or score ≥ 70% on the "Quiz" tab

Module 4 · Scenario ③: Async and scheduled jobs

20:00 – 28:00 · Queue + worker: acks, retries, dead letters, idempotency, graceful shutdown; cron jobs; queue-length scaling
8 min★★★★★
Learning objectives
  • 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.
Prerequisites: the idempotency key from Module 2; signals and exit codes from hour 2. Importance: ★★★★★

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

EssentialHowWhat happens if you don't
DurabilityQueue durable=True, message delivery_mode=2Messages lost on RabbitMQ restart
Manual ackOnly after success call basic_ack;prefetch_count=1Auto-ack loses the message on a crash; a large prefetch lets one worker hoard messages
Idempotent consumptionUPDATE … 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 lettersOn failure republish with an x-retry header; on the 3rd failure nack(requeue=False) → via orders.dlx into orders.dlqA "poison message" loops forever, blocking workers and normal messages
Graceful shutdownOn SIGTERM, finish the current message, then exit; stop_grace_period: 30sSIGKILLed 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 runs docker 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 BusRedis lists / StreamsKafka / Event Hubs
ModelTask queue (deleted on consume), dead letters, delays, prioritiesLightweight, handy if Redis is already thereReplayable event log, ordered per partition
Good forBackground jobs, commandsSmall, low-stakes jobsHigh-throughput event streams, many consumers
Consistency between the DB write and the publish The sample commits, then publishes: if publishing fails, the order stays pending. In production use a Transactional Outbox (an outbox row in the same transaction, forwarded by a background process) or a job that republishes long-pending orders.
Common misconceptions ① "The queue guarantees exactly once": RabbitMQ and Service Bus default to at-least-once; exactly-once effects come from idempotency. ② "More retries, more reliable": endless poison retries tie up workers; cap and back off. ③ "The DLQ is a trash can": dead letters are open tickets that must alert. ④ "crond in the container is simplest": PID 1 gets one job; schedule with host cron, an ACA Schedule job or EventBridge Scheduler.
apipublish queue: ordersdurablex-dead-letter-exchange worker-1 worker-2 PostgreSQLidempotent UPDATE orders.dlx orders.dlq fail: republish x-retry+1 3rd fail: nack(requeue=False) ack onlyafter success
Figure 4-1 Message lifecycle: publish → consume → ack on success / retry on failure / dead-letter after too many attempts
Service Busqueue orders KEDA rule (every 30 s)messageCount=5, managed ID ca-orders-worker0 ↔ 4 replicas Dead-letter subqueueorders/$deadletterqueue desired replicas ≈ ceil(queue length / 5), max 4; scale to 0 after 300 s idle
Figure 4-2 Azure: event-driven scaling on queue length

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.

Ready.
$ docker compose logs -f --no-log-prefix worker

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

CommandDescription
docker compose exec rabbitmq rabbitmqctl list_queues name messages_ready messages_unacknowledged consumersDepth, unacked, consumers
docker compose exec rabbitmq rabbitmq-diagnostics -q pingHealthcheck 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-recreateAdd consumers
docker compose stop -t 30 workerSIGTERM, wait ≤ 30 s, then SIGKILL
docker compose run --rm -e REPORT_DAY=2026-11-14 reportRun / backfill the job by hand
crontab -eHost scheduling (see lab)

Lab 4: backlog, scale-out, poison messages, graceful shutdown and the daily report (about 6 minutes)

Stop workers; watch messages pile up
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
Start 4 workers to drain the backlog
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
Poison message → 3 retries → dead letter
$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.

Graceful shutdown
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.

Scheduled job: run by hand + cron
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
PointNotes (checked against official docs, 2026-11)
Managed-identity scalingManaged 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 defaultsPolling interval 30 s; cooldown 300 s (only for the last replica → 0)
AZURE_CLIENT_IDRequired when the app's DefaultAzureCredential uses a user-assigned identity
Event job vs long-running workerLong (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 lettersBeyond --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.

Command-line exercises
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}}'
Scenario analysis
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 in 100 Seconds — Fireship
2:30 · 2022-09-06 · English · exchanges, queues, bindings, AMQP concepts

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the "Quiz" tab

Module 5 · Scenario ④: Database migrations and releases

28:00 – 35:00 · Migrations as a one-off job; expand/contract for zero downtime; backups must be restorable
7 min★★★★★
Learning objectives
  • 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.
Prerequisites: Module 1 (one-off processes); Hour 5, Module 7 (release and rollback). Importance: ★★★★★

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:

StepDatabaseApplicationCan we roll back to the previous version?
1 ExpandADD 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 BackfillUPDATE … WHERE customer_email IS NULL (in batches for big tables)—✓
4 ContractSET 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

OperationRiskSafe approach
NOT NULL / volatile default on a big tableTable rewrite or long lockAdd nullable, backfill in batches; on PG 11+ a constant default does not rewrite
CREATE INDEXBlocks writesCREATE INDEX CONCURRENTLY (not inside a transaction; run separately)
Dropping/renaming a columnOld version errors at onceExpand/contract; drop last
Any DDLWhile waiting for a lock it blocks every query behind itSET lock_timeout = '5s' before migrating; retry on failure
Common misconceptions① "Rolling back the image rolls back everything" — schema and data stay, so each migration must remain compatible with the previous app version. ② "Automatic backups keep us safe" — an unrehearsed restore is not a backup; a restore also creates a new server, so connection string, firewall and secrets must follow. ③ "The HA standby protects against accidental deletes" — HA replicates DROP TABLE instantly; PITR protects against human error (Module 7).
Build imageorders:1.1 Migration jobexpand only Fail → stop Release app v2old + new coexist Watch / backfillhours to days Next releaserun contract The schema always works with every running version
Figure 5-1 A release pipeline that includes database changes

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).

Ready.
$ docker compose run --rm migrate

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

CommandDescription
docker compose run --rm migrateRun 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.dumpCustom-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.dumpRestore into another DB
pg_dump --versionpg_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 tsvLatest 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)

Migrations are idempotent and concurrency-safe
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
Run the contract migration (as if all instances are on v2)
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'
Backup → restore → verify
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 capabilityDescription
Automatic backupsFlexible Server keeps 7 days by default (1–35 configurable), with point-in-time restore to a new server
Restore drillsaz postgres flexible-server restore … --restore-time restores to a temporary server; verify, then delete
High availabilityGeneral Purpose / Memory Optimized support same-zone or zone-redundant standby (not Burstable; see Module 7)
Long-term retentionBeyond 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.

Command-line exercises
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
Scenario analysis
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:

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
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.
or score ≥ 70% on the "Quiz" tab

Module 6 · Scenario ⑤: File uploads and object storage

35:00 – 42:00 · Files belong in neither container nor database: object storage + short-lived SAS + managed identity
7 min★★★★☆
Learning objectives
  • 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).
Prerequisites: Module 3 (request body limit); managed identity from Hour 3. Importance: ★★★★☆

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

OptionProblem
Container writable layerLost on container recreation; a file uploaded on replica A is invisible to replica B
Local named volumeOne host only; no cross-host scaling; backup, permissions and CDN are on you
Database bytea/BLOBBloats 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, start st, expiry se, signature sig. 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 st 1 minute back for clock skew.

When: upload through the API vs direct upload

Upload through the API (this example)Direct client upload (write SAS)
FlowBrowser → gateway → API → BlobAPI issues a write-only SAS → browser PUTs to Blob → notifies the API
ProsSimple; the API can inspect content and restrict typesLarge files skip API bandwidth and memory; parallel block upload
ConsLarge files tie up API processes; capped by the gateway's client_max_body_sizeNeeds storage CORS; validate asynchronously after upload (size, type, malware)
Good forAvatars, attachments < 10 MBVideo, large files, mobile
Common misconceptions① "Anyone can share a SAS link, so it's insecure": security comes from short lifetime + least privilege + tamper-proof signature; long-lived write SAS links cause incidents. ② "Contributor can do everything": it's management-plane; Blob data needs a Storage Blob Data * data-plane role. ③ "Public container + random names is enough": URLs leak into logs, history and shares, irrevocably.
Browser apiManaged identity Blob: files (private)Public access disabled Entra IDUser delegation key (≤ 7 days) ① POST /api/files ② upload_blob ③ get delegation key ④ return SAS URL ⑤ GET …/files/x?sp=r&se=+10min&sig=… (straight to storage, not via the API)
Figure 6-1 Upload via the API, download straight from storage (Azure). Locally, ③ is signing with the Azurite account key and ⑤ goes through the gateway's /blob/

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).

Ready.
$ curl -sk -F file=@a.pdf https://localhost:8443/api/files

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

CommandDescription
curl -sk -F file=@a.pdf https://localhost:8443/api/filesMultipart 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 tableAzure: 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-uriAzure: generate a user delegation SAS
az storage account update -g RG -n ST --allow-shared-key-access falseDisable account keys (then only Entra ID / user delegation SAS work)

Lab 6: upload, SAS, tampering and sharing across replicas (about 5 minutes)

Upload and download through the SAS
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: 403
Tamper with the expiry → the signature breaks
T=$(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.

All replicas read the same file; recreation loses nothing
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 pointDescription
RolesStorage 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 filesMicrosoft Defender for Storage on-upload malware scanning; or a quarantine container first, moved once the scan passes
LifecycleLifecycle policy: cool tier after 30 days, delete after 365 days; reports can get an immutable (WORM) policy
Direct uploadIssue a short-lived write-only (sp=cw) SAS for one blob name; storage CORS allows only your domain
NetworkPrivate 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.

Command-line exercises
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 table
Scenario analysis
Support 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:

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
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.
or score ≥ 70% on the "Quiz" tab

Module 7 · Scenario ⑥: High availability and disaster recovery

42:00 – 51:00 · A replica dies, a zone or whole region goes down, someone deletes data by mistake: what happens in each case?
9 minAzure first · AWS comparedArchitecture level · commands not run in the cloud★★★★★
Learning objectives
  • 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.
Prerequisites: Module 2 (probes, connections), Module 5 (backups and PITR); Hour 3 (ACA, ACR), Hour 4 (ECS, ECR, ALB). Importance: ★★★★★ (this course's HA and DR module)

What: failure domains and two metrics

Failure domainTypical eventCountermeasureCovered in
Process / replicaOOM, crash, single node failureMultiple replicas + probes + platform auto-replacementModules 2, 4
Availability zone (AZ)Data centers lose power or networkZone redundancy: compute, data and storage across several AZs, automatic failoverThis module
RegionRegion-wide outage, major network incidentMulti-region: images, data replicas, compute and a global entry point in a second region; usually a human decisionThis module
Human error / data corruptionDropped table, bad migration, ransomwareBackups and point-in-time restore: replication copies the mistake tooModule 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 stateWhen an AZ failsWhen the region fails
ACA environment cae-ordersNo VNet, no zone redundancyAll replicas may be in the failed zone; down until the platform rebuilds them elsewhereUnavailable
PostgreSQL B1ms (Burstable)Burstable: no HA; a single serverDatabase down (data safe in ZRS backups)Unavailable; without geo-redundant backup, wait for the region to recover
ACR BasicOne region; geo-replication requires PremiumHandled by the managed serviceNew replicas can't pull images → no scale-out, no deployment elsewhere
Blob, Service Bus, Managed RedisDefault SKU / redundancyPer 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)

LayerZone level (same region)Region level (second region)Prerequisites · cost · limits (verified 2026-11)
Compute ACAZone-redundant environment: replicas spread across AZs automatically; failed-zone replicas are removed and probes usually reroute traffic within about 30 secondsAnother environment in the second region, same app digestSet 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
IngressACA ingress is zone-redundant with the environmentFront 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 alternativeFront Door (classic) retires 2027-03-31; origins should accept only Front Door traffic
Images ACRGeo-replicas are always zone-redundantGeo-replication: one registry, one global endpoint (myregistry.azurecr.io), every replica read-write (active-active); the global endpoint routes to healthy replicas automaticallyRequires 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 ServerZone-redundant HA: hot standby in another AZ, sync replication, automatic forced failover on AZ failure, typically 60–120 seconds, RPO 0Cross-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 BlobZRS (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

StrategyWhat the second region normally hasRTO / RPO (order of magnitude)CostSuits
Backup & restoreBackups only (geo-redundant backups, image replicas)Hours / minutes to hoursLowestInternal systems tolerating half a day of downtime
Pilot lightContinuous data replication (read replica) + images; compute off or minimalTens of minutes / minutesLowDefault for most business systems
Warm standbyData replication + an always-running scaled-down app copyMinutes / seconds to minutesMediumCustomer-facing core business
Multi-site (active-active)Both regions serve; data multi-writer or partitionedNear 0 / near 0 (depends on the data tier)Highest; most complexGlobal 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.

Common misconceptions① "With HA we don't need backups": HA is synchronous, so 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)

Azure Front Door (global · WAF)Origins: priority 1 = primary, 2 = DR Primary region canadacentral (serving) DR region canadaeast (pilot light / warm) ACA zone-redundant env (VNet · min 2 replicas) AZ 1: api · worker AZ 2: api · worker AZ 3: (scale-out) PostgreSQL primaryAZ 1 · GP · zone-redundant HAsync → standby (AZ 2) ACR Premium (home)orders@sha256:…global endpoint · active-active Blob (ZRS / GZRS) · Service Bus · Managed Redis · Key VaultEach uses its own redundancy options; secrets and roleassignments must exist in the DR region too ACA environment (same digest, min replicas 0–1)No traffic normally; scale out on failoverReadiness probe must reflect "database writable" PostgreSQL read replicaasync replication · lag = RPOmanual forced promote 1–3 min ACR geo-replicaeventually consistentstorage billed per replica Failover steps (runbook)Declare disaster → promote replica (virtual endpoint follows)→ scale out DR → Front Door probes switch → smoke test async
Figure 7-1 Solid = normal traffic; dashed = replication and failover paths. In-region redundancy is automatic; cross-region failover needs a human decision

Comparison: Azure vs AWS

LayerAzure (this course's main path)AWS (compare with hour 4)
Compute across AZsACA zone-redundant environment: set at creation, VNet, min replicas ≥ 2, no extra costECS 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 balancingACA built-in ingressALB (cross-AZ)
Global entry / failoverFront 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 regionsACR geo-replication (Premium): one registry, global endpoint, active-active, eventually consistentECR 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 levelPostgreSQL 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 levelCross-region read replica + virtual endpoint; geo-redundant backup → paired-region restoreCross-region read replicas; Aurora Global Database (async replication to secondary regions); cross-region backup replication
Object storageBlob ZRS / GZRS / RA-GZRSS3 (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).

Ready.
$ # monitoring and runbook output appears here

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

CommandPurpose
az containerapp env show … --query properties.zoneRedundantIs the environment zone-redundant?
az containerapp replica list -g RG -n APP -o tableReplica count (meaningful at ≥ 2)
az acr replication list -r ACR -o tableGeo-replica status (anything but Online is trouble)
az postgres flexible-server restart --failover Planned|ForcedHA failover drill
az postgres flexible-server replica promote --promote-mode switchover --promote-option planned|forcedCross-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.

Record a baseline and cause a "disaster": back up, then assume the primary database's region is down.
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)
Restore in the "secondary region" and switch over: restore into new database 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.

Fail back and clean up:
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
Write the runbook: save this template as 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.

Command-line exercises
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 table
2. 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"
Scenario analysis
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

▶
The Ultimate Guide to Disaster Recovery: RTO, RPO, & Failover! — ByteMonk
English · duration not verified · RTO / RPO, failover and failback, backup-restore / pilot light / warm standby / hot standby (title/channel verified via YouTube oEmbed)

Official documentation

Video storyboard (about 90 seconds)

No video/MP3 is generated here; this storyboard and narration script can feed a video tool.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or score ≥ 70% on the "Quiz" tab

Module 8 · Architecture review and incident drill

51:00 – 60:00 · One checklist for the whole system: what happens when each part fails? Then diagnose 7 realistic incidents from evidence
9 minRecap + self-test★★★★★
Learning objectives
  • 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.
Prerequisites: Modules 1–7. Importance: ★★★★★

Failure mode analysis (this system)

Component failureWhat users seeMitigation in the designWhat is still missing
1 api replica crashesNothing2 replicas + health checks + gateway re-resolution—
Redis downSlower responsesCache degradation, 0.5 s timeoutDatabase capacity for uncached traffic
RabbitMQ downOrder placement errors (publish fails)Worker reconnectsOutbox pattern; highly available Service Bus on Azure
All workers stoppedOrders stuck in pendingDurable messages, processed after recoveryQueue depth alert
Database downWhole site unavailableReadiness probe returns 503Managed database + zone-redundant HA; backup/PITR drills (Module 7)
Blob unavailableUpload/download fails, ordering worksFeature isolationRetries, friendly message
Host downEverything unavailable—Inherent to single-host Compose → ACA multi-replica + zone redundancy (Module 7)

Review checklist (condensed five Well-Architected pillars)

PillarChecks
ReliabilityNo single point of failure? Separate probes? Idempotency? Dead-lettering? Backups restorable?
SecurityOnly the gateway exposed? No keys (managed identity)? Secrets in Key Vault? Non-root? Private storage + short-lived SAS?
CostWorkers scale to 0? Database SKU fits the connection budget? Lifecycle policies?
OperationsJSON logs + request ID? Separate migration job? One image, many processes? Alerts (DLQ, 5xx, restarts)?
PerformanceCaching? Connection pooling? Slow work async? Large files uploaded directly?

How: running a review

  1. Prepare: the latest architecture diagram (Module 1), ADR list and non-functional requirements (availability, RTO/RPO, latency).
  2. Analyze failure per component (table above): write impact as "what users see", not "the component errors".
  3. Score the five pillars (Animation tab scorer); fix reliability and security gaps first.
  4. Verify with drills: every design mitigation needs a drill proving it works — this lesson's failure-drill labs are that evidence.
  5. 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

TopicContent
Deep troubleshootingnsenter / docker debug, tcpdump, strace, /proc, OOM/cgroup events, DNS/MTU issues, zombie processes
Performance tuningLoad testing (k6), P95/P99, gunicorn processes/threads, pool tuning, slow queries, Redis hot keys
Build extensionsRemote BuildKit, cache backends, Bake matrices, multi-arch builds
Advanced networkingmacvlan/ipvlan, IPv6, overlay troubleshooting, iptables/nftables rules
Developer experienceDev Containers, Testcontainers tests, Compose Watch
GPU / AI workloadsNVIDIA Container Toolkit, --gpus, model-serving containers
Failure drillsChaos experiments: latency injection, full disks, dependency timeouts
Common misconceptions① "A review is fault-finding" — its output is a prioritized risk list, not a score. ② "Fix every gap now" — rank by impact × likelihood; some risks can be explicitly accepted in an ADR. ③ "Drills might hurt production, so skip them" — start in staging with planned failovers, then widen; an undrilled mitigation is as good as none.

Failure mode heat map: impact × current state

What users see when a part fails (single-host Compose → Azure zone-redundant + indicators) ComponentLocal ComposeAzure (final lab)Azure (hardened, Mod 7) 1 api replicaNot noticedNot noticedNot noticed RedisSlower (degraded)Slower (degraded)Managed HA + degrade QueueOrders failManaged Service Bus+ outbox DatabaseSite downB1ms, no HAZone HA, 1–2 min Zone(1 host) all downMay be interruptedBarely noticed Region—Down (wait it out)Manual failover (min) AcceptableDegraded / watchUnacceptable, goes on the risk list
Figure 8-1 The color shift across the three stages is this course's progress

Knowledge map: six scenarios, one system

ModulePatternsIncidents preventedDrill evidence
2Connection budget, cache-aside + degradation, separate probes, idempotency keysScale-out swamping the database, cache failure downing the site, duplicate ordersRedis stopped → 200; database frozen → /readyz 503 in 2 s (tested)
3Single entry point, TLS, rate limiting, dynamic DNSExpired certs, traffic bursts, 502 after scaling50 concurrent → 22×200 / 28×429 (tested)
4At-least-once + idempotency, retries + dead-lettering, graceful shutdownDuplicate shipments, poison messages blocking the queue, half-done work during releasesPoison message to DLQ after 3 attempts
5Migration job + advisory lock, expand/contract, restore drillsOld version errors during releases, long-lock downtime, bad backups3 concurrent migrations run only once (tested)
6Object storage, short-lived read-only SAS, shared keys disabledLost files, data leaksTampered se → 403 (tested)
7Zone redundancy, geo-replication, read replicas, runbooksZone / region outages, accidental deletionLocal 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).

Ready.
[pager] alert received

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

CheckLocal commandAzure command
Exposuredocker compose ps --format '{{.Service}} {{.Ports}}'az containerapp list -g RG --query "[].{n:name,ext:properties.configuration.ingress.external}" -o table
Non-rootdocker compose exec api id -uImage USER 10001 (hour 2)
No secrets in images/codedocker image history --no-trunc orders:1.0 | grep -iE 'password|key'az containerapp show … --query "properties.configuration.secrets[].keyVaultUrl"
Replicas and scalingdocker compose ps api workeraz containerapp show … --query properties.template.scale
Dead lettersrabbitmqctl list_queues name messagesaz servicebus queue show … --query countDetails.deadLetterMessageCount
Backups and HAls -lh orders-*.dumpaz 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)

End-to-end smoke test script
#!/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.

Cleanup (local)
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.

Command-line exercises
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 -u
2. 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}}'
Scenario analysis
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

▶
Kubernetes-Free Microservices: The Azure Container Apps Advantage — Microsoft Reactor
2025-04-04 · English · duration not verified · microservice architecture on Container Apps

Video storyboard (about 75 seconds)

Shot 1 · 0–25s
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.
Shot 2 · 25–50s
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.
Shot 3 · 50–75s
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.
or score ≥ 70% on the "Quiz" tab

Command cheat sheet

Compose, data-tier, gateway, queue, storage, HA and Azure / AWS commands from this hour

Compose lifecycle

docker compose up -d --buildBuild and start
docker compose up -d --scale api=4 --no-recreateScale replicas
docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'Status (incl. exited one-off services)
docker compose logs -f --no-log-prefix apiFollow logs
docker compose run --rm reportRun a one-off / profile service
docker compose stop -t 30 workerGraceful stop
docker compose pause postgresFreeze processes (drill)
docker compose config -qValidate 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 ordersInteractive 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.dumpBackup
docker compose exec -T postgres pg_restore -U orders -d NEWDB --no-owner < o.dumpRestore
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 statsTTL, hit ratio
rabbitmqctl list_queues name messages_ready messages_unacknowledged consumersQueue status
rabbitmq-diagnostics -q pingHealth check
ssh -L 15672:localhost:15672 VMRemote management UI

Gateway / TLS

docker compose exec gateway nginx -tCheck configuration
docker compose exec gateway nginx -s reloadGraceful reload
curl -skI https://localhost:8443/Response headers
openssl s_client -connect H:443 -servername H </dev/null | openssl x509 -noout -datesCertificate validity
seq 50 | xargs -P25 -I{} curl -sk -o /dev/null -w '%{http_code}\n' URL | sort | uniq -cQuick concurrency test

Azure data and messaging

az postgres flexible-server create --version 17 --tier Burstable --sku-name Standard_B1msManaged PostgreSQL
az postgres flexible-server restore -n NEW --source-server SRC --restore-time TPoint-in-time restore
az redisenterprise create --sku Balanced_B0 --clustering-policy EnterpriseClusterManaged Redis (port 10000)
az servicebus queue create --max-delivery-count 5Queue + automatic dead-lettering
az storage account create --allow-shared-key-access false --allow-blob-public-access falseEntra-only access

Azure Container Apps

az containerapp create … --ingress internalInternal API
… --scale-rule-type azure-servicebus --scale-rule-identity IDScale on queue length (managed identity)
az containerapp job create --trigger-type Manual|Schedule|EventMigration / scheduled / event jobs
az containerapp job start -n JTrigger manually
az containerapp job execution show -n J --job-execution-name EExecution status
az containerapp logs show -n APP --followLog stream

HA and DR (Azure, examples)

az containerapp env create … --infrastructure-subnet-resource-id S --zone-redundantZone-redundant environment (creation only)
az containerapp update … --min-replicas 2Needed to spread across zones
az acr replication create -r ACR -l REGIONACR geo-replication (Premium)
az postgres flexible-server update … --zonal-resiliency Enabled --standby-zone 2Zone-redundant HA (not Burstable)
az postgres flexible-server restart … --failover Planned|ForcedHA failover drill
az postgres flexible-server replica create / promoteCross-region read replica, promotion
az afd origin create … --priority 1|2Front Door primary/secondary origins

HA and DR (AWS equivalents, examples)

aws ecs update-service … --availability-zone-rebalancing ENABLEDECS 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-immediatelyRDS Multi-AZ DB instance
aws rds reboot-db-instance … --force-failoverFailover drill
Route 53 failover records (PRIMARY / SECONDARY + health checks)DNS-level primary/standby

Design decisions at a glance

NeedPatternModule
Think it through before buildingNon-functional requirements → data flow → ADR → failure analysis1
Read-heavy, high latencyCache-aside + TTL + invalidate on write + degradation2
Clients retryIdempotency key + unique constraint2
Several backends, one TLS endpoint, rate limitingGateway / reverse proxy3
Slow operations, absorbing spikesQueue + worker + dead-lettering + idempotent consumers4
Periodic tasksRe-entrant one-off process + external scheduler (cron / ACA Schedule job)4
Schema changesSeparate migration job + expand/contract + lock_timeout5
User filesObject storage + short-lived read-only SAS (user delegation)6
Zone outage barely noticedZone-redundant compute (≥ 2 replicas) + zone-redundant HA database + ZRS storage7
Recoverable region outageImage geo-replication + cross-region read replica + global-entry priority routing + runbook and drills7
Accidental deletion / data corruptionPITR, geo-redundant backups, regular restore drills5, 7

Quick troubleshooting table

SymptomMost likely causeLook at first
too many clients alreadyConnection budget exceededpg_stat_activity grouped by client
Gateway 502Upstream not ready / static DNS caching old IPdocker compose ps api, nginx resolver
Lots of 429sRate-limit threshold / real client IP not restoredremote in the gateway's JSON log
Orders stuck in pendingWorker down / publish failed / message in the DLQlist_queues, worker logs
Worker exit code 137Signal not reaching Python / processing exceeds the grace periodEntrypoint uses exec? stop_grace_period
Old version reports "column does not exist" mid-releaseContracted too earlyTABLE schema_migrations
Blob 403SAS expired/tampered, no data-plane role, shared key disabledError code (AuthenticationFailed / AuthorizationPermissionMismatch / KeyBasedAuthenticationNotPermitted)
manifest unknown pulling in the secondary regionGeo-replication unfinishedaz acr replication list, webhook
App keeps returning 500 after HA failoverPool holds stale connections, no retryApp logs, readiness probe code

Final lab: deploy the orders system to Azure + final quiz

About 40–60 minutes (mostly waiting on resource creation) · incurs charges; clean up right after
Paid resourcesCommands not run in this environment; outputs are examples
Target architecture
  • 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.
Users Container Apps environment cae-orders (managed identity id-orders) ca-orders-webexternal · nginx ca-orders-apiinternal · 1–5 ca-orders-workerKEDA 0–4 job-migrate / job-report PostgreSQL 17 Managed Redis Service Bus Blob Storage Key Vault · ACR
Figure F-1 Azure target architecture
Variables file 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.
Deploy (about 20–30 minutes)
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 test (the Module 8 script)
./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.

Watch event-driven scaling
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
Verify the security design
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
Reliability check-up (Module 7, read-only): run the Module 7 lab's four read-only checks and paste the output into your risk list.
Clean up (important)
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).

Extension challenges ① Turn deploy.sh into the hour 5 pipeline (job-migrate first, then update api/worker by digest), and manage infrastructure as in the Terraform course (Chinese). ② Move Redis to Entra ID auth (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

Verified: 2026-11-17 (Modules 1–6 first verified on 2026-11-15)

Versions and prerequisites

ComponentVersion used / verified in this hour
Docker Engine / Compose29.x / v5.x (verified in Hours 1–5)
Python dependenciesflask 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
Imagespython: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 CLI2.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 server17 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 RedisPort 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 redundancySet 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-replicationPremium; 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 DoorStandard / Premium; origin priority 1–5; (classic) retires 2027-03-31
AWSECS 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

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 on removed).
  • 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 -m as an option (switched to orders-* 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.sh matches the Chinese edition, so its comments and echo messages stay in Chinese (same code).