diff --git a/REPORT.md b/REPORT.md index a084953a..a3422fd1 100644 --- a/REPORT.md +++ b/REPORT.md @@ -7,7 +7,7 @@ ## Запуск из чистого clone -Требуются Docker с Compose и Python 3.9+. Все серверные зависимости поднимаются из репозитория. Локальные пароли из `lab5.env.example` предназначены только для изолированного учебного стенда. +Требуются Docker с Compose и Python 3.9+. Все серверные зависимости поднимаются из репозитория. Обычные настройки приложения находятся в `config/messenger.yaml`; `.env` содержит адреса окружения, локальные credentials и параметры контейнеров. ```sh cp lab5.env.example .env @@ -97,11 +97,11 @@ Worker повторно проверяет доверенный staging объе EXIF orientation применяется к производным вариантам. Прозрачность сводится на белый фон. Повторное кодирование удаляет metadata. Ключ эффекта имеет вид `attachments//pipelines///.`, поэтому повтор той же операции записывает тот же объект. -Concurrency и prefetch ограничены значениями `WORKER_CONCURRENCY` и `WORKER_PREFETCH`. Перед decode worker оценивает память по размеру входа, числу исходных пикселей и производным буферам, затем занимает часть `WORKER_MEMORY_BYTES` через weighted semaphore. Для разрешённых 40 млн пикселей зарезервировано 704 MiB внутри контейнера с лимитом 1 GiB; несогласованная конфигурация останавливает worker при старте. Одна попытка ограничена 20 секундами при lease 30 секунд. +Concurrency и prefetch задаются через `worker.concurrency` и `worker.prefetch`. Перед decode worker оценивает память по размеру входа, числу исходных пикселей и производным буферам, затем занимает часть `worker.memory_bytes` через weighted semaphore. Для разрешённых 40 млн пикселей зарезервировано 704 MiB внутри контейнера с лимитом 1 GiB; несогласованная конфигурация останавливает worker при старте. Одна попытка ограничена 20 секундами при lease 30 секунд. Worker продлевает lease каждые 5 секунд; потеря lease отменяет обработку. Decode и собственные циклы преобразования проверяют context во время работы. ## Доставка, retry и восстановление -Dispatcher забирает due outbox events через `FOR UPDATE SKIP LOCKED` и lease token. После подтверждённого `XADD` event помечается опубликованным. Сбой после `XADD`, но до этой отметки создаёт допустимый дубль. +Dispatcher забирает due outbox events через `FOR UPDATE SKIP LOCKED` и lease token. После подтверждённого `XADD` event помечается опубликованным. Сбой после `XADD`, но до этой отметки создаёт допустимый дубль. Опубликованные события хранятся семь суток и удаляются раз в минуту пакетами до 1000 строк, не задерживая первый dispatch после запуска. Worker читает consumer group через `XREADGROUP`. При старте обработки PostgreSQL атомарно проверяет `job_id`, `pipeline_version`, `attempt`, выдаёт lease token и переводит attachment в `processing`. Результат применяется только при совпадении всех fencing полей и живом lease. `XACK` выполняется после commit результата. После ACK обработанная запись удаляется из основного stream; pending записи не вытесняются. Failed stream ограничен приблизительно 10 000 записями. @@ -153,7 +153,7 @@ Raw summaries сохранены в `evidence/lab5-idempotency.json` и `evidenc ## Мониторинг и CI -Prometheus опрашивает API replicas, worker, dispatcher, PostgreSQL exporter, отдельные exporters Valkey и Redis broker, Nginx и MinIO. Grafana dashboard содержит RPS, status classes, p95 API latency, Go heap, PostgreSQL, Valkey, MinIO, throughput pipeline по результатам, p95 обработки, in-flight jobs, retry/reclaim, outbox publish failures и Redis broker memory/commands. +Prometheus опрашивает API replicas, worker, dispatcher, PostgreSQL exporter, отдельные exporters Valkey и Redis broker, Nginx и MinIO. Grafana dashboard разделён на блоки API, PostgreSQL, Valkey/Redis, object storage и attachment pipeline. В нём показаны timing основных ручек, CPU, соединения и транзакции PostgreSQL, cache hit/miss, память, доступность worker/dispatcher, throughput, p95 обработки, in-flight jobs, retry/reclaim, outbox backlog, Redis Streams lag, PEL, DLQ и idle consumers. CI для pull request и `main` выполняет contract check, OpenAPI validation, formatting, lint, race tests, build, публичный smoke, интеграционные тесты, persistence/failover lab4 и fault injection lab5. Production workflow запускается вручную и требует approval environment перед rolling deployment. @@ -170,7 +170,7 @@ CI для pull request и `main` выполняет contract check, OpenAPI vali ## Ограничения -Один MinIO, PostgreSQL и Redis container не дают высокой доступности самих хранилищ. `appendfsync always` уменьшает окно потери Redis, но не заменяет репликацию и резервное копирование. Lease должен быть больше максимального времени обработки; для больших production изображений нужен heartbeat продления lease. Deadline проверяется между стадиями, но библиотечный вызов WebP не прерывается посередине кодирования. Failed stream ограничен, поэтому перед достижением retention limit записи нужно выгружать во внешнее долговременное хранилище. Staging у `failed` сохраняется для явного replay; его окончательное удаление остаётся отдельной операторской retention policy. +Один MinIO, PostgreSQL и Redis container не дают высокой доступности самих хранилищ. `appendfsync always` уменьшает окно потери Redis, но не заменяет репликацию и резервное копирование. Decode и собственные циклы обработки прерываются по deadline; библиотечный вызов WebP обрабатывает ограниченный вариант до `1280×1280` и не прерывается посередине кодирования. Failed stream ограничен, поэтому перед достижением retention limit записи нужно выгружать во внешнее долговременное хранилище. Staging у `failed` сохраняется для явного replay; его окончательное удаление остаётся отдельной операторской retention policy. ## Источники и библиотеки diff --git a/compose.yaml b/compose.yaml index 48ad2db0..291eaec1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -320,6 +320,9 @@ services: DATA_SOURCE_USER: ${POSTGRES_USER} DATA_SOURCE_PASS: ${POSTGRES_PASSWORD} PG_EXPORTER_COLLECTION_TIMEOUT: 5s + PG_EXPORTER_EXTEND_QUERY_PATH: /etc/postgres_exporter/queries.yml + volumes: + - ./monitoring/postgres-queries.yml:/etc/postgres_exporter/queries.yml:ro depends_on: postgres: condition: service_healthy @@ -348,6 +351,7 @@ services: REDIS_ADDR: redis://redis-broker:6379 REDIS_USER: default REDIS_PASSWORD: ${REDIS_BROKER_PASSWORD} + REDIS_EXPORTER_CHECK_SINGLE_STREAMS: attachment-jobs,attachment-jobs-failed depends_on: redis-broker: condition: service_healthy diff --git a/internal/messenger/attachment/pipeline/metrics.go b/internal/messenger/attachment/pipeline/metrics.go index ad76eca2..8e8d4324 100644 --- a/internal/messenger/attachment/pipeline/metrics.go +++ b/internal/messenger/attachment/pipeline/metrics.go @@ -9,6 +9,8 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" ) +var workerDurationBuckets = []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 15, 20, 30, 60} + type Metrics struct { workerInFlight prometheus.Gauge workerJobs *prometheus.CounterVec @@ -34,7 +36,7 @@ func NewMetrics() *Metrics { }, []string{"result"}), workerDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "messenger", Subsystem: "attachment_worker", Name: "job_duration_seconds", - Help: "Attachment job delivery processing duration.", Buckets: prometheus.DefBuckets, + Help: "Attachment job delivery processing duration.", Buckets: workerDurationBuckets, }, []string{"result"}), workerRetries: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "messenger", Subsystem: "attachment_worker", Name: "retries_total", diff --git a/internal/messenger/httpapi/metrics.go b/internal/messenger/httpapi/metrics.go index 1dae064e..f1b058e2 100644 --- a/internal/messenger/httpapi/metrics.go +++ b/internal/messenger/httpapi/metrics.go @@ -11,6 +11,11 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" ) +var ( + requestDurationBuckets = []float64{0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30} + uploadDurationBuckets = []float64{0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30, 60} +) + type metrics struct { requests *prometheus.CounterVec duration *prometheus.HistogramVec @@ -36,7 +41,7 @@ func newMetrics() *metrics { Subsystem: "http", Name: "request_duration_seconds", Help: "HTTP request duration in seconds.", - Buckets: prometheus.DefBuckets, + Buckets: requestDurationBuckets, }, []string{"method", "route"}), inFlight: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "messenger", @@ -59,7 +64,7 @@ func newMetrics() *metrics { Namespace: "messenger", Name: "attachment_upload_duration_seconds", Help: "Attachment upload duration in seconds.", - Buckets: prometheus.DefBuckets, + Buckets: uploadDurationBuckets, }), attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "messenger", diff --git a/internal/messenger/httpapi/server_test.go b/internal/messenger/httpapi/server_test.go index 00467d34..044121d1 100644 --- a/internal/messenger/httpapi/server_test.go +++ b/internal/messenger/httpapi/server_test.go @@ -90,8 +90,8 @@ func (s attachmentServiceStub) Metadata(context.Context, string, string) (model. func (s attachmentServiceStub) Content(context.Context, string, string, string) (attachment.Content, error) { return attachment.Content{ Attachment: s.uploaded, - Variant: model.Variant{ContentType: s.uploaded.ContentType, SizeBytes: s.uploaded.SizeBytes}, - Body: io.NopCloser(strings.NewReader("content")), + Variant: model.Variant{ContentType: s.uploaded.ContentType, SizeBytes: s.uploaded.SizeBytes}, + Body: io.NopCloser(strings.NewReader("content")), }, s.err } diff --git a/monitoring/grafana/dashboards/messenger.json b/monitoring/grafana/dashboards/messenger.json index a4d0a5b0..de0ef2d0 100644 --- a/monitoring/grafana/dashboards/messenger.json +++ b/monitoring/grafana/dashboards/messenger.json @@ -6,612 +6,893 @@ "graphTooltip": 1, "panels": [ { - "type": "timeseries", - "title": "API requests per second", - "id": 1, + "type": "row", + "title": "API and edge", + "id": 100, + "collapsed": true, "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 0 - }, - "targets": [ - { - "expr": "sum(rate(messenger_http_requests_total[1m]))", - "legendFormat": "total", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "API RPS by replica", - "id": 2, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 0 - }, - "targets": [ - { - "expr": "sum by (instance) (rate(messenger_http_requests_total[1m]))", - "legendFormat": "{{instance}}", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "API responses by status class", - "id": 3, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 8 - }, - "targets": [ - { - "expr": "sum by (status_class) (rate(messenger_http_requests_total[1m]))", - "legendFormat": "{{status_class}}", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Healthy API replicas", - "id": 4, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 8 - }, - "targets": [ - { - "expr": "sum(up{job=\"messenger\"})", - "legendFormat": "replicas", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "API latency p95 by replica and route", - "id": 5, - "gridPos": { - "h": 8, + "h": 1, "w": 24, "x": 0, - "y": 16 + "y": 0 }, - "fieldConfig": { - "defaults": { - "unit": "s" - }, - "overrides": [] - }, - "targets": [ + "panels": [ { - "expr": "histogram_quantile(0.95, sum by (le, instance, route) (rate(messenger_http_request_duration_seconds_bucket[5m])))", - "legendFormat": "{{instance}} {{route}}", - "refId": "A" + "type": "timeseries", + "title": "API requests by route", + "id": 1, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 1 + }, + "targets": [ + { + "expr": "sum by (method, route) (rate(messenger_http_requests_total[1m]))", + "legendFormat": "{{method}} {{route}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "API responses by status class", + "id": 2, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 1 + }, + "targets": [ + { + "expr": "sum by (status_class) (rate(messenger_http_requests_total[1m]))", + "legendFormat": "{{status_class}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "API latency p95 by route", + "id": 3, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 9 + }, + "targets": [ + { + "expr": "histogram_quantile(0.95, sum by (le, method, route) (rate(messenger_http_request_duration_seconds_bucket[5m])))", + "legendFormat": "{{method}} {{route}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "API replicas and requests in flight", + "id": 4, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 9 + }, + "targets": [ + { + "expr": "sum(up{job=\"messenger\"})", + "legendFormat": "healthy replicas", + "refId": "A" + }, + { + "expr": "sum(messenger_http_requests_in_flight)", + "legendFormat": "in flight", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "API CPU usage", + "id": 5, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 17 + }, + "targets": [ + { + "expr": "sum(rate(process_cpu_seconds_total{job=\"messenger\"}[1m]))", + "legendFormat": "API", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "cores" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "Nginx requests and connections", + "id": 6, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 17 + }, + "targets": [ + { + "expr": "sum(rate(nginx_http_requests_total[1m]))", + "legendFormat": "requests/s", + "refId": "A" + }, + { + "expr": "sum(nginx_connections_active)", + "legendFormat": "active connections", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } } ] }, { - "type": "timeseries", - "title": "API in flight", - "id": 6, + "type": "row", + "title": "PostgreSQL", + "id": 101, + "collapsed": true, "gridPos": { - "h": 8, - "w": 8, + "h": 1, + "w": 24, "x": 0, - "y": 24 + "y": 25 }, - "targets": [ + "panels": [ { - "expr": "messenger_http_requests_in_flight", - "legendFormat": "{{instance}}", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Go heap by replica", - "id": 7, - "gridPos": { - "h": 8, - "w": 8, - "x": 8, - "y": 24 - }, - "fieldConfig": { - "defaults": { - "unit": "bytes" + "type": "timeseries", + "title": "PostgreSQL availability and connections", + "id": 7, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 26 + }, + "targets": [ + { + "expr": "up{job=\"postgres\"}", + "legendFormat": "up", + "refId": "A" + }, + { + "expr": "sum(pg_stat_activity_count{datname=\"messenger\"})", + "legendFormat": "connections", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } }, - "overrides": [] - }, - "targets": [ { - "expr": "go_memstats_heap_alloc_bytes{job=\"messenger\"}", - "legendFormat": "{{instance}}", - "refId": "A" + "type": "timeseries", + "title": "PostgreSQL transactions", + "id": 8, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 26 + }, + "targets": [ + { + "expr": "sum(rate(pg_stat_database_xact_commit{datname=\"messenger\"}[1m]))", + "legendFormat": "commit/s", + "refId": "A" + }, + { + "expr": "sum(rate(pg_stat_database_xact_rollback{datname=\"messenger\"}[1m]))", + "legendFormat": "rollback/s", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "PostgreSQL database size", + "id": 9, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 34 + }, + "targets": [ + { + "expr": "pg_database_size_bytes{datname=\"messenger\"}", + "legendFormat": "messenger", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "Attachment jobs by status", + "id": 10, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 34 + }, + "targets": [ + { + "expr": "messenger_attachment_jobs_count", + "legendFormat": "{{status}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "Oldest attachment job", + "id": 11, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 42 + }, + "targets": [ + { + "expr": "messenger_attachment_jobs_oldest_age_seconds", + "legendFormat": "{{status}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "Pending outbox", + "id": 12, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 42 + }, + "targets": [ + { + "expr": "messenger_outbox_pending", + "legendFormat": "events", + "refId": "A" + }, + { + "expr": "messenger_outbox_oldest_pending_age_seconds", + "legendFormat": "oldest age, seconds", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [ + { + "matcher": { + "id": "byFrameRefID", + "options": "B" + }, + "properties": [ + { + "id": "unit", + "value": "s" + } + ] + } + ] + } } ] }, { - "type": "timeseries", - "title": "Idempotency replays", - "id": 8, + "type": "row", + "title": "Valkey and Redis", + "id": 102, + "collapsed": true, "gridPos": { - "h": 8, - "w": 8, - "x": 16, - "y": 24 - }, - "targets": [ - { - "expr": "sum(rate(messenger_http_idempotency_replays_total[1m]))", - "legendFormat": "replays/s", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Nginx connections and requests", - "id": 9, - "gridPos": { - "h": 8, - "w": 12, + "h": 1, + "w": 24, "x": 0, - "y": 32 + "y": 50 }, - "targets": [ + "panels": [ { - "expr": "nginx_connections_active", - "legendFormat": "active connections", - "refId": "A" + "type": "timeseries", + "title": "Valkey and Redis availability", + "id": 13, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 51 + }, + "targets": [ + { + "expr": "up{job=\"valkey\"}", + "legendFormat": "Valkey", + "refId": "A" + }, + { + "expr": "up{job=\"redis-broker\"}", + "legendFormat": "Redis broker", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } }, { - "expr": "rate(nginx_http_requests_total[1m])", - "legendFormat": "requests/s", - "refId": "B" - } - ] - }, - { - "type": "timeseries", - "title": "PostgreSQL connections", - "id": 10, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 32 - }, - "targets": [ + "type": "timeseries", + "title": "Valkey and Redis memory", + "id": 14, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 51 + }, + "targets": [ + { + "expr": "redis_memory_used_bytes{job=\"valkey\"}", + "legendFormat": "Valkey", + "refId": "A" + }, + { + "expr": "redis_memory_used_bytes{job=\"redis-broker\"}", + "legendFormat": "Redis broker", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + } + }, { - "expr": "sum(pg_stat_activity_count{datname=\"messenger\"})", - "legendFormat": "connections", - "refId": "A" + "type": "timeseries", + "title": "Valkey cache hits and misses", + "id": 15, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 59 + }, + "targets": [ + { + "expr": "sum(rate(redis_keyspace_hits_total{job=\"valkey\"}[1m]))", + "legendFormat": "hits/s", + "refId": "A" + }, + { + "expr": "sum(rate(redis_keyspace_misses_total{job=\"valkey\"}[1m]))", + "legendFormat": "misses/s", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "Valkey and Redis commands", + "id": 16, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 59 + }, + "targets": [ + { + "expr": "sum(rate(redis_commands_processed_total{job=\"valkey\"}[1m]))", + "legendFormat": "Valkey commands/s", + "refId": "A" + }, + { + "expr": "sum(rate(redis_commands_processed_total{job=\"redis-broker\"}[1m]))", + "legendFormat": "Redis commands/s", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } } ] }, { - "type": "timeseries", - "title": "PostgreSQL transactions", - "id": 11, + "type": "row", + "title": "Object storage", + "id": 103, + "collapsed": true, "gridPos": { - "h": 8, - "w": 12, + "h": 1, + "w": 24, "x": 0, - "y": 40 + "y": 67 }, - "targets": [ + "panels": [ { - "expr": "rate(pg_stat_database_xact_commit{datname=\"messenger\"}[1m])", - "legendFormat": "commit/s", - "refId": "A" + "type": "timeseries", + "title": "MinIO availability", + "id": 17, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 68 + }, + "targets": [ + { + "expr": "up{job=\"minio\"}", + "legendFormat": "up", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } }, { - "expr": "rate(pg_stat_database_xact_rollback{datname=\"messenger\"}[1m])", - "legendFormat": "rollback/s", - "refId": "B" + "type": "timeseries", + "title": "MinIO objects and requests", + "id": 18, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 68 + }, + "targets": [ + { + "expr": "sum(minio_cluster_usage_object_total)", + "legendFormat": "objects", + "refId": "A" + }, + { + "expr": "sum(rate(minio_s3_requests_total[1m]))", + "legendFormat": "requests/s", + "refId": "B" + }, + { + "expr": "sum(rate(minio_s3_requests_errors_total[1m]))", + "legendFormat": "errors/s", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "type": "timeseries", + "title": "MinIO storage", + "id": 19, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 68 + }, + "targets": [ + { + "expr": "sum(minio_cluster_usage_total_bytes)", + "legendFormat": "used", + "refId": "A" + }, + { + "expr": "sum(minio_cluster_capacity_usable_free_bytes)", + "legendFormat": "free", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + } } ] }, { - "type": "timeseries", - "title": "PostgreSQL database size", - "id": 12, + "type": "row", + "title": "Attachment pipeline", + "id": 104, + "collapsed": true, "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 40 - }, - "fieldConfig": { - "defaults": { - "unit": "bytes" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "pg_database_size_bytes{datname=\"messenger\"}", - "legendFormat": "database", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Valkey memory", - "id": 13, - "gridPos": { - "h": 8, - "w": 12, + "h": 1, + "w": 24, "x": 0, - "y": 48 + "y": 76 }, - "fieldConfig": { - "defaults": { - "unit": "bytes" - }, - "overrides": [] - }, - "targets": [ + "panels": [ { - "expr": "redis_memory_used_bytes{job=\"valkey\"}", - "legendFormat": "used", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Valkey keys and commands", - "id": 14, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 48 - }, - "targets": [ - { - "expr": "sum(redis_db_keys{job=\"valkey\"})", - "legendFormat": "keys", - "refId": "A" + "type": "timeseries", + "title": "Pipeline availability and consumers", + "id": 20, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 77 + }, + "targets": [ + { + "expr": "sum(up{job=\"attachment-worker\"})", + "legendFormat": "workers up", + "refId": "A" + }, + { + "expr": "sum(up{job=\"outbox-dispatcher\"})", + "legendFormat": "dispatcher up", + "refId": "B" + }, + { + "expr": "max(redis_stream_group_consumers{job=\"redis-broker\",stream=\"attachment-jobs\",group=\"attachment-workers\"})", + "legendFormat": "active consumers", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } }, { - "expr": "rate(redis_commands_processed_total{job=\"valkey\"}[1m])", - "legendFormat": "commands/s", - "refId": "B" - } - ] - }, - { - "type": "timeseries", - "title": "Attachment uploads by result", - "id": 15, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 56 - }, - "targets": [ - { - "expr": "sum by (result) (rate(messenger_attachment_uploads_total[1m]))", - "legendFormat": "{{result}}", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Attachment upload latency p95", - "id": 16, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 56 - }, - "fieldConfig": { - "defaults": { - "unit": "s" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_upload_duration_seconds_bucket[5m])))", - "legendFormat": "p95", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Attachment upload traffic", - "id": 17, - "gridPos": { - "h": 8, - "w": 8, - "x": 0, - "y": 64 - }, - "fieldConfig": { - "defaults": { - "unit": "Bps" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "sum(rate(messenger_attachment_upload_bytes_total[1m]))", - "legendFormat": "bytes/s", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "MinIO objects", - "id": 18, - "gridPos": { - "h": 8, - "w": 8, - "x": 8, - "y": 64 - }, - "targets": [ - { - "expr": "sum(minio_cluster_usage_object_total)", - "legendFormat": "objects", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "MinIO requests and errors", - "id": 19, - "gridPos": { - "h": 8, - "w": 8, - "x": 16, - "y": 64 - }, - "targets": [ - { - "expr": "sum(rate(minio_s3_requests_total[1m]))", - "legendFormat": "requests/s", - "refId": "A" + "type": "timeseries", + "title": "Attachment upload results", + "id": 21, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 77 + }, + "targets": [ + { + "expr": "sum by (result) (rate(messenger_attachment_uploads_total[1m]))", + "legendFormat": "{{result}}", + "refId": "A" + }, + { + "expr": "sum(rate(messenger_attachment_upload_bytes_total[1m]))", + "legendFormat": "bytes/s", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [ + { + "matcher": { + "id": "byFrameRefID", + "options": "B" + }, + "properties": [ + { + "id": "unit", + "value": "Bps" + } + ] + } + ] + } }, { - "expr": "sum(rate(minio_s3_requests_errors_total[1m]))", - "legendFormat": "errors/s", - "refId": "B" - } - ] - }, - { - "type": "timeseries", - "title": "MinIO availability", - "id": 20, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 72 - }, - "targets": [ - { - "expr": "up{job=\"minio\"}", - "legendFormat": "up", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "MinIO storage", - "id": 21, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 72 - }, - "fieldConfig": { - "defaults": { - "unit": "bytes" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "sum(minio_cluster_usage_total_bytes)", - "legendFormat": "used", - "refId": "A" + "type": "timeseries", + "title": "Worker throughput by result", + "id": 22, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 85 + }, + "targets": [ + { + "expr": "sum by (result) (rate(messenger_attachment_worker_jobs_total[1m]))", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } }, { - "expr": "sum(minio_cluster_capacity_usable_free_bytes)", - "legendFormat": "free", - "refId": "B" - } - ] - }, - { - "type": "timeseries", - "title": "Attachment pipeline throughput", - "id": 22, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 80 - }, - "fieldConfig": { - "defaults": { - "unit": "ops" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "sum by (result) (rate(messenger_attachment_worker_jobs_total[1m]))", - "legendFormat": "{{result}}", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Attachment worker latency and concurrency", - "id": 23, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 80 - }, - "fieldConfig": { - "defaults": {}, - "overrides": [] - }, - "targets": [ - { - "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_worker_job_duration_seconds_bucket[5m])))", - "legendFormat": "p95", - "refId": "A" + "type": "timeseries", + "title": "Worker processing latency p95", + "id": 23, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 85 + }, + "targets": [ + { + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_worker_job_duration_seconds_bucket[5m])))", + "legendFormat": "p95", + "refId": "A" + }, + { + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_upload_duration_seconds_bucket[5m])))", + "legendFormat": "upload p95", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } }, { - "expr": "sum(messenger_attachment_worker_jobs_in_flight)", - "legendFormat": "in flight", - "refId": "B" - } - ] - }, - { - "type": "timeseries", - "title": "Attachment retries and reclaimed deliveries", - "id": 24, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 88 - }, - "fieldConfig": { - "defaults": { - "unit": "ops" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "sum(rate(messenger_attachment_worker_retries_total[1m]))", - "legendFormat": "retries", - "refId": "A" + "type": "timeseries", + "title": "Worker jobs in flight", + "id": 24, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 93 + }, + "targets": [ + { + "expr": "sum(messenger_attachment_worker_jobs_in_flight)", + "legendFormat": "jobs", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } }, { - "expr": "sum(rate(messenger_attachment_worker_reclaimed_deliveries_total[1m]))", - "legendFormat": "reclaimed", - "refId": "B" - } - ] - }, - { - "type": "timeseries", - "title": "Transactional outbox", - "id": 25, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 88 - }, - "fieldConfig": { - "defaults": { - "unit": "ops" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "sum(rate(messenger_outbox_published_total[1m]))", - "legendFormat": "published", - "refId": "A" + "type": "timeseries", + "title": "Retries and reclaimed deliveries", + "id": 25, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 93 + }, + "targets": [ + { + "expr": "sum(rate(messenger_attachment_worker_retries_total[1m]))", + "legendFormat": "retries/s", + "refId": "A" + }, + { + "expr": "sum(rate(messenger_attachment_worker_reclaimed_deliveries_total[1m]))", + "legendFormat": "reclaimed/s", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } }, { - "expr": "sum(rate(messenger_outbox_publish_failures_total[1m]))", - "legendFormat": "publish failures", - "refId": "B" + "type": "timeseries", + "title": "Outbox dispatcher", + "id": 26, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 93 + }, + "targets": [ + { + "expr": "sum(rate(messenger_outbox_published_total[1m]))", + "legendFormat": "published/s", + "refId": "A" + }, + { + "expr": "sum(rate(messenger_outbox_publish_failures_total[1m]))", + "legendFormat": "failures/s", + "refId": "B" + }, + { + "expr": "sum(rate(messenger_outbox_recovered_leases_total[1m]))", + "legendFormat": "recovered/s", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } }, { - "expr": "sum(rate(messenger_outbox_recovered_leases_total[1m]))", - "legendFormat": "recovered leases", - "refId": "C" - } - ] - }, - { - "type": "timeseries", - "title": "Redis broker memory", - "id": 26, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 96 - }, - "fieldConfig": { - "defaults": { - "unit": "bytes" - }, - "overrides": [] - }, - "targets": [ - { - "expr": "redis_memory_used_bytes{job=\"redis-broker\"}", - "legendFormat": "used", - "refId": "A" - } - ] - }, - { - "type": "timeseries", - "title": "Redis broker commands and keys", - "id": 27, - "gridPos": { - "h": 8, - "w": 12, - "x": 12, - "y": 96 - }, - "fieldConfig": { - "defaults": {}, - "overrides": [] - }, - "targets": [ - { - "expr": "rate(redis_commands_processed_total{job=\"redis-broker\"}[1m])", - "legendFormat": "commands", - "refId": "A" + "type": "timeseries", + "title": "Redis Stream lag, PEL and DLQ", + "id": 27, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 101 + }, + "targets": [ + { + "expr": "max(redis_stream_group_lag{job=\"redis-broker\",stream=\"attachment-jobs\",group=\"attachment-workers\"})", + "legendFormat": "lag", + "refId": "A" + }, + { + "expr": "max(redis_stream_group_messages_pending{job=\"redis-broker\",stream=\"attachment-jobs\",group=\"attachment-workers\"})", + "legendFormat": "PEL", + "refId": "B" + }, + { + "expr": "max(redis_stream_length{job=\"redis-broker\",stream=\"attachment-jobs-failed\"})", + "legendFormat": "DLQ", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } }, { - "expr": "sum(redis_db_keys{job=\"redis-broker\"})", - "legendFormat": "keys", - "refId": "B" + "type": "timeseries", + "title": "Redis Stream consumers", + "id": 28, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 101 + }, + "targets": [ + { + "expr": "max(redis_stream_group_consumers{job=\"redis-broker\",stream=\"attachment-jobs\",group=\"attachment-workers\"})", + "legendFormat": "consumers", + "refId": "A" + }, + { + "expr": "max(redis_stream_group_consumer_idle_seconds{job=\"redis-broker\",stream=\"attachment-jobs\",group=\"attachment-workers\"})", + "legendFormat": "max idle, seconds", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [ + { + "matcher": { + "id": "byFrameRefID", + "options": "B" + }, + "properties": [ + { + "id": "unit", + "value": "s" + } + ] + } + ] + } } ] } @@ -621,8 +902,7 @@ "tags": [ "highload", "lab5", - "nginx", - "failover" + "pipeline" ], "templating": { "list": [] @@ -634,5 +914,5 @@ "timezone": "browser", "title": "Messenger lab5 overview", "uid": "messenger-lab5", - "version": 2 + "version": 3 } diff --git a/monitoring/postgres-queries.yml b/monitoring/postgres-queries.yml new file mode 100644 index 00000000..7666281c --- /dev/null +++ b/monitoring/postgres-queries.yml @@ -0,0 +1,39 @@ +messenger_attachment_jobs: + query: | + WITH statuses(status) AS ( + VALUES ('queued'), ('processing'), ('failed') + ) + SELECT + statuses.status, + COUNT(j.id)::bigint AS count, + COALESCE(EXTRACT(EPOCH FROM (clock_timestamp() - MIN(j.created_at))), 0)::double precision AS oldest_age_seconds + FROM statuses + LEFT JOIN attachment_jobs j ON j.status = statuses.status + GROUP BY statuses.status + metrics: + - status: + usage: LABEL + description: Attachment job status. + - count: + usage: GAUGE + description: Attachment jobs in this status. + - oldest_age_seconds: + usage: GAUGE + description: Age of the oldest attachment job in this status. + +messenger_outbox: + query: | + SELECT + COUNT(*) FILTER (WHERE published_at IS NULL)::bigint AS pending, + COALESCE( + EXTRACT(EPOCH FROM (clock_timestamp() - MIN(created_at) FILTER (WHERE published_at IS NULL))), + 0 + )::double precision AS oldest_pending_age_seconds + FROM outbox_events + metrics: + - pending: + usage: GAUGE + description: Unpublished outbox events. + - oldest_pending_age_seconds: + usage: GAUGE + description: Age of the oldest unpublished outbox event.