Files
mtusi2026lab6/infra/otel/prometheus/rules.yml
T
ricoromaandClaude Opus 5.5 ef60b47246 fix: address slo-alerts verify findings
Count the first SDK telemetry loss on the loss panel, print pending
moments on every alerts-check step, check the loss panel on a quiet
stand, align two scenarios and the SLI cross-check text with what the
driver verifies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 04:08:13 +03:00

191 lines
12 KiB
YAML
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.
# Правила Prometheus стенда (design change slo-alerts): правила записи SLI и
# SLO (решение 1), учёт потерь телеметрии (решение 9) и оповещения (решения 3,
# 4). Вычисляет Prometheus; доставки наружу нет — состояние firing / resolved:
# /api/v1/rules, /api/v1/alerts, ряды ALERTS и Grafana (правила источника
# prometheus только для чтения, панель истории). Модульные тесты —
# rules.test.yml (make alerts_test). У каждого оповещения — локальный runbook
# infra/otel/runbooks/<имя>.md.
#
# SLI (окно SLO — скользящие 7 суток, срок хранения Prometheus):
# доступность — ответы публичного frontend LB (entry) не 5xx, вместе с 502,
# 503 и 504 самого LB; SLO 99,5 %;
# задержка — «лёгкие» запросы API без 5xx не дольше 0,25 с; SLO 99 %.
# Не «лёгкие» — регистрация и вход (KDF, тот же шаблон у DELETE
# /api/v1/users), загрузка и скачивание байтов вложения; запросы без
# маршрута (404 неизвестного пути) входят;
# время до ready — вложение ready без replay не позже 30 с от устойчивого
# приёма; SLO 99 %.
# SLI окна W — sum_over_time(good[W]) / sum_over_time(total[W]) по рядам
# группы messenger-slo (для доступности — 1 − bad / total); остаток бюджета —
# (SLI − SLO) / (1 − SLO).
groups:
# окна оповещений и панелей — 2 мин (8 сборов при 15 с)
- name: messenger-sli
interval: 15s
rules:
- record: messenger:lb_http_responses:rate2m
expr: sum(rate(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry"}[2m]))
- record: messenger:lb_http_errors:rate2m
expr: sum(rate(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry",code="5xx"}[2m]))
- record: messenger:lb_http_errors:ratio_rate2m
expr: messenger:lb_http_errors:rate2m / messenger:lb_http_responses:rate2m
- record: messenger:http_light_requests:rate2m
expr: >-
sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[2m]))
- record: messenger:http_light_fast:rate2m
expr: >-
sum(rate(http_server_request_duration_seconds_bucket{job="messenger-api",le="0.25",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[2m]))
- record: messenger:http_light_slow:ratio_rate2m
expr: 1 - messenger:http_light_fast:rate2m / messenger:http_light_requests:rate2m
# потери телеметрии по процессу (решение 9): Collector — отказ приёма
# (memory_limiter), очередь экспорта полна, повторы истекли; SDK API,
# worker и relay — отброшено из-за полной очереди и неудачные отправки.
# Сумма, а не increase(): ряд отказов появляется с первой потерей, у
# метрик Collector нет времени начала — первое значение нового ряда
# целиком рост. Третья часть — ноль процесса SDK по ряду ёмкости очереди
# span (есть с запуска): ряд суммы начинается с нуля, и rate() панели
# потерь видит первую потерю (verify W1; у Collector ряды
# otelcol_receiver_refused_* есть с нуля с его старта)
- record: telemetry:lost_items:total
expr: >-
sum by (job, instance) ({__name__=~"otelcol_(receiver_refused|exporter_send_failed|exporter_enqueue_failed)_(spans|log_records|metric_points)"})
or
sum by (job, instance) ({__name__=~"otel_sdk_(processor|exporter)_(span|log)_(processed|exported)_total",error_type!=""})
or
sum by (job, instance) (otel_sdk_processor_span_queue_capacity) * 0
# приращения событий SLI за непересекающиеся 5-минутные окна: SLI любого
# окна — отношение сумм, без чтения 7 суток histogram на каждое обновление
- name: messenger-slo
interval: 5m
rules:
- record: messenger:slo_availability_bad:increase5m
expr: sum(increase(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry",code="5xx"}[5m]))
- record: messenger:slo_availability_total:increase5m
expr: sum(increase(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry"}[5m]))
- record: messenger:slo_latency_good:increase5m
expr: >-
sum(increase(http_server_request_duration_seconds_bucket{job="messenger-api",le="0.25",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[5m]))
- record: messenger:slo_latency_total:increase5m
expr: >-
sum(increase(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[5m]))
- record: messenger:slo_time_to_ready_good:increase5m
expr: sum(increase(messenger_job_time_to_ready_seconds_bucket{job="messenger-worker",le="30.0"}[5m]))
- record: messenger:slo_time_to_ready_total:increase5m
expr: sum(increase(messenger_job_time_to_ready_seconds_count{job="messenger-worker"}[5m]))
# оповещения о сервисе: пороги — 10 × допустимой доли SLO, шум отсекают for
# и порог трафика 0,1 запроса/с (не меньше 12 запросов за окно)
- name: messenger-alerts
interval: 15s
rules:
- alert: MessengerHighErrorRate
expr: messenger:lb_http_errors:ratio_rate2m > 0.05 and messenger:lb_http_responses:rate2m > 0.1
for: 1m
labels:
severity: critical
annotations:
summary: High share of 5xx responses to clients on the load balancer
description: >-
{{ $value | humanizePercentage }} of responses of the public frontend
in the last 2 minutes are 5xx (threshold 5 %, SLO 99.5 %), including
responses generated by the load balancer itself. Runbook:
infra/otel/runbooks/MessengerHighErrorRate.md
runbook_url: infra/otel/runbooks/MessengerHighErrorRate.md
- alert: MessengerSlowRequests
expr: messenger:http_light_slow:ratio_rate2m > 0.1 and messenger:http_light_requests:rate2m > 0.1
for: 1m
labels:
severity: warning
annotations:
summary: Many light API requests are slower than 0.25 s
description: >-
{{ $value | humanizePercentage }} of light API requests without 5xx
in the last 2 minutes took longer than 0.25 s (threshold 10 %, SLO
99 %); login, registration and attachment bytes are not counted.
Runbook: infra/otel/runbooks/MessengerSlowRequests.md
runbook_url: infra/otel/runbooks/MessengerSlowRequests.md
- alert: MessengerNoReadyReplicas
expr: max(haproxy_backend_active_servers{job="haproxy",proxy="api"}) < 1
for: 30s
labels:
severity: critical
annotations:
summary: No API replica is ready behind the load balancer
description: >-
The load balancer sees {{ $value }} ready API replicas: clients get
503 from the load balancer. Fires without traffic too. Runbook:
infra/otel/runbooks/MessengerNoReadyReplicas.md
runbook_url: infra/otel/runbooks/MessengerNoReadyReplicas.md
- alert: MessengerQueueLagHigh
expr: max(messenger_queue_oldest_age_seconds{job="messenger-relay"}) > 60
for: 1m
labels:
severity: warning
annotations:
summary: The oldest unfinished attachment job is older than 60 s
description: >-
The oldest unfinished job waits {{ $value | humanizeDuration }}
(threshold 60 s, time to ready SLO 30 s). Runbook:
infra/otel/runbooks/MessengerQueueLagHigh.md
runbook_url: infra/otel/runbooks/MessengerQueueLagHigh.md
- alert: MessengerQueueMetricsMissing
# снимка очереди relay нет (relay остановлен или не читает PostgreSQL),
# и MessengerQueueLagHigh слеп; при недоступном экспортёре Collector
# молчит — там срабатывает TelemetryTargetDown
expr: absent(messenger_queue_oldest_age_seconds{job="messenger-relay"}) unless on() (up{job="otel-collector-exporter"} == 0)
for: 2m
labels:
severity: warning
# $value у absent() — всегда 1; текущее значение в описании — возраст
# последнего снимка за час (verify S3)
annotations:
summary: The relay queue snapshot is missing
description: >-
There is no queue depth and age snapshot of the relay while the
Collector exporter is up (last snapshot {{ with query `time() -
max(max_over_time(timestamp(messenger_queue_oldest_age_seconds{job="messenger-relay"})[1h:15s]))`
}}{{ . | first | value | humanizeDuration }} ago{{ else }}more
than an hour ago{{ end }}): the relay is stopped or cannot read
PostgreSQL, and MessengerQueueLagHigh is blind. Runbook:
infra/otel/runbooks/MessengerQueueMetricsMissing.md
runbook_url: infra/otel/runbooks/MessengerQueueMetricsMissing.md
# оповещения о самом конвейере телеметрии
- name: telemetry-alerts
interval: 15s
rules:
- alert: TelemetryTargetDown
expr: up{job=~"otel-collector|loki|tempo|haproxy"} == 0
for: 1m
labels:
severity: warning
annotations:
summary: 'Metrics target {{ $labels.job }} is down'
# $value — up цели (0); рядом — сколько целей правила недоступно
# сейчас (verify S3)
description: >-
Prometheus cannot scrape {{ $labels.job }} ({{ $labels.instance }})
for a minute (up {{ $value }}; targets of the rule down now: {{
with query `count(up{job=~"otel-collector|loki|tempo|haproxy"} ==
0)` }}{{ . | first | value }}{{ else }}0{{ end }}); with job
haproxy the load balancer metrics are missing and
MessengerHighErrorRate is blind. Runbook:
infra/otel/runbooks/TelemetryTargetDown.md
runbook_url: infra/otel/runbooks/TelemetryTargetDown.md
- alert: TelemetryDataLoss
# рост суммы потерь процесса за 2 мин; новый ряд — целиком рост, сброс
# суммы (рестарт Collector) — отрицательный, оповещения нет
expr: telemetry:lost_items:total - (telemetry:lost_items:total offset 2m or telemetry:lost_items:total * 0) > 0
labels:
severity: warning
annotations:
summary: 'Telemetry of {{ $labels.job }} is being lost'
description: >-
{{ $labels.job }} ({{ $labels.instance }}) lost {{ $value }} spans,
log records or metric points in the last 2 minutes (full queue,
failed export or refused by the memory limiter). Runbook:
infra/otel/runbooks/TelemetryDataLoss.md
runbook_url: infra/otel/runbooks/TelemetryDataLoss.md