feat(lab6): add observability and SLO burn-rate alerts

This commit is contained in:
2026-11-15 06:54:54 +03:00
parent 470d9d6f1e
commit 63c1f06b84
204 changed files with 25348 additions and 37 deletions
+7
View File
@@ -0,0 +1,7 @@
FROM haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad
COPY infrastructure/haproxy/haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
USER haproxy
EXPOSE 8080
+66
View File
@@ -0,0 +1,66 @@
global
log stdout format raw local0
maxconn 2048
defaults
log global
mode http
option httplog
timeout connect 1s
timeout client 30s
timeout server 30s
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold other 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
frontend public
bind :8080
acl api_request path_beg /api/ /web-api/ /health/
acl web_api path_beg /web-api/
acl has_session req.cook(mtusi_session) -m found
acl message_create method POST
acl message_path path_reg ^/(api|web-api)/v1/chats/[^/]+/messages$
http-request del-header Authorization if web_api
http-request set-header Authorization "Bearer %[req.cook(mtusi_session)]" if web_api has_session
http-request del-header Cookie if api_request
http-request replace-path ^/web-api/(.*)$ /api/\1 if web_api
use_backend message_backend if message_create message_path
use_backend api_backend if api_request
default_backend frontend_backend
backend api_backend
balance leastconn
option httpchk
http-check send meth GET uri /health/lb ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker init-addr libc,none
server-template api 8 api:8080
backend message_backend
balance leastconn
option httpchk
option redispatch
option http-buffer-request
retries 3
retry-on conn-failure empty-response response-timeout 502 503 504
http-check send meth GET uri /health/lb ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker init-addr libc,none
server-template api 8 api:8080
backend frontend_backend
option httpchk GET /
http-check expect status 200
server frontend frontend:8080 check inter 2s fall 2 rise 2 resolvers docker init-addr libc,none
+40
View File
@@ -0,0 +1,40 @@
FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS minio-builder
ARG MINIO_VERSION=RELEASE.2025-10-15T17-29-55Z
RUN CGO_ENABLED=0 GOBIN=/out go install github.com/minio/minio@${MINIO_VERSION}
FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS mc-builder
ARG MC_VERSION=RELEASE.2025-08-13T08-35-41Z
RUN CGO_ENABLED=0 GOBIN=/out go install github.com/minio/mc@${MC_VERSION}
FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 AS server
RUN apk add --no-cache ca-certificates wget && \
addgroup -g 1000 minio && \
adduser -u 1000 -G minio -s /sbin/nologin -D minio && \
mkdir -p /data && \
chown minio:minio /data
COPY --from=minio-builder /out/minio /usr/local/bin/minio
USER minio:minio
VOLUME ["/data"]
EXPOSE 9000
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=20 \
CMD wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null || exit 1
ENTRYPOINT ["/usr/local/bin/minio"]
CMD ["server", "/data", "--address", ":9000"]
FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 AS client
RUN apk add --no-cache ca-certificates && \
addgroup -g 1000 minio && \
adduser -u 1000 -G minio -s /sbin/nologin -D minio
COPY --from=mc-builder /out/mc /usr/local/bin/mc
USER minio:minio
ENTRYPOINT ["/usr/local/bin/mc"]
@@ -0,0 +1,26 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetBucketLocation",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::__BUCKET__"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::__BUCKET__/*"
]
}
]
}
+15
View File
@@ -0,0 +1,15 @@
FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS frontend-build
WORKDIR /frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm test && npm run build
FROM nginx:1.30.6-alpine@sha256:970364228b1e4f932abc22d321932816782cca8a20b85a77552a7cfe9acfb3b5
COPY infrastructure/nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=frontend-build /frontend/dist /usr/share/nginx/html
EXPOSE 8080
+32
View File
@@ -0,0 +1,32 @@
worker_processes auto;
events {
worker_connections 512;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 8080;
server_name _;
root /usr/share/nginx/html;
index index.html;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer" always;
add_header X-Frame-Options "DENY" always;
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
location /assets/ {
try_files $uri =404;
expires 1y;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
}
}
@@ -0,0 +1,80 @@
{
"annotations": {"list": []},
"editable": false,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"liveNow": false,
"panels": [
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 0},
"id": 1,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "sum(rate(messenger_http_server_requests_total[1m]))", "legendFormat": "all requests", "refId": "A"}],
"title": "API request rate",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 0},
"id": 2,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "sum by (status_class) (rate(messenger_http_server_requests_total[1m]))", "legendFormat": "{{status_class}}", "refId": "A"}],
"title": "API responses by status class",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 0},
"id": 3,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}],
"title": "API duration",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "jobs"}, "overrides": []},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"id": 4,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "sum by (outcome) (increase(messenger_worker_jobs_total[5m]))", "legendFormat": "{{outcome}}", "refId": "A"}],
"title": "Worker jobs by outcome",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
"id": 5,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_worker_job_duration_seconds_bucket[5m])))", "legendFormat": "p95 {{outcome}}", "refId": "A"}],
"title": "Worker processing duration",
"type": "timeseries"
},
{
"datasource": {"type": "loki", "uid": "loki"},
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 16},
"id": 6,
"options": {"dedupStrategy": "none", "enableLogDetails": true, "showCommonLabels": false, "showLabels": false, "showTime": true, "sortOrder": "Descending", "wrapLogMessage": true},
"targets": [{"expr": "{service_name=~\"messenger-(api|worker)\"}", "queryType": "range", "refId": "A"}],
"title": "Correlated structured logs",
"type": "logs"
}
],
"refresh": "5s",
"schemaVersion": 41,
"tags": ["mtusi", "lab6", "grade3"],
"templating": {"list": []},
"time": {"from": "now-15m", "to": "now"},
"timepicker": {},
"timezone": "browser",
"title": "MTUSI Lab 6 — Grade 3",
"uid": "mtusi-lab6-grade3",
"version": 1
}
@@ -0,0 +1,543 @@
{
"annotations": {
"list": []
},
"editable": false,
"graphTooltip": 1,
"id": null,
"links": [],
"panels": [
{
"id": 1,
"title": "API RPS",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 6,
"x": 0,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_server_requests_total[1m]))",
"legendFormat": "requests/s"
}
]
},
{
"id": 2,
"title": "API 5xx ratio",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 6,
"x": 6,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_server_requests_total{status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)",
"legendFormat": "5xx / all"
}
]
},
{
"id": 3,
"title": "API latency p50/p95/p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))",
"legendFormat": "p99"
}
]
},
{
"id": 4,
"title": "Queue depth / oldest age seconds",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_depth)",
"legendFormat": "depth"
},
{
"refId": "B",
"expr": "max(messenger_queue_oldest_job_age_seconds)",
"legendFormat": "oldest age s"
}
]
},
{
"id": 5,
"title": "Worker saturation",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_worker_busy) / clamp_min(max(messenger_worker_capacity), 1)",
"legendFormat": "busy / capacity"
}
]
},
{
"id": 6,
"title": "Time to ready p50/p95/p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))",
"legendFormat": "p99"
}
]
},
{
"id": 7,
"title": "PostgreSQL pool used/idle/capacity",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name, state) (messenger_db_pool_connections)",
"legendFormat": "{{service_name}} {{state}}"
}
]
},
{
"id": 8,
"title": "PostgreSQL pool waits",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name) (rate(messenger_db_pool_waits_total[5m]))",
"legendFormat": "{{service_name}} waits/s"
}
]
},
{
"id": 9,
"title": "Process CPU",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name) (rate(messenger_process_cpu_time_seconds_total[5m]))",
"legendFormat": "{{service_name}}"
}
]
},
{
"id": 10,
"title": "Process RSS",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "max by (service_name) (messenger_process_memory_bytes)",
"legendFormat": "{{service_name}}"
}
]
},
{
"id": 11,
"title": "Worker jobs and p95 duration",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_worker_jobs_total[5m]))",
"legendFormat": "jobs/s {{outcome}}"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_worker_job_duration_seconds_bucket[5m])))",
"legendFormat": "p95 s {{outcome}}"
}
]
},
{
"id": 12,
"title": "Collector bounded queues / drops",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size",
"legendFormat": "queue {{exporter}}"
},
{
"refId": "B",
"expr": "otelcol_exporter_queue_capacity",
"legendFormat": "capacity {{exporter}}"
},
{
"refId": "C",
"expr": "(sum(rate(otelcol_exporter_send_failed_log_records[5m])) or vector(0)) + (sum(rate(otelcol_exporter_send_failed_spans[5m])) or vector(0))",
"legendFormat": "drops/s"
}
]
},
{
"id": 13,
"title": "Alert state",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 28
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"Messenger(APIHighErrorRate|QueueLagGrowing)\"}",
"legendFormat": "{{alertname}} {{alertstate}}"
}
]
},
{
"id": 14,
"title": "Correlated logs",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"h": 10,
"w": 16,
"x": 8,
"y": 28
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-(api|worker|dispatcher)\"}",
"queryType": "range"
}
],
"options": {
"dedupStrategy": "none",
"enableLogDetails": true,
"showCommonLabels": false,
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": true
}
}
],
"refresh": "5s",
"schemaVersion": 41,
"tags": [
"mtusi",
"lab6",
"grade4"
],
"templating": {
"list": []
},
"time": {
"from": "now-30m",
"to": "now"
},
"timepicker": {},
"timezone": "browser",
"title": "MTUSI Lab 6 - Grade 4",
"uid": "mtusi-lab6-grade4",
"version": 1
}
@@ -0,0 +1,69 @@
{
"annotations": {"list": []},
"editable": false,
"graphTooltip": 1,
"id": null,
"panels": [
{
"id": 1,
"title": "API error ratio by burn window",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 9, "w": 12, "x": 0, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "messenger:sli_api_error_ratio_30s", "legendFormat": "30s"},
{"refId": "B", "expr": "messenger:sli_api_error_ratio_1m", "legendFormat": "1m"},
{"refId": "C", "expr": "messenger:sli_api_error_ratio_2m", "legendFormat": "2m"},
{"refId": "D", "expr": "messenger:sli_api_error_ratio_5m", "legendFormat": "5m"}
]
},
{
"id": 2,
"title": "Attachment >10s ratio by burn window",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 9, "w": 12, "x": 12, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "messenger:sli_attachment_slow_ratio_30s", "legendFormat": "30s"},
{"refId": "B", "expr": "messenger:sli_attachment_slow_ratio_1m", "legendFormat": "1m"},
{"refId": "C", "expr": "messenger:sli_attachment_slow_ratio_2m", "legendFormat": "2m"},
{"refId": "D", "expr": "messenger:sli_attachment_slow_ratio_5m", "legendFormat": "5m"}
]
},
{
"id": 3,
"title": "SLO compliance (7d policy window)",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 9},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"targets": [
{"refId": "A", "expr": "messenger:slo_api_success_ratio_7d", "legendFormat": "API success"},
{"refId": "B", "expr": "messenger:slo_attachment_ready_ratio_7d", "legendFormat": "ready <=10s"},
{"refId": "C", "expr": "vector(0.99)", "legendFormat": "99% objective"}
]
},
{
"id": 4,
"title": "Burn-rate alert states",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 9},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "ALERTS{alertname=~\"Messenger(API|AttachmentReady)BurnRate(Fast|Slow)\"}", "legendFormat": "{{alertname}} {{alertstate}}"}
]
}
],
"refresh": "5s",
"schemaVersion": 42,
"tags": ["mtusi", "lab6", "grade5", "slo", "burn-rate"],
"templating": {"list": []},
"time": {"from": "now-30m", "to": "now"},
"timezone": "browser",
"title": "MTUSI Lab 6 - Grade 5 SLO",
"uid": "mtusi-lab6-grade5",
"version": 1
}
@@ -0,0 +1,12 @@
apiVersion: 1
providers:
- name: MTUSI Lab 6
orgId: 1
folder: Lab 6
type: file
disableDeletion: true
editable: false
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,44 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '([0-9a-f]{32})'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: -1m
spanEndTimeShift: 1m
tags:
- key: service.name
value: service_name
filterByTraceID: true
filterBySpanID: true
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
+34
View File
@@ -0,0 +1,34 @@
auth_enabled: false
server:
http_listen_port: 3100
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 168h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
@@ -0,0 +1,72 @@
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 512
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_constant_labels:
included: [service.name, service.version, service.instance.id, deployment.environment.name]
otlp_http/tempo:
endpoint: http://tempo:4318
timeout: 3s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
otlp_http/loki:
endpoint: http://loki:3100/otlp
timeout: 3s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
service:
extensions: [health_check]
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/tempo]
telemetry:
logs:
level: info
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
@@ -0,0 +1,12 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/rules/*.yaml
scrape_configs:
- job_name: application-telemetry
static_configs:
- targets: [otel-collector:8889]
- job_name: collector-internal
static_configs:
- targets: [otel-collector:8888]
@@ -0,0 +1,97 @@
groups:
- name: messenger-level4
interval: 5s
rules:
- record: messenger:sli_api_success_ratio_5m
expr: 1 - (sum(rate(messenger_http_server_requests_total{status_class="5xx"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total[5m])), 0.000001))
- alert: MessengerAPIHighErrorRate
expr: (sum(rate(messenger_http_server_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)) > 0.01 and sum(rate(messenger_http_server_requests_total[1m])) > 0.05
for: 10s
labels:
severity: warning
slo: api-availability
annotations:
summary: API 5xx ratio exceeds the 99% availability SLO
description: More than 1% of business HTTP requests were 5xx during the last minute.
runbook: infrastructure/telemetry/runbooks/level4.md#api-high-error-rate
- alert: MessengerQueueLagGrowing
expr: max(messenger_queue_depth) > 0 and max(messenger_queue_oldest_job_age_seconds) > 10
for: 10s
labels:
severity: warning
slo: attachment-ready
annotations:
summary: Attachment queue lag is growing
description: At least one job has remained queued for more than 10 seconds.
runbook: infrastructure/telemetry/runbooks/level4.md#queue-lag-growing
- name: messenger-level5-burn-rate
interval: 5s
rules:
- record: messenger:slo_api_success_ratio_7d
expr: (1 - (sum(increase(messenger_http_server_requests_total{status_class="5xx"}[7d])) / clamp_min(sum(increase(messenger_http_server_requests_total[7d])), 1))) and sum(increase(messenger_http_server_requests_total[7d])) > 0
- record: messenger:slo_attachment_ready_ratio_7d
expr: (sum(increase(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[7d])) / clamp_min(sum(increase(messenger_attachment_ready_duration_seconds_count[7d])), 1)) and sum(increase(messenger_attachment_ready_duration_seconds_count[7d])) > 0
- record: messenger:sli_api_error_ratio_30s
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_server_requests_total[30s])), 0.000001)
- record: messenger:sli_api_error_ratio_1m
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)
- record: messenger:sli_api_error_ratio_2m
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[2m])) / clamp_min(sum(rate(messenger_http_server_requests_total[2m])), 0.000001)
- record: messenger:sli_api_error_ratio_5m
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total[5m])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_30s
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[30s])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[30s]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[30s])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_1m
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[1m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[1m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[1m])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_2m
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[2m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[2m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[2m])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_5m
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[5m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[5m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[5m])), 0.000001)
- alert: MessengerAPIBurnRateFast
expr: messenger:sli_api_error_ratio_30s > (14.4 * 0.01) and messenger:sli_api_error_ratio_2m > (14.4 * 0.01) and sum(rate(messenger_http_server_requests_total[30s])) > 0.1
for: 10s
labels:
severity: page
slo: api-availability
burn_rate: fast
annotations:
summary: API consumes the 1% error budget at fast burn rate
description: Both 30s and 2m windows exceed 14.4x burn rate.
runbook: infrastructure/telemetry/runbooks/level5.md#api-burn-rate
- alert: MessengerAPIBurnRateSlow
expr: messenger:sli_api_error_ratio_1m > (6 * 0.01) and messenger:sli_api_error_ratio_5m > (6 * 0.01) and sum(rate(messenger_http_server_requests_total[1m])) > 0.05
for: 20s
labels:
severity: ticket
slo: api-availability
burn_rate: slow
annotations:
summary: API consumes the 1% error budget at sustained burn rate
description: Both 1m and 5m windows exceed 6x burn rate.
runbook: infrastructure/telemetry/runbooks/level5.md#api-burn-rate
- alert: MessengerAttachmentReadyBurnRateFast
expr: messenger:sli_attachment_slow_ratio_30s > (14.4 * 0.01) and messenger:sli_attachment_slow_ratio_2m > (14.4 * 0.01) and sum(rate(messenger_attachment_ready_duration_seconds_count[30s])) > 0
for: 10s
labels:
severity: page
slo: attachment-ready
burn_rate: fast
annotations:
summary: Attachment ready latency consumes its error budget quickly
description: More than 14.4% of completed attachments exceed 10s in both windows.
runbook: infrastructure/telemetry/runbooks/level5.md#attachment-ready-burn-rate
- alert: MessengerAttachmentReadyBurnRateSlow
expr: messenger:sli_attachment_slow_ratio_1m > (6 * 0.01) and messenger:sli_attachment_slow_ratio_5m > (6 * 0.01) and sum(rate(messenger_attachment_ready_duration_seconds_count[1m])) > 0
for: 20s
labels:
severity: ticket
slo: attachment-ready
burn_rate: slow
annotations:
summary: Attachment ready latency consumes its error budget persistently
description: More than 6% of completed attachments exceed 10s in both windows.
runbook: infrastructure/telemetry/runbooks/level5.md#attachment-ready-burn-rate
@@ -0,0 +1,24 @@
# Runbook уровня 4
## API high error rate
1. Сравнить error ratio с RPS на dashboard.
2. Найти в Loki `{service_name="messenger-api"} | status_class="5xx"`.
3. Открыть `trace_id` в Tempo.
4. Ошибочный `postgresql.*` client span указывает на БД; медленный server span без медленного DB child — на handler/внешнюю зависимость.
5. Проверить DB pool used/capacity и rate waits.
6. После восстановления создать успешные запросы и дождаться `resolved`.
## Queue lag growing
1. Сравнить `messenger_queue_depth` и `messenger_queue_oldest_job_age_seconds`.
2. Проверить worker busy/capacity и `attachment_job_failed` в Loki.
3. Открыть consumer trace и S3/PostgreSQL child spans.
4. Восстановить worker; depth/age должны вернуться к нулю, alert — в `resolved`.
## Telemetry backend unavailable
1. Проверить `otelcol_exporter_queue_size`, capacity и failure counters.
2. Memory limiter — 192 MiB при container limit 256 MiB; exporter queues — 256 batches.
3. API/очередь не зависят от Loki/Tempo. После 30 s retry telemetry может отбрасываться — это bounded degradation.
4. После восстановления backend проверить уменьшение очереди и появление новых сигналов.
@@ -0,0 +1,31 @@
# Runbook уровня 5: SLO burn rate
## SLO и приоритет
- Policy window — 7 дней, что совпадает с retention Prometheus.
- API availability SLO: не менее 99% HTTP-запросов без 5xx (`messenger:slo_api_success_ratio_7d`).
- Attachment ready SLO: не менее 99% успешно завершённых attachments переходят в `ready` не позднее 10 секунд после durable acceptance (`messenger:slo_attachment_ready_ratio_7d`).
- `fast` (14.4x, 30s + 2m) — page: бюджет расходуется достаточно быстро для немедленного вмешательства.
- `slow` (6x, 1m + 5m) — ticket: деградация устойчивее, но допускает более спокойную диагностику.
- Оба окна должны нарушаться одновременно. Traffic guard исключает алерт при отсутствии наблюдений.
## API burn rate
1. В Prometheus открыть `ALERTS{alertname=~"MessengerAPIBurnRate(Fast|Slow)"}` и записать `activeAt`.
2. Сравнить `messenger:sli_api_error_ratio_30s`, `_1m`, `_2m`, `_5m` и RPS. Одно короткое окно без длинного не считается burn-rate инцидентом.
3. В Loki выполнить `{service_name="messenger-api"} | status_class="5xx"` и взять свежие `request_id`/`trace_id`.
4. Открыть trace в Tempo. `postgresql.acquire` error означает исчерпание/недоступность pool; `postgresql.*` query error — ошибку операции; медленный server span без DB/S3 child указывает на handler.
5. Проверить `messenger_db_pool_connections`, `messenger_db_pool_waits_total`, process RAM/CPU и health зависимостей.
6. Восстановить зависимость, создать контрольные успешные запросы. Зафиксировать момент исчезновения alert и recovery time.
## Attachment ready burn rate
1. Сравнить `messenger:sli_attachment_slow_ratio_30s`, `_1m`, `_2m`, `_5m` с queue depth/oldest age.
2. Проверить `messenger_worker_busy / messenger_worker_capacity`; saturation около 1 при растущей очереди означает недостаточную worker capacity.
3. Найти `attachment_job_failed`/`attachment_job_completed` в Loki и перейти по trace ID к producer/consumer spans.
4. Ошибка `s3.*` указывает на object storage; `postgresql.*` — на DB; длинный разрыв между producer и consumer — на queue/worker.
5. Восстановить worker/backend. Убедиться, что новые attachments укладываются в 10 секунд, оба burn-rate alert исчезли, queue age вернулся к нулю.
## Проверка ложного срабатывания
`tests/slo_burn_rate.py` сначала создаёт большой успешный baseline, затем короткий ограниченный 5xx burst. В течение observation window ни `Fast`, ни `Slow` не должны перейти в `pending` или `firing`. Далее тот же тест создаёт длительную DB-деградацию и измеряет detection/recovery. Это отделяет чувствительность к реальному расходованию бюджета от реакции на единичную ошибку.
@@ -0,0 +1,21 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
compactor:
compaction:
block_retention: 168h