#!/usr/bin/env python3 """Generate the Grafana dashboard infra/grafana/dashboards/messenger.json (provisioned at start). python scripts/build_dashboard.py Every panel names its query and unit here, in one place (docs/OBSERVABILITY.md copies the list). Percentiles are ALWAYS histogram_quantile over buckets summed `by (le)` across every replica - never an average of per-replica percentiles. Datasource UIDs are the fixed provisioned ones. """ from __future__ import annotations import json import sys from pathlib import Path OUT = Path(__file__).resolve().parents[1] / "infra" / "grafana" / "dashboards" / "messenger.json" PROM = {"type": "prometheus", "uid": "prometheus"} LOKI = {"type": "loki", "uid": "loki"} TEMPO = {"type": "tempo", "uid": "tempo"} BUSINESS = 'job="messenger-api", http_route!~"/health/.*"' panels: list[dict] = [] _next_id = [1] _y = [0] def _id() -> int: _next_id[0] += 1 return _next_id[0] def row(title: str) -> None: panels.append({"type": "row", "title": title, "id": _id(), "collapsed": False, "panels": [], "gridPos": {"h": 1, "w": 24, "x": 0, "y": _y[0]}}) _y[0] += 1 class Grid: """Places panels left to right, wrapping at 24 columns.""" def __init__(self) -> None: self.x = 0 self.h = 0 def place(self, w: int, h: int) -> dict: if self.x + w > 24: _y[0] += self.h self.x, self.h = 0, 0 pos = {"h": h, "w": w, "x": self.x, "y": _y[0]} self.x += w self.h = max(self.h, h) return pos def end(self) -> None: _y[0] += self.h self.x, self.h = 0, 0 grid = Grid() def ts(title: str, targets: list[tuple[str, str]], unit: str, description: str, *, w: int = 8, h: int = 8, stack: bool = False, minimum: float | None = 0, maximum: float | None = None, thresholds=None) -> None: defaults: dict = {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10 if not stack else 40, "showPoints": "never", "stacking": {"mode": "normal" if stack else "none", "group": "A"}}} if minimum is not None: defaults["min"] = minimum if maximum is not None: defaults["max"] = maximum if thresholds: defaults["thresholds"] = {"mode": "absolute", "steps": thresholds} defaults["custom"]["thresholdsStyle"] = {"mode": "line+area"} panels.append({ "type": "timeseries", "title": title, "id": _id(), "datasource": PROM, "description": description + f"\n\nUnit: {unit}.", "gridPos": grid.place(w, h), "fieldConfig": {"defaults": defaults, "overrides": []}, "options": {"legend": {"displayMode": "list", "placement": "bottom", "showLegend": True}, "tooltip": {"mode": "multi", "sort": "desc"}}, "targets": [{"refId": chr(65 + i), "datasource": PROM, "expr": expr, "legendFormat": legend, "range": True} for i, (expr, legend) in enumerate(targets)], }) def stat(title: str, expr: str, unit: str, description: str, steps, *, w: int = 6, h: int = 5, decimals: int = 2) -> None: panels.append({ "type": "stat", "title": title, "id": _id(), "datasource": PROM, "description": description + f"\n\nUnit: {unit}.", "gridPos": grid.place(w, h), "fieldConfig": {"defaults": {"unit": unit, "decimals": decimals, "thresholds": {"mode": "absolute", "steps": steps}}, "overrides": []}, "options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False}, "colorMode": "background", "graphMode": "area", "textMode": "value"}, "targets": [{"refId": "A", "datasource": PROM, "expr": expr, "instant": False, "range": True}], }) def q(phi: float, metric: str, selector: str, window: str = "$__rate_interval", by: str = "") -> str: group = f"le{', ' + by if by else ''}" return f"histogram_quantile({phi}, sum by ({group}) (rate({metric}_bucket{{{selector}}}[{window}])))" # =============================================================================== API row("API: requests, errors, latency (all replicas)") ts("Requests per second by route", [(f"sum by (http_route) (rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "{{http_route}}")], "reqps", "Business requests (no /health/*) per second, summed over the API replicas. " "Counter = _count of the histogram http.server.request.duration (no second instrument).", stack=True) ts("Error ratio (5xx and 4xx / all business requests)", [(f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"5xx\"}}[$__rate_interval])) or vector(0)) " f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "5xx (SLI: server failures)"), (f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"4xx\"}}[$__rate_interval])) or vector(0)) " f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "4xx (client errors, not in the SLI)")], "percentunit", "Numerator: 5xx (or 4xx) business requests; denominator: all business requests. " "Alert MessengerApiHighErrorRate: 5xx > 5 % for 1 min.", thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 0.05}]) ts("Latency p50 / p95 / p99 (all routes, all replicas)", [(q(0.50, "http_server_request_duration_seconds", BUSINESS), "p50"), (q(0.95, "http_server_request_duration_seconds", BUSINESS), "p95"), (q(0.99, "http_server_request_duration_seconds", BUSINESS), "p99")], "s", "histogram_quantile over the buckets of http.server.request.duration summed by le across replicas " "(buckets 1 ms ... 10 s). Not an average, not per-replica p99s averaged.") ts("p95 by route", [(q(0.95, "http_server_request_duration_seconds", BUSINESS, by="http_route"), "{{http_route}}")], "s", "Per route template, buckets of all replicas.", w=12) ts("Requests in flight by replica", [("sum by (instance) (http_server_active_requests{job=\"messenger-api\"})", "{{instance}}")], "short", "UpDownCounter http.server.active_requests per API replica (saturation of the HTTP layer).", w=12) grid.end() # =============================================================================== worker row("Worker and queue") ts("Jobs handled per second by outcome", [("sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))", "{{outcome}}")], "ops", "messenger.jobs.processed: succeeded / retry / failed / fenced / superseded / noop_* / deferred / rejected.", stack=True) ts("Job duration p50 / p95 / p99 (succeeded)", [(q(0.50, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p50"), (q(0.95, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p95"), (q(0.99, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p99")], "s", "One delivery in the worker: claim -> S3 read -> variants -> S3 writes -> COMMIT -> ack.") ts("Time to ready p50 / p95 / p99 (uploads)", [(q(0.50, "messenger_attachment_time_to_ready_seconds", ""), "p50"), (q(0.95, "messenger_attachment_time_to_ready_seconds", ""), "p95"), (q(0.99, "messenger_attachment_time_to_ready_seconds", ""), "p99")], "s", "From the durable acceptance (job COMMIT before 202) to the COMMIT of status ready. " "Includes queue wait and retries. SLO: 99 % within 30 s.") ts("Queue depth (PostgreSQL) and outbox", [("max by (state) (messenger_queue_depth)", "jobs {{state}}"), ("max by (state) (messenger_outbox_pending)", "outbox {{state}}")], "short", "messenger.queue.depth: unfinished jobs (queued incl. retry wait / processing); " "messenger.outbox.pending: unpublished messages (due / delayed). Reported by the relay every 5 s.") ts("Oldest job age / oldest due outbox row", [("max(messenger_queue_oldest_age_seconds)", "oldest unfinished job"), ("max(messenger_outbox_oldest_age_seconds)", "oldest due outbox row (broker)")], "s", "Age of the oldest unfinished job (now - acceptance). Grows when nobody processes the queue. " "Alert MessengerQueueLagGrowing: > 60 s for 1 min with queued jobs.", thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 60}]) ts("Worker saturation (busy / capacity)", [("sum(messenger_worker_busy) / sum(messenger_worker_capacity)", "busy share")], "percentunit", "messenger.worker.busy (attempts running) / messenger.worker.capacity (WORKER_CONCURRENCY), " "all worker processes. 100 % for long = the worker is the bottleneck.", maximum=1) grid.end() # =============================================================================== DB and resources row("Database pool and resources") ts("DB pool: used / max, waiting requests", [("sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", "{{job}} used"), ("sum by (job) (db_client_connection_max)", "{{job}} max"), ("sum by (job) (db_client_connection_pending_requests)", "{{job}} waiting")], "short", "psycopg_pool counters per service (all replicas summed). Waiting > 0 = pool exhausted.") ts("DB unit of work p95 by service", [(q(0.95, "db_client_operation_duration_seconds", "", by="job"), "{{job}}")], "s", "db.client.operation.duration: pool wait + statements + COMMIT of one Database.run().") ts("DB pool wait p95 by service", [(q(0.95, "db_client_connection_wait_time_seconds", "", by="job"), "{{job}}")], "s", "db.client.connection.wait_time: time to get a connection from the pool.") ts("Container CPU (cores)", [("sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", "{{job}} {{instance}}"), ("rate(otelcol_process_cpu_seconds[$__rate_interval])", "otel-collector")], "short", "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.", w=12) ts("Container memory", [("sum by (job, instance) (container_memory_usage_bytes)", "{{job}} {{instance}}"), ("otelcol_process_memory_rss", "otel-collector RSS")], "bytes", "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).", w=12) grid.end() # =============================================================================== SLO row("SLO (docs/SLO.md) and alerts") stat("Availability, last 1 h (target 99 %)", "1 - messenger:http_error_ratio:rate1h", "percentunit", "1 - 5xx/all business requests over 1 h.", [{"color": "red", "value": None}, {"color": "orange", "value": 0.99}, {"color": "green", "value": 0.995}], decimals=3) stat("Requests under 250 ms, last 5 min (target 95 %)", "messenger:http_fast_ratio:rate5m", "percentunit", "Share of business requests in buckets le=0.25.", [{"color": "red", "value": None}, {"color": "green", "value": 0.95}], decimals=3) stat("Uploads ready within 30 s, last 1 h (target 99 %)", "messenger:ready_within_30s_ratio:rate1h", "percentunit", "Share of uploads with time_to_ready <= 30 s.", [{"color": "red", "value": None}, {"color": "green", "value": 0.99}], decimals=3) stat("Alerts firing", "count(ALERTS{alertstate=\"firing\"}) or vector(0)", "none", "Number of firing Prometheus alerts (table below).", [{"color": "green", "value": None}, {"color": "red", "value": 1}], decimals=0) panels.append({ "type": "table", "title": "Alerts (pending / firing)", "id": _id(), "datasource": PROM, "description": "ALERTS series of Prometheus (rules: infra/prometheus/rules/alerts.yml, runbook: docs/RUNBOOK.md).", "gridPos": grid.place(24, 6), "targets": [{"refId": "A", "datasource": PROM, "expr": "ALERTS", "instant": True, "format": "table"}], "transformations": [{"id": "organize", "options": {"excludeByName": {"Time": True, "Value": True, "__name__": True}, "indexByName": {}, "renameByName": {}}}], "fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True}, }) grid.end() # =============================================================================== telemetry pipeline row("Telemetry pipeline (Collector, SDK)") ts("Collector: spans accepted / sent / failed per second", [("sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", "accepted"), ("sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", "refused (memory_limiter)"), ("sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", "sent to Tempo"), ("sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", "send failed (dropped)")], "ops", "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).") ts("Collector: logs and metric points per second", [("sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", "logs accepted"), ("sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", "logs failed"), ("sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", "metric points accepted"), ("sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", "metric points failed")], "ops", "Same for the logs and metrics pipelines.") ts("Collector: exporter queues", [("max by (exporter) (otelcol_exporter_queue_size)", "{{exporter}} size"), ("max by (exporter) (otelcol_exporter_queue_capacity)", "{{exporter}} capacity")], "short", "Bounded sending_queue (batches) per exporter: fills while a backend is down, never above capacity.") ts("SDK: spans recorded vs exported (all processes)", [("sum by (job) (rate(messenger_telemetry_spans_ended_total[$__rate_interval]))", "{{job}} recorded"), ("sum by (job, result) (rate(messenger_telemetry_spans_exported_total[$__rate_interval]))", "{{job}} export {{result}}")], "ops", "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).", w=12) ts("Telemetry components up", [("up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", "{{job}}")], "short", "1 = the scrape succeeded.", w=12, maximum=1) grid.end() # =============================================================================== logs and traces row("Logs and traces") panels.append({ "type": "logs", "title": "Application logs (Loki): warnings and errors", "id": _id(), "datasource": LOKI, "description": "OTLP log records of api/relay/worker. Expand a line: trace_id links to Tempo. " "Query: {service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\".", "gridPos": grid.place(12, 10), "targets": [{"refId": "A", "datasource": LOKI, "expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\"", "queryType": "range"}], "options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending", "dedupStrategy": "none", "prettifyLogMessage": False}, }) panels.append({ "type": "table", "title": "Recent upload traces (Tempo)", "id": _id(), "datasource": TEMPO, "description": "TraceQL: POST of an attachment. Click a trace id: upload -> enqueue -> publish -> process -> S3/DB.", "gridPos": grid.place(12, 10), "targets": [{"refId": "A", "datasource": TEMPO, "queryType": "traceql", "limit": 20, "tableType": "traces", "query": "{ span.http.route = \"/api/v1/chats/{chat_id}/attachments\" }"}], "fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True}, }) grid.end() dashboard = { "uid": "messenger-lab6", "title": "Messenger lab 6: API, worker, queue, SLO", "description": "Generated by scripts/build_dashboard.py - edit the script, not the JSON.", "tags": ["messenger", "lab6"], "timezone": "browser", "schemaVersion": 39, "version": 1, "editable": False, "graphTooltip": 1, "refresh": "10s", "time": {"from": "now-30m", "to": "now"}, "templating": {"list": []}, "annotations": {"list": [{"builtIn": 1, "datasource": {"type": "grafana", "uid": "-- Grafana --"}, "enable": True, "hide": True, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard"}]}, "panels": panels, } def main() -> int: OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text(json.dumps(dashboard, indent=1, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n") print(f"written {OUT.relative_to(OUT.parents[3])}: {len(panels)} panels") return 0 if __name__ == "__main__": sys.exit(main())