Files
mtusi2026lab3/infra/haproxy/haproxy.cfg
T
2026-10-13 19:11:11 +03:00

97 lines
5.9 KiB
INI
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HAProxy 3.0 — единственная публичная точка входа (порт 8080).
# Backend-адреса берутся из встроенного DNS Docker: имя сервиса `api` возвращает A-запись
# каждого работающего контейнера-реплики. Реплики не публикуют порты наружу.
global
log stdout format raw local0 info
maxconn 2048
# Встроенный DNS Docker. hold valid 2s — как часто перечитывается список реплик
# (новые контейнеры при scale/rolling update появляются в пуле за ≤ 2–3 s).
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold other 2s
hold refused 2s
hold nx 2s
hold timeout 2s
hold obsolete 2s
accepted_payload_size 8192
defaults
mode http
log global
option httplog
option dontlognull
# Таймауты согласованы с приложением:
# connect 1s — недоступная реплика быстро даёт ошибку соединения -> retry на другую;
# server 10s — больше statement_timeout БД (5 s) + ожидания пула (3 s);
# http-keep-alive 10s < timeout_keep_alive uvicorn (30 s): LB закрывает простой первым.
timeout connect 1s
timeout client 30s
timeout server 10s
timeout http-request 10s
timeout http-keep-alive 10s
timeout queue 5s
retries 2
option redispatch 1
frontend http_in
bind :8080
# X-Request-Id создаётся на входе (если клиент не прислал корректный), передаётся в API
# и попадает в лог LB — один ID в логах LB и реплики.
unique-id-format %{+X}o\ %ci:%cp_%fi:%fp_%Ts_%rt:%pid
acl has_valid_rid req.hdr(X-Request-Id) -m reg ^[A-Za-z0-9._:-]{1,128}$
http-request set-header X-Request-Id %[unique-id] unless has_valid_rid
http-request set-var(txn.rid) req.hdr(X-Request-Id)
log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.rid)] \"%HM %HPO\""
default_backend api
# Ошибки, созданные самим LB (нет живых реплик / timeout), — в формате контракта.
http-error status 502 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Нет доступных реплик API\",\"request_id\":\"%[var(txn.rid)]\"}}" hdr X-Request-Id "%[var(txn.rid)]"
http-error status 503 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Нет доступных реплик API\",\"request_id\":\"%[var(txn.rid)]\"}}" hdr X-Request-Id "%[var(txn.rid)]"
http-error status 504 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Реплика API не ответила вовремя\",\"request_id\":\"%[var(txn.rid)]\"}}" hdr X-Request-Id "%[var(txn.rid)]"
backend api
# Обычный round-robin без sticky session: корректность обеспечивает общее состояние в PostgreSQL.
balance roundrobin
# Активная проверка готовности каждые 1 s; 2 неудачи подряд -> DOWN, 2 успеха -> UP.
# Максимальное время обнаружения отказа «процесс жив, но не готов»:
# inter × fall + timeout check = 1 s × 2 + 1 s ≈ 3 s.
# Упавший процесс (connection refused) обнаруживается быстрее: observe layer4 + error-limit 1
# переводит сервер в DOWN по первой реальной ошибке соединения, а запрос уходит на другую реплику.
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 observe layer4 error-limit 1 on-error mark-down resolvers docker init-addr none resolve-prefer ipv4 check
timeout check 1s
# Повторы на другую реплику:
# - ошибка установления соединения повторяется всегда (запрос не дошёл до приложения);
# - L7-повторы (пустой ответ / 503 от дренирующейся реплики) разрешены только для
# безопасных GET и для POST сообщения С Idempotency-Key — его повтор не создаст дубль.
# POST /users, /chats, /auth/sessions после отправки не повторяются (нет ключа идемпотентности).
retry-on conn-failure empty-response 503
acl is_message_post path_reg ^/api/v1/chats/[^/]+/messages$
acl has_idem_key req.hdr(Idempotency-Key) -m found
http-request disable-l7-retry if METH_POST !is_message_post
http-request disable-l7-retry if METH_POST !has_idem_key
http-request disable-l7-retry if METH_DELETE
# До 8 реплик (scale/rolling update); пустые слоты остаются в MAINT, пока DNS не вернёт адрес.
server-template api 8 api:8080
# Служебная страница состояния backend-ов (UP/DOWN, счётчики ошибок/повторов).
# В compose.yaml публикуется только на 127.0.0.1 хоста — не часть публичного API.
frontend stats
bind :8404
http-request return status 200 content-type text/plain string "ok" if { path /lb-health }
stats enable
stats uri /stats
stats refresh 2s
stats show-legends