Поднять API в нескольких репликах за HAProxy и добавить скрипты отказа реплики и rolling update

This commit is contained in:
2026-11-02 17:20:38 +03:00
parent 951fd0d517
commit c5cdcb3377
9 changed files with 312 additions and 10 deletions
+1
View File
@@ -2,5 +2,6 @@
# checkouts with core.autocrlf=true.
*.sh text eol=lf
*.conf text eol=lf
*.cfg text eol=lf
*.sql text eol=lf
*.cmd text eol=crlf
+10 -1
View File
@@ -34,7 +34,7 @@ test-failover:
# ---------------------------------------------------------------------------
EVIDENCE_DIR ?= evidence
.PHONY: build vet unit secrets up down destroy logs concurrency explain
.PHONY: build vet unit secrets up down destroy logs concurrency explain instances rollout
build:
go build -o bin/server ./cmd/server
@@ -63,6 +63,15 @@ destroy:
logs:
docker compose logs
# Which container answers under which X-Instance-Id.
instances:
sh scripts/instances.sh
# Replaces every API replica with one built from the current sources, without
# downtime; restore a replica stopped by stop-one with `docker compose start api`.
rollout:
sh scripts/rollout.sh
concurrency:
go run ./tools/concurrency --base-url "$(BASE_URL)" --output "$(EVIDENCE_DIR)/concurrency.json"
+93 -9
View File
@@ -1,13 +1,51 @@
# Local stand: the API over PostgreSQL (users, chats, messages) and Valkey
# (sessions). Only the API is published, on loopback. Credentials are files in
# Local stand: HAProxy in front of interchangeable API replicas over shared
# PostgreSQL (users, chats, messages, idempotency keys) and Valkey (sessions).
# Only the balancer is published, on loopback. Credentials are files in
# ./secrets created by `make secrets`; named volumes keep the data across
# restarts, and only `make destroy` removes them.
#
# Two networks: edge joins the balancer and the API, data joins the API, the
# migrations and the stores and has no way out. The balancer cannot reach the
# stores, and the stores cannot reach anything outside.
name: lab3
services:
lb:
image: haproxy:3.4.7-alpine3.24@sha256:2caaf8b1a1ef67f3f1ea9b721f2821675d3ba4500fb518e23884fecb93e8dbaa
volumes:
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
environment:
# 1 silences the log line of every successful request during load runs.
LB_QUIET: ${LB_QUIET:-0}
# One HAProxy thread per CPU of the limit below.
LB_THREADS: ${LB_THREADS:-1}
ports:
# Loopback only; override with PUBLISH=127.0.0.1:28080 when 8080 is busy.
- "${PUBLISH:-127.0.0.1:8080}:8080"
# Read-only statistics page: state and checks of every replica.
- "${STATS_PUBLISH:-127.0.0.1:8404}:8404"
networks:
- edge
healthcheck:
# Through the balancer itself: healthy once it can route to a ready
# replica, so `compose up --wait` means "ready through the entry point".
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/health/ready"]
interval: 5s
timeout: 3s
retries: 3
start_period: 20s
start_interval: 1s
deploy:
resources:
limits:
cpus: "${LB_CPUS:-0.5}"
memory: 128M
api:
build: .
image: mtusi-messenger:lab3
# Fixed name for docker logs/inspect in the report.
container_name: mtusi-messenger-lab3
# No container_name and no ports: the service scales, and clients reach
# the replicas only through the balancer.
env_file:
- path: .env
required: false
@@ -15,9 +53,20 @@ services:
DATABASE_URL_FILE: /run/secrets/database_url
SESSION_STORE_URL_FILE: /run/secrets/session_store_url
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
# Above the balancer's detection time of 1.5 s (haproxy.cfg).
APP_DRAIN_DELAY: ${APP_DRAIN_DELAY:-2s}
DB_MAX_CONNS: ${DB_MAX_CONNS:-10}
# About 90 % of the memory limit below; Go does not read the cgroup limit.
GOMEMLIMIT: ${API_GOMEMLIMIT:-230MiB}
# Empty disables the internal expvar listener; the benchmark sets :9090.
APP_DEBUG_ADDR: ${APP_DEBUG_ADDR:-}
secrets:
- database_url
- session_store_url
networks:
- edge
- data
depends_on:
migrate:
condition: service_completed_successfully
@@ -25,12 +74,16 @@ services:
condition: service_healthy
valkey:
condition: service_healthy
# Loopback only; override with PUBLISH=127.0.0.1:18080 when 8080 is busy.
ports:
- "${PUBLISH:-127.0.0.1:8080}:8080"
stop_grace_period: 10s
# Drain delay 2 s + shutdown timeout 8 s fit before Docker sends SIGKILL.
stop_grace_period: 15s
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits:
cpus: "${API_CPUS:-1.0}"
memory: ${API_MEMORY:-256M}
# One-shot: applies the schema before the API starts, then exits.
# One-shot: applies the schema once before the replicas start, then exits.
migrate:
image: mtusi-messenger:lab3
entrypoint: ["/usr/local/bin/migrate"]
@@ -38,15 +91,26 @@ services:
DATABASE_URL_FILE: /run/secrets/database_url
secrets:
- database_url
networks:
- data
depends_on:
postgres:
condition: service_healthy
restart: "no"
healthcheck:
# The image's check probes the API port, which migrate never opens.
disable: true
deploy:
resources:
limits:
cpus: "0.5"
memory: 128M
postgres:
image: postgres:18.6-alpine3.24@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873
# Ten replicas with ten connections each fit during a rolling update of
# five, plus migrate and psql sessions.
command: ["postgres", "-c", "max_connections=150"]
environment:
POSTGRES_DB: messenger
POSTGRES_USER: messenger
@@ -57,6 +121,8 @@ services:
# below /var/lib/postgresql, so the volume is mounted on the parent.
volumes:
- pgdata:/var/lib/postgresql
networks:
- data
healthcheck:
# Over TCP: during first initialisation the image runs a temporary
# server on the Unix socket only, which must not count as ready.
@@ -68,6 +134,11 @@ services:
# A clean shutdown writes a checkpoint instead of leaving crash recovery
# to the next start.
stop_grace_period: 30s
deploy:
resources:
limits:
cpus: "${PG_CPUS:-1.0}"
memory: ${PG_MEMORY:-512M}
valkey:
image: valkey/valkey:9.1.2-alpine3.24@sha256:48332870af354a799964c0012ae1194a0bf2bf894eb508f945810596dc2d8d11
@@ -77,6 +148,8 @@ services:
volumes:
- ./infra/valkey/valkey.conf:/usr/local/etc/valkey/valkey.conf:ro
- valkeydata:/data
networks:
- data
healthcheck:
# valkey-cli exits 0 even on NOAUTH, so the reply itself is checked.
test: ["CMD-SHELL", "VALKEYCLI_AUTH=\"$$(sed -n 's/^requirepass //p' /run/secrets/valkey_auth)\" valkey-cli ping | grep -q PONG"]
@@ -85,11 +158,22 @@ services:
retries: 10
start_period: 5s
stop_grace_period: 10s
deploy:
resources:
limits:
cpus: "0.5"
# maxmemory 256mb (valkey.conf) plus the server's own overhead.
memory: 320M
volumes:
pgdata:
valkeydata:
networks:
edge: {}
data:
internal: true
secrets:
database_url:
file: ./secrets/database_url
+83
View File
@@ -0,0 +1,83 @@
# The single entry point: round-robin over the API replicas found through
# Docker DNS, with active readiness checks and no client stickiness. Replicas
# are interchangeable: sessions live in Valkey, everything else in PostgreSQL.
global
log stdout format raw local0 info
maxconn 20000
# One thread per CPU of the container limit; by default HAProxy would
# start one per CPU of the host and fight the CPU quota.
nbthread "${LB_THREADS}"
defaults
mode http
log global
option dontlognull
# Inside the Docker network a replica accepts or refuses at once; a
# second means it is gone.
timeout connect 1s
timeout client 30s
# Above the API's own 5 s request deadline: a slow request ends in the
# API's 503 with its cause logged, and this timeout only cuts off a
# replica that hangs entirely.
timeout server 7s
timeout http-request 10s
timeout http-keep-alive 10s
timeout check 2s
# A request is re-sent, to another replica, only when the connection
# failed and so nothing reached the API. A timeout or an empty response
# may follow a committed write, and POST /users or /chats must never be
# repeated behind the client's back (contract, idempotency section).
retries 2
option redispatch 1
retry-on conn-failure
# Errors produced by the balancer itself use the contract's envelope. They
# carry X-Request-Id but no X-Instance-Id: no replica answered.
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"the API replica failed to answer","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"no API replica is available","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"the API replica did not answer in time","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
# Docker's embedded DNS: the service name `api` resolves to every running
# replica. Re-resolved every second, so scaled, restarted or replaced
# replicas join and stopped ones leave without a reload.
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 10s
hold obsolete 0s
accepted_payload_size 8192
frontend entry
bind :8080
option httplog
# 32 hex characters, like the request ids of the API.
unique-id-format %[uuid(4),regsub(-,,g)]
# The access log names the replica that answered and its request id, which
# is the key to the replica's own log line.
capture response header X-Instance-Id len 32
capture response header X-Request-Id len 40
http-after-response set-log-level silent if { status lt 500 } { env(LB_QUIET) -m str 1 }
default_backend replicas
backend replicas
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
# Detection: a replica that fails readiness is out after the next check
# (inter 1 s) plus one fast re-check (fastinter 0.5 s), so within 1.5 s.
# A stopping API keeps serving for APP_DRAIN_DELAY (2 s) after readiness
# turns 503, longer than this, and only then closes its listener. Back in
# rotation after two good checks (rise 2), about 2 s.
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4
# Ten slots: up to five replicas, doubled while docker rollout replaces them.
server-template api 10 api:8080
listen stats
bind :8404
no log
stats enable
stats uri /
stats refresh 2s
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# Lists the API containers of this compose project, one per line:
# <container id> <name> <state> <alias> <image id>
# The alias is what the process sends as X-Instance-Id. It is random per
# process, so it is asked from the process itself, over the same wget the
# Docker healthcheck uses, from inside the container. A container that is not
# running has no alias and shows "-". The replicas are asked in parallel: the
# failover hook that relies on this list must return within 10 seconds.
set -eu
cd "$(dirname "$0")/.."
ids=$(docker compose ps -aq api)
[ -n "$ids" ] || exit 0
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
docker inspect --format '{{.Id}} {{.Name}} {{.State.Status}} {{.Image}}' $ids >"$tmp/containers"
while read -r id name state image; do
if [ "$state" = running ]; then
# wget prints the response headers on stderr; the body is dropped.
(docker exec "$id" wget -S -q -O - http://127.0.0.1:8080/health/live 2>&1 >/dev/null |
sed -n 's/^ *[Xx]-[Ii]nstance-[Ii]d: *//p' | tr -d '\r' | head -n 1 >"$tmp/$id") &
fi
done <"$tmp/containers"
wait
while read -r id name state image; do
alias=-
if [ -s "$tmp/$id" ]; then
alias=$(cat "$tmp/$id")
fi
image=${image#sha256:}
printf '%s %s %s %s %s\n' "$(printf '%s' "$id" | cut -c1-12)" "${name#/}" "$state" "$alias" "$(printf '%s' "$image" | cut -c1-12)"
done <"$tmp/containers"
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# Shows which container answers under which X-Instance-Id: the proof on the
# defense that the header values belong to different running processes, and
# which container a failover test actually stopped.
set -eu
cd "$(dirname "$0")/.."
printf '%-12s %-14s %-8s %-16s %s\n' CONTAINER NAME STATE X-INSTANCE-ID IMAGE
sh scripts/api-instances.sh | while read -r id name state alias image; do
printf '%-12s %-14s %-8s %-16s %s\n' "$id" "$name" "$state" "$alias" "$image"
done
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
# Rolling update of the API without downtime, with docker rollout
# (https://github.com/wowu/docker-rollout, MIT): it starts as many new
# replicas as are running, waits until all of them are healthy, then stops
# and removes the old ones. If a new replica does not become healthy it
# removes the new ones and leaves the old ones serving, so the stand is never
# left with a mix of versions.
#
# The migrations of the new version run first, once, while the old replicas
# serve: they only add to the schema. docker rollout scales with `compose up`,
# which also starts the dependencies of the API and would rerun the old,
# exited migrate container. Recreating it beforehand from the new image,
# without starting it, makes that `up` run the new migrations exactly once,
# before any new replica starts.
set -eu
cd "$(dirname "$0")/.."
version=v0.14
checksum=cdeaba6ae9eee3b0b606286e585bbda6787283d801a6ad6d9b9d2bc347fda05b
tool=bin/docker-rollout
if ! printf '%s %s\n' "$checksum" "$tool" | sha256sum -c - >/dev/null 2>&1; then
mkdir -p bin
curl -fsSL -o "$tool.download" "https://github.com/wowu/docker-rollout/releases/download/$version/docker-rollout"
if ! printf '%s %s\n' "$checksum" "$tool.download" | sha256sum -c - >/dev/null 2>&1; then
rm -f "$tool.download"
echo "docker-rollout $version: checksum mismatch, not used" >&2
exit 1
fi
mv "$tool.download" "$tool"
fi
docker compose build api
docker compose up --no-start --no-deps --force-recreate migrate
# Run through sh: Windows cannot use the script as a docker CLI plugin.
if ! sh "$tool" rollout --wait-after-healthy 4 api; then
# A failed migration stops the scale-up after the new containers were
# created but before they started; remove them for a clean next attempt.
created=$(docker compose ps -aq --status created api)
if [ -n "$created" ]; then
docker rm $created >/dev/null
fi
exit 1
fi
+5
View File
@@ -0,0 +1,5 @@
@echo off
rem Windows entry point of scripts/stop-one.sh: tests/resilience.py starts the
rem hook without a shell, and Windows cannot execute a .sh file directly.
sh "%~dp0stop-one.sh"
exit /b %errorlevel%
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Failover hook of `make test-failover` (tests/resilience.py): stops the one
# API replica whose X-Instance-Id is $TARGET_INSTANCE_ID and leaves it
# stopped. The stop is graceful: on SIGTERM the replica turns unready, keeps
# serving for its drain delay while HAProxy takes it out of rotation, then
# exits; `docker stop` returns once it has. Nothing else is touched, and an
# alias that does not name exactly one running replica stops nothing.
# Restore the replica with: docker compose start api
set -eu
cd "$(dirname "$0")/.."
target=${TARGET_INSTANCE_ID:-}
case "$target" in
'' | *[!0-9a-f]*)
echo "TARGET_INSTANCE_ID must be the 16 lowercase hex characters of an X-Instance-Id" >&2
exit 2
;;
esac
if [ ${#target} -ne 16 ]; then
echo "TARGET_INSTANCE_ID must be the 16 lowercase hex characters of an X-Instance-Id" >&2
exit 2
fi
matches=$(sh scripts/api-instances.sh | awk -v t="$target" '$3 == "running" && $4 == t { print $1 }')
count=$(printf '%s\n' "$matches" | grep -c . || true)
if [ "$count" -ne 1 ]; then
echo "expected one running API replica with X-Instance-Id $target, found $count" >&2
exit 2
fi
docker stop "$matches" >/dev/null
echo "stopped API container $matches (X-Instance-Id $target)"