Лаба6 - оценка 4 исправление
This commit is contained in:
@@ -11,76 +11,91 @@ groups:
|
||||
title: "Messenger: API 5xx error rate > 1%"
|
||||
condition: C
|
||||
for: 2m
|
||||
noDataState: NoData # реальные проблемы источника видны; idle-окно больше не даёт NoData
|
||||
execErrState: Alerting
|
||||
labels:
|
||||
severity: warning
|
||||
component: api
|
||||
annotations:
|
||||
summary: "Доля 5xx ответов API превысила 1% в окне 2 минуты."
|
||||
description: |
|
||||
SLI: 5xx / все HTTP-запросы. Окно 2m. Порог 0.01.
|
||||
SLI: 5xx / все HTTP-запросы. Окно 2m, порог 0.01.
|
||||
Выражение всегда возвращает число: при отсутствии 5xx или трафика — 0.
|
||||
runbook: |
|
||||
1. Откройте dashboard 'messenger-overview', панель 'HTTP 5xx error ratio'.
|
||||
2. Посмотрите 'HTTP latency p50/p95/p99': резкий рост p99 указывает
|
||||
на зависимый сервис (БД/S3).
|
||||
3. Найдите трассу с 5xx через Tempo: service.name=messenger-api,
|
||||
status.code=ERROR. В дочерних spans ищите db.client или
|
||||
s3.operation с ошибками.
|
||||
4. Проверьте логи Loki: {service_name="messenger-api"} |= "error".
|
||||
5. Отличите медленный DB handler от недоступной БД:
|
||||
- недоступная БД: много 'database unavailable', /health/ready = 503;
|
||||
- медленный handler: /health/ready = 200, но p99 > 5s и
|
||||
db.client.operation.duration растёт.
|
||||
1. Dashboard 'messenger-overview', панель 'HTTP 5xx error ratio'.
|
||||
2. 'HTTP latency p50/p95/p99': резкий рост p99 указывает на зависимый сервис.
|
||||
3. Tempo: service.name=messenger-api, status.code=ERROR; в дочерних spans
|
||||
ищите db/s3 операции с ошибками.
|
||||
4. Loki: {service_name="messenger-api"} |= "error", переход по trace_id.
|
||||
5. Отличите отказы: недоступная БД — /health/ready=503 и db-spans ERROR;
|
||||
медленный handler — /health/ready=200, высокий p99 без ERROR.
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange: { from: 120, to: 0 }
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
expr: "sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\"}[2m])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[2m]))"
|
||||
refId: A
|
||||
instant: true
|
||||
# FIX (ревью): пустой числитель больше не даёт пустое выражение.
|
||||
expr: '(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[2m])) / sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))) or vector(0)'
|
||||
- refId: B
|
||||
datasourceUid: __expr__
|
||||
model: { type: "reduce", expression: "A", reducer: "last" }
|
||||
model:
|
||||
refId: B
|
||||
type: reduce
|
||||
expression: A
|
||||
reducer: last
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model: { type: "threshold", expression: "B", conditions: [{ evaluator: { type: "gt", params: [0.01] } }] }
|
||||
model:
|
||||
refId: C
|
||||
type: threshold
|
||||
expression: B
|
||||
conditions:
|
||||
- evaluator: { type: gt, params: [0.01] }
|
||||
|
||||
- uid: messenger-queue-lag
|
||||
title: "Messenger: queue oldest job age > 30s"
|
||||
condition: C
|
||||
for: 2m
|
||||
noDataState: NoData
|
||||
execErrState: Alerting
|
||||
labels:
|
||||
severity: warning
|
||||
component: worker
|
||||
annotations:
|
||||
summary: "Возраст старейшего задания в очереди превысил 30 секунд в окне 2 минуты."
|
||||
description: |
|
||||
SLI: messenger_queue_oldest_age_seconds. Рост указывает, что worker
|
||||
не справляется или недоступен. Проверьте также messenger_jobs_oldest_queued_age_seconds.
|
||||
SLI: возраст backlog'а. Broker — messenger_queue_oldest_age_seconds (lag+pending),
|
||||
DB — messenger_jobs_oldest_queued_age_seconds (jobs.status='queued').
|
||||
runbook: |
|
||||
1. Dashboard 'messenger-overview', панели 'Queue oldest age' и
|
||||
'Worker saturation'.
|
||||
2. Проверьте worker через `docker compose ps worker`:
|
||||
- Up — worker жив, но не справляется (смотрим Job duration p99);
|
||||
- Exited — worker упал, перезапустите и проверьте логи:
|
||||
`docker compose logs worker --tail 100`.
|
||||
3. Если worker жив, а depth растёт — посмотрите 'Jobs processed rate
|
||||
by outcome': высокий retry_scheduled/retry_exhausted указывает
|
||||
на внешнюю проблему (S3, БД).
|
||||
4. Трассы worker'а в Tempo: service.name=messenger-worker,
|
||||
name=attachment.process. Дочерние spans redis/pgsql/s3 покажут,
|
||||
где задержка.
|
||||
5. После устранения причины — очередь должна уменьшиться,
|
||||
alert перейдёт в resolved автоматически.
|
||||
1. Dashboard: 'Queue oldest age' и 'Worker saturation'.
|
||||
2. docker compose ps worker: Exited — поднять и смотреть логи;
|
||||
Up — worker не справляется, смотреть Job duration p99.
|
||||
3. 'Jobs processed rate by outcome': retry_scheduled/retry_exhausted
|
||||
указывают на внешнюю проблему (S3, БД).
|
||||
4. Tempo: service.name=messenger-worker, name=attachment.process.
|
||||
5. После устранения очередь должна разгрестись, alert — resolved.
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange: { from: 120, to: 0 }
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
expr: "max(messenger_queue_oldest_age_seconds{service_name=\"messenger-api\"})"
|
||||
refId: A
|
||||
instant: true
|
||||
expr: 'max(messenger_queue_oldest_age_seconds{service_name="messenger-api"}) or vector(0)'
|
||||
- refId: B
|
||||
datasourceUid: __expr__
|
||||
model: { type: "reduce", expression: "A", reducer: "last" }
|
||||
model:
|
||||
refId: B
|
||||
type: reduce
|
||||
expression: A
|
||||
reducer: last
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model: { type: "threshold", expression: "B", conditions: [{ evaluator: { type: "gt", params: [30] } }] }
|
||||
model:
|
||||
refId: C
|
||||
type: threshold
|
||||
expression: B
|
||||
conditions:
|
||||
- evaluator: { type: gt, params: [30] }
|
||||
@@ -38,7 +38,7 @@
|
||||
"gridPos": { "h": 8, "w": 8, "x": 8, "y": 1 },
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\"}[$__rate_interval])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[$__rate_interval]))",
|
||||
"expr": "(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\"}[$__rate_interval])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[$__rate_interval]))) or vector(0)",
|
||||
"legendFormat": "5xx ratio"
|
||||
}
|
||||
],
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -500,17 +501,26 @@ func (s *Store) EnqueueDueRetries(ctx context.Context) (int, error) {
|
||||
// JobQueueStats — глубина и возраст очереди заданий в PostgreSQL.
|
||||
// LAB 6: источник данных для метрик messenger.jobs.queued и
|
||||
// messenger.jobs.oldest_queued_age (observable gauge).
|
||||
//
|
||||
// ВАЖНО (ревью): FILTER (WHERE ...) допустим только у агрегата, но не у
|
||||
// обёртки EXTRACT — прежний запрос падал с syntax error at or near "FILTER",
|
||||
// из-за чего обе DB-метрики очереди молча оставались нулевыми. Условная
|
||||
// агрегация через CASE не зависит от позиции FILTER: MIN(CASE ...) игнорирует
|
||||
// NULL и берёт минимум только по queued-строкам.
|
||||
func (s *Store) JobQueueStats(ctx context.Context) (queued int64, oldestAgeSeconds float64, err error) {
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
count(*) FILTER (WHERE status = 'queued'),
|
||||
COALESCE(SUM(CASE WHEN status = 'queued' THEN 1 ELSE 0 END), 0)::bigint,
|
||||
COALESCE(
|
||||
EXTRACT(EPOCH FROM (now() - MIN(created_at))) FILTER (WHERE status = 'queued'),
|
||||
EXTRACT(EPOCH FROM (now() - MIN(CASE WHEN status = 'queued' THEN created_at END))),
|
||||
0
|
||||
)
|
||||
)::float8
|
||||
FROM jobs`).Scan(&queued, &oldestAgeSeconds)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
return 0, 0, fmt.Errorf("job queue stats: %w", err)
|
||||
}
|
||||
if oldestAgeSeconds < 0 { // защита от рассинхрона часов
|
||||
oldestAgeSeconds = 0
|
||||
}
|
||||
return queued, oldestAgeSeconds, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user