feat: coordinate timeout chain and add failover load profile
HAProxy checks get fastinter 500ms and timeout check 2.5s (hung replica detected within 6.5 s), http-reuse never with uvicorn keep-alive 60 s so the LB closes idle replica connections, and app connections set idle_in_transaction_session_timeout so a frozen replica releases its idempotency key. The bench stand runs behind HAProxy with N replicas and gains the failover profile (make bench_failover / bench_failover_quick): constant-rate writes with a key and reads while each replica is stopped, killed or paused, with per-second timeline, detection and recovery time and write reconciliation. Driver commands idle-conns and hang-key check the keep-alive and hung-transaction decisions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,6 +8,7 @@ from pydantic import (
|
||||
BeforeValidator,
|
||||
Field,
|
||||
SecretStr,
|
||||
ValidationInfo,
|
||||
field_validator,
|
||||
)
|
||||
from pydantic_settings import (
|
||||
@@ -40,6 +41,12 @@ class App(BaseModel):
|
||||
# секунды, которые uvicorn ждёт текущие запросы после SIGTERM;
|
||||
# docker шлёт SIGKILL через 10 с, поэтому не больше 9
|
||||
graceful_shutdown_seconds: int = Field(default=8, ge=1, le=9)
|
||||
# секунды, которые uvicorn держит простаивающее keep-alive соединение.
|
||||
# Больше, чем HAProxy держит простаивающий сеанс клиента, а с ним и
|
||||
# соединение с репликой (timeout http-keep-alive 10 с и http-reuse
|
||||
# never в infra/haproxy/haproxy.cfg): закрывает LB, а не реплика, и
|
||||
# запрос не уходит в закрывающееся соединение
|
||||
keep_alive_seconds: int = Field(default=60, ge=1)
|
||||
# X-Instance-Id и поле instance_id журнала. Пусто — hostname процесса
|
||||
# (в compose — короткий ID контейнера). В config.toml, .env и compose
|
||||
# не задавать: эти источники общие у реплик, а значение должно
|
||||
@@ -88,6 +95,28 @@ class Database(BaseModel):
|
||||
# секунды на всю работу запроса с БД (asyncio): зависший сервер или
|
||||
# обрыв сети, где серверный таймаут не сработает
|
||||
request_timeout_seconds: float = Field(default=6, gt=0)
|
||||
# миллисекунды, серверный idle_in_transaction_session_timeout: открытую
|
||||
# транзакцию замороженной реплики PostgreSQL прерывает и снимает её
|
||||
# блокировки (ключ идемпотентности); 0 — без ограничения
|
||||
idle_in_transaction_timeout_ms: int = Field(default=10000, ge=0)
|
||||
|
||||
@field_validator("idle_in_transaction_timeout_ms")
|
||||
@classmethod
|
||||
def idle_longer_than_request(cls, value: int, info: ValidationInfo) -> int:
|
||||
"""Срок простоя транзакции больше срока работы запроса с БД.
|
||||
|
||||
Транзакция живого запроса дольше `request_timeout_seconds` не
|
||||
живёт: прерывать её PostgreSQL не должен. Проверка на поле, а не
|
||||
на секции: в ошибке валидатора секции было бы всё её значение,
|
||||
вместе с паролем.
|
||||
"""
|
||||
request = info.data.get("request_timeout_seconds")
|
||||
if value and request is not None and value <= request * 1000:
|
||||
raise ValueError(
|
||||
"must be 0 or greater than request_timeout_seconds in "
|
||||
"milliseconds",
|
||||
)
|
||||
return value
|
||||
|
||||
@property
|
||||
def url(self) -> URL:
|
||||
|
||||
+12
-4
@@ -37,6 +37,17 @@ class BoundedCloseConnection(asyncpg.Connection):
|
||||
|
||||
def create_engine(database: Database) -> AsyncEngine:
|
||||
"""Engine с ограниченным пулом и таймаутами из `[database]`."""
|
||||
server_settings = {
|
||||
"application_name": DB_APPLICATION_NAME,
|
||||
"statement_timeout": str(database.statement_timeout_ms),
|
||||
}
|
||||
if database.idle_in_transaction_timeout_ms:
|
||||
# транзакцию замороженного процесса (docker pause) PostgreSQL
|
||||
# прерывает сам: TCP-соединение живо, и иначе её блокировки, в
|
||||
# том числе ключа идемпотентности, держались бы до разморозки
|
||||
server_settings["idle_in_transaction_session_timeout"] = str(
|
||||
database.idle_in_transaction_timeout_ms,
|
||||
)
|
||||
return create_async_engine(
|
||||
database.url,
|
||||
pool_size=database.pool_size,
|
||||
@@ -55,10 +66,7 @@ def create_engine(database: Database) -> AsyncEngine:
|
||||
connect_args={
|
||||
"timeout": database.connect_timeout_seconds,
|
||||
"connection_class": BoundedCloseConnection,
|
||||
"server_settings": {
|
||||
"application_name": DB_APPLICATION_NAME,
|
||||
"statement_timeout": str(database.statement_timeout_ms),
|
||||
},
|
||||
"server_settings": server_settings,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -74,6 +74,9 @@ def main() -> None:
|
||||
# процесс
|
||||
workers=1,
|
||||
timeout_graceful_shutdown=settings.app.graceful_shutdown_seconds,
|
||||
# простаивающее соединение закрывает HAProxy раньше реплики
|
||||
# (design change graceful-failover, решение 3)
|
||||
timeout_keep_alive=settings.app.keep_alive_seconds,
|
||||
# логи uvicorn идут через наш JSON-форматтер (src/infra/logger.py)
|
||||
log_config=None,
|
||||
access_log=False,
|
||||
|
||||
Reference in New Issue
Block a user