Files
mtusi2026lab4/infra/haproxy/haproxy.cfg
T

72 lines
4.2 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.
global
log stdout format raw local0 info
maxconn 2000
defaults
mode http
log global
# в лог не попадают query string и заголовки: только путь, код, тайминги и выбранный сервер
log-format "%ci %HM %HPO status=%ST server=%s retries=%rc Tq=%TR Tw=%Tw Tc=%Tc Tr=%Tr Ta=%Ta"
# новое соединение с API на каждый запрос: остановленная реплика сразу видна как отказ соединения,
# а такой запрос до приложения не дошёл, поэтому его безопасно отправить на другую
option http-server-close
retries 2
retry-on conn-failure
option redispatch 1
timeout connect 1s
timeout http-request 10s
timeout queue 3s
# больше самого долгого ответа API: очередь на запись 10 с + S3 7 с + база и Redis по 1-2 с
timeout server 20s
timeout client 30s
timeout http-keep-alive 30s
timeout check 1s
# запрос, который не удалось разобрать: своего id у него ещё нет, поэтому ответы готовые, в формате контракта
errorfile 400 /usr/local/etc/haproxy/errors/400.http
errorfile 408 /usr/local/etc/haproxy/errors/408.http
errorfile 414 /usr/local/etc/haproxy/errors/414.http
errorfile 431 /usr/local/etc/haproxy/errors/431.http
resolvers docker
nameserver dns 127.0.0.11:53
accepted_payload_size 8192
# DNS Docker убирает остановленные контейнеры и добавляет новые, список реплик обновляется сам
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold obsolete 0s
hold nx 2s
frontend api_in
bind *:8080
unique-id-format %[uuid(4)]
# грубый предел до API: файл 10 MiB проходит, точный лимит считает приложение
http-request deny deny_status 413 if { req.hdr_val(content-length) gt 11534336 }
default_backend api
# ответы самого балансировщика в формате ошибок контракта
http-error status 413 content-type application/json lf-string '{"error":{"code":"payload_too_large","message":"Слишком большое тело запроса","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 500 content-type application/json lf-string '{"error":{"code":"internal_error","message":"Внутренняя ошибка сервера","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
backend api
balance roundrobin
# без sticky session: любой запрос может уйти на любую реплику
option httpchk GET /health/ready
http-check expect status 200
# проверка раз в секунду, две неудачи подряд исключают реплику, две удачи возвращают
default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
# до 6 реплик; адреса приходят из DNS по имени сервиса
server-template api 1-6 api:8080
# только внутри контейнера lb, порт не опубликован
frontend internal
bind *:8404
monitor-uri /lb-health
stats enable
stats uri /stats
stats refresh 0
no log