2 Commits
8 changed files with 159 additions and 9 deletions
+1
View File
@@ -434,6 +434,7 @@ services:
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin}
volumes:
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
- ./infra/grafana/provisioning/alerting:/etc/grafana/provisioning/alerting:ro
- grafana-data:/var/lib/grafana
ports:
- "127.0.0.1:3000:3000"
@@ -0,0 +1,13 @@
apiVersion: 1
contactPoints:
- orgId: 1
name: messenger-local
receivers:
- uid: messenger-local-webhook
type: webhook
disableResolveMessage: false
settings:
# Доставка наружу не требуется; локальный no-op endpoint.
url: http://127.0.0.1:9/messenger-alerts
httpMethod: POST
@@ -0,0 +1,9 @@
apiVersion: 1
policies:
- orgId: 1
receiver: messenger-local
group_by: ['alertname']
group_wait: 10s
group_interval: 1m
repeat_interval: 4h
@@ -0,0 +1,109 @@
apiVersion: 1
groups:
- orgId: 1
name: messenger-alerts
folder: Messenger
interval: 1m
rules:
- uid: messenger-high-error-rate
title: MessengerHighErrorRate
condition: C
data:
- refId: A
relativeTimeRange:
from: 60
to: 0
datasourceUid: prometheus
model:
editorMode: code
expr: sum(rate(http_requests_total{http_status_class="5xx"}[1m])) / clamp_min(sum(rate(http_requests_total[1m])), 1e-9)
instant: true
intervalMs: 1000
maxDataPoints: 43200
range: false
refId: A
- refId: C
datasourceUid: __expr__
model:
conditions:
- evaluator:
params: [0.05]
type: gt
operator:
type: and
query:
params: [C]
reducer:
params: []
type: last
type: query
datasource:
type: __expr__
uid: __expr__
expression: A
intervalMs: 1000
maxDataPoints: 43200
refId: C
type: threshold
for: 30s
annotations:
summary: "API error rate > 5% over 1m"
description: "5xx ratio exceeds SLO 5% for 30 seconds."
runbook: "infra/runbooks/high-error-rate.md"
labels:
severity: warning
noDataState: NoData
execErrState: Error
isPaused: false
- uid: messenger-jobs-backlog-growing
title: MessengerJobsBacklogGrowing
condition: C
data:
- refId: A
relativeTimeRange:
from: 600
to: 0
datasourceUid: prometheus
model:
editorMode: code
expr: sum(increase(jobs_processed_total{outcome="retry"}[10m])) - sum(increase(jobs_processed_total{outcome="success"}[10m]))
instant: true
intervalMs: 1000
maxDataPoints: 43200
range: false
refId: A
- refId: C
datasourceUid: __expr__
model:
conditions:
- evaluator:
params: [5]
type: gt
operator:
type: and
query:
params: [C]
reducer:
params: []
type: last
type: query
datasource:
type: __expr__
uid: __expr__
expression: A
intervalMs: 1000
maxDataPoints: 43200
refId: C
type: threshold
for: 5m
annotations:
summary: "Retries outpace successes"
description: "Worker retry count exceeds successes by >5 for 5m."
runbook: "infra/runbooks/queue-lag.md"
labels:
severity: warning
noDataState: NoData
execErrState: Error
isPaused: false
+5 -5
View File
@@ -4,16 +4,16 @@ groups:
rules:
- alert: MessengerHighErrorRate
expr: |
sum(rate(http_requests_total{http_status_class="5xx"}[5m]))
sum(rate(http_requests_total{http_status_class="5xx"}[1m]))
/
sum(rate(http_requests_total[5m]))
sum(rate(http_requests_total[1m]))
> 0.05
for: 2m
for: 30s
labels:
severity: warning
annotations:
summary: "API error rate > 5% over 5m"
description: "5xx ratio exceeds SLO 5% for 2 minutes."
summary: "API error rate > 5% over 1m"
description: "5xx ratio exceeds SLO 5% for 30 seconds."
runbook: "infra/runbooks/high-error-rate.md"
- alert: MessengerJobsBacklogGrowing
+9 -3
View File
@@ -30,9 +30,15 @@ def readiness() -> Health:
main.py конвертирует его в 503 с телом Error из contracts/openapi.json.
Все проверки — с короткими таймаутами, чтобы не зависать надолго.
"""
with _db.connection() as conn, conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
try:
with _db.connection() as conn, conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
except Exception as exc: # noqa: BLE001
# Пул уже проверяет живость соединения (check_connection) и короткий
# timeout=3.0; здесь лишь превращаем любую ошибку БД в 503, чтобы
# после рестарта PostgreSQL readiness быстро возвращался в 200.
raise RuntimeError("db_unavailable: %s" % type(exc).__name__) from exc
# Redis (в режиме redis)
if _store() == "redis":
_redis_client().ping()
+3
View File
@@ -200,6 +200,9 @@ async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError
async def runtime_error_handler(request: Request, exc: RuntimeError):
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
text = str(exc)
if "db_unavailable" in text:
logger.error("event=db_unavailable request_id=%s", request_id)
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
if "redis_unavailable" in text:
logger.error("event=redis_unavailable request_id=%s", request_id)
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
+10 -1
View File
@@ -25,8 +25,17 @@ def init_pool() -> None:
conninfo=_dsn(),
min_size=2,
max_size=10,
timeout=5.0,
# Короткий таймаут получения соединения из пула: readiness/бизнес-запрос
# при мёртвой БД должен быстро вернуть 503, а не висеть.
timeout=3.0,
max_idle=300.0,
# check: перед выдачей соединения проверяем его живость; мёртвые
# соединения после рестарта PostgreSQL отбрасываются, пул сам
# открывает новые — readiness восстанавливается без рестарта API.
check=ConnectionPool.check_connection,
# Раз в 30с фоновый worker пула добивает min_size живыми соединениями,
# чтобы после старта БД готовность вернулась в пределах окна теста.
reconnect_timeout=30.0,
kwargs={"options": "-c statement_timeout=5000"},
open=True,
)