Реализовать уровень 4: сквозные трассы, SLO, отказы и отчёт

This commit is contained in:
2026-11-21 12:18:33 +03:00
parent d0a062e2d2
commit 12181fa893
69 changed files with 52258 additions and 47 deletions
+753 -3
View File
@@ -1,13 +1,13 @@
{
"uid": "messenger-lab6",
"title": "Messenger lab6 - Observability",
"description": "Application OTLP metrics, structured logs and traces. HTTP error ratio is business 5xx / all business responses; health excluded. Duration units are seconds. All API replicas are aggregated.",
"description": "Application OTLP metrics, structured logs and traces. HTTP error ratio is business 5xx / all business responses; health excluded. Duration units are seconds. All API replicas are aggregated. Grade 4: histogram percentiles, durable queue age/depth, pool/acquisition pressure, worker saturation, process CPU/RAM, ready latency, 5-minute SLIs and local alerts. See infra/otel/RUNBOOK.md.",
"tags": [
"lab6",
"opentelemetry"
],
"schemaVersion": 39,
"version": 1,
"version": 2,
"editable": false,
"timezone": "browser",
"refresh": "5s",
@@ -74,7 +74,7 @@
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\",status_class=\"5xx\"}[$__rate_interval])) / clamp_min(sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\"}[$__rate_interval])), 1e-9)",
"expr": "(sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\",status_class=\"5xx\"}[$__rate_interval])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\"}[$__rate_interval])), 1e-9)",
"legendFormat": ""
}
],
@@ -317,6 +317,756 @@
"options": {
"showHeader": true
}
},
{
"id": 9,
"type": "timeseries",
"title": "API duration p50 / p95 / p99 (seconds)",
"description": "Percentiles from aggregated histogram buckets across all API replicas. Never an average of replica percentiles.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 41,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[$__rate_interval])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[$__rate_interval])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[$__rate_interval])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 10,
"type": "timeseries",
"title": "Worker duration p50 / p95 / p99 (seconds)",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 41,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_jobs_duration_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_jobs_duration_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_jobs_duration_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 11,
"type": "timeseries",
"title": "Durable unfinished jobs (count)",
"description": "Authoritative PostgreSQL backlog, including pending outbox and delayed retries; not RabbitMQ ready count.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 49,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_depth{service_name=\"messenger-publisher\"})",
"legendFormat": "queued + processing"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 12,
"type": "timeseries",
"title": "Oldest unfinished job / observer sample age (seconds)",
"description": "A sample older than 10 seconds is stale. Oldest age differs from processing latency.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 49,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_oldest_age_seconds{service_name=\"messenger-publisher\"})",
"legendFormat": "oldest unfinished"
},
{
"refId": "B",
"expr": "max(messenger_queue_sample_age_seconds{service_name=\"messenger-publisher\"})",
"legendFormat": "sample age"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 15
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 13,
"type": "timeseries",
"title": "DB pool used / capacity (connections)",
"description": "Bounded SQLAlchemy pool by process, max size includes overflow.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 57,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "messenger_db_pool_used",
"legendFormat": "used {{service_name}} {{service_instance_id}}"
},
{
"refId": "B",
"expr": "messenger_db_pool_capacity",
"legendFormat": "capacity {{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 14,
"type": "timeseries",
"title": "DB acquisitions in progress (requests)",
"description": "Acquisitions in progress include waiting for a pool slot and opening a new DB connection. They are not active SQL queries.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 57,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "messenger_db_pool_waiting",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 15,
"type": "timeseries",
"title": "Worker saturation (busy / capacity)",
"description": "Busy / capacity for workers with heartbeat younger than 15 seconds. Zero live capacity gives no ratio; do not interpret absence as successful operation.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 65,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "(sum(messenger_worker_busy{service_name=\"messenger-worker\"} and on(service_instance_id) (time() - messenger_worker_heartbeat_seconds{service_name=\"messenger-worker\"} < 15)) or vector(0)) / (sum(messenger_worker_capacity{service_name=\"messenger-worker\"} and on(service_instance_id) (time() - messenger_worker_heartbeat_seconds{service_name=\"messenger-worker\"} < 15)) or vector(0))",
"legendFormat": "saturation"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 16,
"type": "timeseries",
"title": "Worker busy / capacity (jobs)",
"description": "Sum only worker process instances with heartbeat younger than 15 seconds; old cached resources after crashes do not count.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 65,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum(messenger_worker_busy{service_name=\"messenger-worker\"} and on(service_instance_id) (time() - messenger_worker_heartbeat_seconds{service_name=\"messenger-worker\"} < 15)) or vector(0)",
"legendFormat": "busy"
},
{
"refId": "B",
"expr": "sum(messenger_worker_capacity{service_name=\"messenger-worker\"} and on(service_instance_id) (time() - messenger_worker_heartbeat_seconds{service_name=\"messenger-worker\"} < 15)) or vector(0)",
"legendFormat": "capacity"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 17,
"type": "timeseries",
"title": "Application CPU (cores)",
"description": "CPU seconds / second = cores used by the Python application process. Worker image subprocess CPU is outside this process signal; container limits apply separately.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 73,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "rate(messenger_process_cpu_seconds_total[$__rate_interval])",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 18,
"type": "timeseries",
"title": "Application resident RAM (bytes)",
"description": "Current resident memory of the Python application process; excludes the separate image subprocess.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 73,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "messenger_process_memory_bytes",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 19,
"type": "timeseries",
"title": "Acceptance to ready p50 / p95 / p99 (seconds)",
"description": "From durable attachment acceptance timestamp to COMMIT ready, including queue wait and retries. Only completed ready jobs enter this histogram.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 81,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[$__rate_interval])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 20,
"type": "timeseries",
"title": "API availability SLI / SLO (5 minutes)",
"description": "5-minute demonstration window. Health excluded, client 4xx not service failure. No traffic gives no SLI value; lower is worse.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 81,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "1 - (sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\",status_class=\"5xx\"}[5m])) or vector(0)) / sum(rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\"}[5m]))",
"legendFormat": "non-5xx / all business"
},
{
"refId": "B",
"expr": "vector(0.99)",
"legendFormat": "SLO 99%"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 21,
"type": "timeseries",
"title": "Ready within 60 seconds SLI / SLO (5 minutes)",
"description": "Conditional SLI over completed ready jobs. Missing completions produce no successful SLI. Inspect unfinished queue and failed attempts alongside this chart.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 89,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\",le=\"60\"}[5m])) / sum(rate(messenger_attachment_time_to_ready_seconds_count{service_name=\"messenger-worker\"}[5m]))",
"legendFormat": "ready <=60s / ready"
},
{
"refId": "B",
"expr": "vector(0.95)",
"legendFormat": "SLO 95%"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 22,
"type": "timeseries",
"title": "Local alert state: pending / firing",
"description": "A series at 1 indicates pending or firing. No series means inactive/resolved. Evaluate rules at http://localhost:9090/alerts; for=10s, rule interval=5s.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 89,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"MessengerHighErrorRate|MessengerQueueLag\"}",
"legendFormat": "{{alertname}} {{alertstate}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 23,
"type": "timeseries",
"title": "Collector queue occupancy (batches)",
"description": "Bounded in-memory sending queue: 256 batches per traces/logs exporter. Retries expire after 30 seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 97,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size{exporter=~\"otlphttp/.*\"}",
"legendFormat": "{{exporter}} size"
},
{
"refId": "B",
"expr": "otelcol_exporter_queue_capacity{exporter=~\"otlphttp/.*\"}",
"legendFormat": "{{exporter}} capacity"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
},
{
"id": 24,
"type": "timeseries",
"title": "Collector failed export attempts / second",
"description": "Failed export attempts can include retries; they do not directly count distinct lost events. See evidence and runbook for outage loss accounting.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 97,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "rate(otelcol_exporter_send_failed_spans[$__rate_interval])",
"legendFormat": "spans {{exporter}}"
},
{
"refId": "B",
"expr": "rate(otelcol_exporter_send_failed_log_records[$__rate_interval])",
"legendFormat": "logs {{exporter}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "multi"
}
}
}
],
"annotations": {
@@ -18,7 +18,8 @@ datasources:
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"trace_id"\s*:\s*"([0-9a-f]{32})"'
matcherType: label
matcherRegex: '^trace_id$'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
@@ -32,8 +33,10 @@ datasources:
datasourceUid: loki
spanStartTimeShift: -5m
spanEndTimeShift: 5m
filterByTraceID: true
filterByTraceID: false
filterBySpanID: false
customQuery: true
query: '{$${__tags}} | trace_id="$${__span.traceId}"'
tags: [{ key: service.name, value: service_name }]
nodeGraph:
enabled: true
+16 -4
View File
@@ -1,7 +1,19 @@
# Конфигурация наблюдаемости — реализовать
# Наблюдаемость lab6
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
`API / publisher / worker → OTLP HTTP → Collector → Prometheus / Loki / Tempo → Grafana`.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
* [Collector](collector.yaml): OTLP receivers, memory limiter, bounded batch,
sending queues и retry. Collector доступен только во внутренней сети Compose.
* [Prometheus](../prometheus/prometheus.yaml) хранит метрики приложения и самого
Collector; [alerts](../prometheus/alerts.yaml) оцениваются каждые 5 секунд.
* [Loki](../loki/loki.yaml) принимает native OTLP logs; технические ID —
structured metadata, не индексные labels.
* [Tempo](../tempo/tempo.yaml) хранит реальные API/producer/consumer spans.
* [Grafana](../grafana/provisioning/datasources/datasources.yaml) подключает
три datasource; [dashboard](../grafana/dashboards/messenger.json) импортируется
provisioning автоматически. Backend ports и Grafana опубликованы на loopback.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Сценарии диагностики и точные SLI/SLO: [RUNBOOK](RUNBOOK.md).
Запуск, семантика метрик, результаты и ограничения: [отчёт](../../REPORT.md).
Воспроизводимая проверка с evidence: `python -X utf8 scripts/test_lab6.py --incidents`.
Подробные сценарии находятся в `scripts/observe_lab6.py`.
+99
View File
@@ -0,0 +1,99 @@
# Диагностика стенда lab6
Правила предназначены для локального учебного стенда и синтетической нагрузки.
Пороги 15 секунд и `for: 10s` сокращены для демонстрации, а не выведены из
производственной статистики. Alert оценивается Prometheus каждые 5 секунд.
Firing и последующее отсутствие активного alert сохраняет сценарий проверки;
внешняя доставка уведомлений не требуется.
## SLI и SLO
- Доступность API: доля бизнес-ответов с кодом ниже 500 среди всех
бизнес-ответов. `/health/*` исключается, 4xx считаются доступным сервисом.
Учебный SLO: не менее 99% в скользящем окне 5 минут.
- Готовность вложения: доля завершений `ready` с временем не более 60 секунд
от устойчивого принятия до COMMIT `ready`. SLO: не менее 95% в окне 5 минут.
Доля вычисляется по `messenger_attachment_time_to_ready_seconds_bucket{le="60"}`
и `_count`; незавершённые и failed задачи отдельно видны в backlog/errors.
Поэтому этот SLI условен по успешным завершениям и один не доказывает,
что 95% всех принятых загрузок достигают ready. При остановленном worker
отсутствие завершений не интерпретируется как выполненный SLO.
- Percentile считается `histogram_quantile` после `sum by (le)` bucket rate
всех нужных реплик. Средние p95 отдельных реплик не усредняются.
## API errors
Ссылка alert: `MessengerHighErrorRate`.
1. Открыть Grafana `http://localhost:3000`, dashboard **Messenger lab6**.
Проверить интервал инцидента, RPS и 5xx ratio. Ошибки входа 401 и
недоступность PostgreSQL 503 отвечают на разные вопросы.
2. Выбрать ошибочный API trace из Tempo и связанный структурный лог по
`trace_id`; `request_id` связывает лог с `X-Request-Id` ответа.
3. Найти DB span: ошибка соединения или большая длительность DB при
коротком handler указывает на зависимость. Сравнить pool used/waiting
и DB operation duration. В spans нет текста SQL и параметров.
Если DB spans быстрые, искать время между ними/в handler, S3 или
ожидание свободного ресурса; одно значение p95 причины не устанавливает.
4. Проверить `docker compose ps db api`. В контролируемом сценарии
`docker compose stop db` ожидаются отказы синхронного пути и readiness.
HAProxy может вернуть собственный 503, не попадающий в счётчик API:
сценарий диагностики должен сохранять также прямой ответ API.
5. Восстановить `docker compose start db`, дождаться API ready, повторить
запросы. В Prometheus `http://localhost:9090/alerts` alert сначала
становится inactive после выхода ошибок из окна 1 минуты.
Сохранять ответ без токена, trace JSON, лог, запросы метрик и состояние alert
до воздействия, во время и после. Не считать текст ошибки DB в stdout
единственным доказательством причины: нужны сохранённые сигналы приложения.
## Queue lag
Ссылка alert: `MessengerQueueLag`.
1. Сравнить queue depth, oldest age, свежесть наблюдения, busy/capacity worker,
успешные/ошибочные jobs и длительность попыток. Backlog измерен по
устойчивым незавершённым заданиям PostgreSQL, включая outbox и retry;
это не только число сообщений ready в RabbitMQ.
2. Если depth > 0 и возраст растёт при отсутствии завершений и busy=0,
проверить `docker compose ps worker publisher broker`. Остановка worker
не останавливает publisher-наблюдатель.
3. Если busy=capacity, искать медленные DB/S3/image spans в worker trace.
Если растут retry/errors, найти соответствующий consumer span и событие
retry. По traceparent пройти producer → consumer → DB/S3, включая попытки.
4. Контролируемое воздействие: `docker compose stop worker`, затем несколько
upload стандартного fixture. Ответ 202 означает устойчивое принятие;
рост oldest age и firing ожидаются через 15 секунд плюс `for` и интервалы
сбора/оценки. Счётчик duration не заменяет возраст ожидающей задачи.
5. Восстановить `docker compose start worker`. Дождаться ready вложений,
depth=0 и inactive alert. Скачать original и thumbnail, проверить байты
и размеры. Уменьшение backlog само по себе ещё не доказывает сохранность.
Sample age защищает от интерпретации устаревшей очереди как свежей. Если DB
недоступна и sample age растёт, сначала расследовать DB; автоматически
приписывать это остановленному worker нельзя.
## Недоступен backend telemetry
1. Перед воздействием сохранить Collector exporter queue/failed counters,
память API/worker/Collector и контрольное сообщение/вложение.
2. `docker compose stop tempo loki` отключает хранилища traces/logs.
Prometheus остаётся включённым и сохраняет self metrics Collector:
очередь, ошибки отправки и память. Отдельно проверить недоступность
Collector, если нужно исследовать именно переполнение SDK.
3. Продолжать бизнес-запросы и загрузки. Проверить 201 сообщений, 202 → ready
вложений и чтение данных. Telemetry отсутствует в readiness; зависимость
от неё не должна отбирать все API из балансировки.
4. Collector: memory limiter 192 MiB, spike 48 MiB, batch максимум 512,
sending queue максимум 256 batches на exporter, 2 consumers; timeout 3s,
retry не более 30s на batch. После исчерпания retries данные отбрасываются.
SDK также имеет конечные очереди и timeout; экспорт выполняется фоново.
Ограничения RAM контейнеров — дополнительный предел, а не замена очередям.
5. `docker compose start tempo loki`; дождаться backend ready и повторить
контрольный запрос. Новые trace/log должны появиться. Часть старых
сигналов может потеряться: сохранённый рост failed/dropped counters и
границы измерения описываются в отчёте. Нельзя обещать полное восстановление
telemetry после перезапуска Collector: его очереди находятся в памяти.
Команды `docker compose down` сохраняют volumes. `down -v` удаляет учебные
данные и историю, для восстановления после инцидента эта команда не нужна.
+32
View File
@@ -0,0 +1,32 @@
groups:
- name: messenger-lab6
interval: 5s
rules:
- alert: MessengerHighErrorRate
expr: |
(
sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[1m]))
/
clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[1m])), 1e-9)
) > 0.05
for: 10s
labels:
severity: warning
annotations:
summary: "Business API 5xx ratio exceeds 5%"
description: "5xx / all business HTTP responses over 1 minute, continuously above 5% for 10 seconds. Health and client 4xx are not failures in this SLI."
runbook: "infra/otel/RUNBOOK.md#api-errors"
- alert: MessengerQueueLag
expr: |
max(messenger_queue_oldest_age_seconds{service_name="messenger-publisher"}) > 15
and
max(messenger_queue_depth{service_name="messenger-publisher"}) > 0
and
max(messenger_queue_sample_age_seconds{service_name="messenger-publisher"}) < 10
for: 10s
labels:
severity: warning
annotations:
summary: "Oldest unfinished attachment job exceeds 15 seconds"
description: "Durable PostgreSQL backlog is nonempty and oldest job age is above 15 seconds for 10 seconds; the observer sample is less than 10 seconds old. This is queue age, not worker processing duration."
runbook: "infra/otel/RUNBOOK.md#queue-lag"
+3
View File
@@ -2,6 +2,9 @@ global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/alerts.yaml
scrape_configs:
- job_name: messenger
static_configs: