forked from mtusi2026/mtusi2026lab3
feat: HAProxy и N API-реплик, X-Instance-Id, общая идемпотентность, drain при SIGTERM
- compose: один масштабируемый сервис api (deploy.replicas=2, без ports и container_name), HAProxy 3.2 LTS по digest — единственная точка входа (127.0.0.1), разовый migrate до старта реплик, CPU/RAM-лимиты у всех сервисов, каждому сервису только его secrets. - HAProxy: server-template + Docker DNS (re-resolve 1 с), активная проверка GET /health/ready каждую 1 с (fall 2 / rise 2), без backup-серверов, retry только conn-failure, ошибки самого LB — в формате контракта с X-Request-Id. - API: X-Instance-Id = hostname контейнера на каждом ответе (и на 500/503); Idempotency-Key обязателен; ключ, сообщение и результат пишутся в ОДНОЙ транзакции (миграция 0002), конкурентный повтор ждёт уникальный индекс; другой body — 409, посторонний — всегда 404; attachment_ids=[] равен отсутствию поля; дубли ключей JSON и тело у POST /auth/sessions — 400. - SIGTERM: readiness 503 + DRAIN_SECONDS=3 обслуживания, затем graceful stop. - scripts: stop-one.sh (+ .cmd для Windows), restore-api.sh, restart.sh перезапускает и LB, lbctl.py — состояние бэкендов HAProxy -> контейнеры. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4f6cfda37a
commit
3f12698676
+62
-10
@@ -1,9 +1,12 @@
|
||||
# Lab 2 stand: API + PostgreSQL + Valkey. Start from a clean clone:
|
||||
# Lab 3 stand: client -> HAProxy (lb) -> API x N (one scalable service `api`) -> PostgreSQL + Valkey.
|
||||
# From a clean clone (details and Windows notes: REPORT.md, docs/WINDOWS.md):
|
||||
# python scripts/init_secrets.py # once: random local credentials into ./secrets (git-ignored)
|
||||
# cp .env.example .env # optional overrides
|
||||
# docker compose up -d --build --wait
|
||||
# Images are pinned by version AND digest. Passwords are passed only as secret files.
|
||||
name: mtusi-lab2
|
||||
# cp .env.example .env # optional overrides (API_REPLICAS, limits, ...)
|
||||
# docker compose --env-file .env up -d --build --wait
|
||||
# Order: postgres/valkey healthy -> migrate (ONE run, exits 0) -> api replicas healthy -> lb.
|
||||
# Images are pinned by version AND digest. Passwords are passed only as secret files, and
|
||||
# every service gets only the secrets it needs. Only the LB publishes ports (127.0.0.1 only).
|
||||
name: mtusi-lab3
|
||||
|
||||
x-api-env: &api-env
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
@@ -17,6 +20,10 @@ x-api-env: &api-env
|
||||
DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3}
|
||||
CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-0.5}
|
||||
PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
# Graceful stop: 3 s drain (readiness 503, still serving) + up to 8 s for in-flight requests.
|
||||
DRAIN_SECONDS: ${DRAIN_SECONDS:-3}
|
||||
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-8}
|
||||
DOCS_ENABLED: ${DOCS_ENABLED:-true}
|
||||
|
||||
services:
|
||||
@@ -26,6 +33,8 @@ services:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
# pg_stat_statements: per-statement counters for the track 5 experiments (bench/track1).
|
||||
command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"]
|
||||
secrets: [postgres_password]
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql # PostgreSQL 18 image keeps PGDATA under this path
|
||||
@@ -37,6 +46,9 @@ services:
|
||||
start_period: 10s
|
||||
stop_grace_period: 30s # clean shutdown checkpoint instead of crash recovery
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${PG_CPUS:-2.0}", memory: "${PG_MEMORY:-1g}"}
|
||||
|
||||
valkey:
|
||||
image: valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571
|
||||
@@ -61,10 +73,15 @@ services:
|
||||
retries: 30
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${VALKEY_CPUS:-0.5}", memory: 256m}
|
||||
|
||||
# One-shot schema migration: runs ONCE per `up`, before any API replica starts
|
||||
# (api depends_on service_completed_successfully). Replicas never migrate themselves.
|
||||
migrate:
|
||||
build: .
|
||||
image: mtusi-messenger:lab2
|
||||
image: mtusi-messenger:lab3
|
||||
command: ["python", "-m", "messenger.migrate"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
@@ -75,14 +92,24 @@ services:
|
||||
healthcheck:
|
||||
disable: true
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256m}
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtusi-messenger:lab2
|
||||
image: mtusi-messenger:lab3
|
||||
environment: *api-env
|
||||
secrets: [database_url, cache_url]
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PUBLISH_PORT:-8080}:8080" # only on localhost of the host
|
||||
# No `ports` and no container_name: replicas are reachable only through `lb`,
|
||||
# and `--scale api=N` / deploy.replicas works. X-Instance-Id = container hostname.
|
||||
expose: ["8080"]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-m", "messenger.healthcheck"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -90,8 +117,33 @@ services:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
stop_grace_period: 10s
|
||||
stop_grace_period: 15s # > DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS (11 s)
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-256m}"}
|
||||
|
||||
lb:
|
||||
image: haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PUBLISH_PORT:-8080}:8080" # the ONLY public entry point
|
||||
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404" # local status page (UP/DOWN of replicas)
|
||||
healthcheck:
|
||||
# Config is valid and the process answers; whether any API is ready is the LB's own job.
|
||||
test: ["CMD-SHELL", "haproxy -c -q -f /usr/local/etc/haproxy/haproxy.cfg && wget -q -O /dev/null http://127.0.0.1:8404/"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${LB_CPUS:-1.0}", memory: 128m}
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
|
||||
Reference in New Issue
Block a user