TExcelTAD
Home › Observability: Prometheus, Grafana, Loki & OpenTelemetry › Mini Project: Instrument, Dashboard & Alert linkly

Mini Project: Instrument, Dashboard & Alert linkly

The project brings the course together for one service: linkly's metrics contract, recording rules, alerts with unit tests, Alertmanager routing with tests, and a dashboard that is smoke-tested against real data. Each part is a real session; together they are the files you'd commit to linkly's repository under observability/, and the observability part of the DevOps Capstone.

text
observability/
├── METRICS.md                    the metrics contract (step 1)
├── rules/linkly.yml              recording + alerting rules (step 2)
├── rules/linkly.test.yml         promtool tests (step 3)
├── alertmanager/linkly.yml       routing (step 4)
├── dashboards/linkly-red.json    generated dashboard (step 5)
└── ci.sh                         runs every check (step 6)

Step 1: the metrics contract

linkly is instrumented as in Instrumenting a Go Service, plus OTel tracing (OpenTelemetry SDKs) and slog JSON logs with trace_id (Structured JSON Logging). The contract that dashboards and alerts rely on:

Metric Type Labels
http_requests_total counter route (template), code
http_request_duration_seconds histogram, buckets 0.005 … 2.5 incl. 0.3 (the SLO threshold) route
linkly_db_connections_in_use, linkly_db_connections_max gauges –
linkly_cache_requests_total counter result = hit/miss
linkly_build_info gauge = 1 version, revision

Plus job, instance, env from scraping. Treat renaming any of these as a breaking change.

Step 2 and 3: rules and their tests

Recording rules give the dashboard and alerts cheap, named series; alerts page on symptoms (errors, latency, the service gone) and ticket on saturation. The test covers each alert firing and not firing:

bash · try it yourself
mkdir -p observability/rules && cd observability
cat > rules/linkly.yml <<'YML'
groups:
  - name: linkly-recording
    rules:
      - record: job_env:http_requests:rate5m
        expr: sum by (job, env) (rate(http_requests_total{job="linkly"}[5m]))
      - record: job_env:http_request_errors:ratio_rate5m
        expr: |
          sum by (job, env) (rate(http_requests_total{job="linkly", code=~"5.."}[5m]))
            / sum by (job, env) (rate(http_requests_total{job="linkly"}[5m]))
      - record: job_env_route:http_request_duration_seconds:p99_5m
        expr: histogram_quantile(0.99, sum by (job, env, route, le) (rate(http_request_duration_seconds_bucket{job="linkly"}[5m])))
  - name: linkly-alerts
    rules:
      - alert: LinklyHighErrorRate
        expr: job_env:http_request_errors:ratio_rate5m{env="prod"} > 0.05
        for: 5m
        labels: {severity: page, team: links}
        annotations:
          summary: 'linkly 5xx ratio {{ $value | humanizePercentage }} in {{ $labels.env }}'
          runbook_url: https://runbooks.example.com/linkly/high-error-rate
      - alert: LinklySlowRoute
        expr: job_env_route:http_request_duration_seconds:p99_5m{env="prod"} > 0.3
        for: 10m
        labels: {severity: page, team: links}
        annotations:
          summary: 'p99 of {{ $labels.route }} is {{ $value | humanizeDuration }}'
      - alert: LinklyDown
        expr: absent(up{job="linkly", env="prod"} == 1)
        for: 2m
        labels: {severity: page, team: links}
        annotations:
          summary: 'no healthy linkly target in prod'
      - alert: LinklyDBPoolSaturated
        expr: sum by (env) (linkly_db_connections_in_use) / sum by (env) (linkly_db_connections_max) > 0.9
        for: 15m
        labels: {severity: ticket, team: links}
        annotations:
          summary: 'DB pool {{ $value | humanizePercentage }} used in {{ $labels.env }}'
YML
cat > rules/linkly.test.yml <<'YML'
rule_files: [linkly.yml]
evaluation_interval: 1m
tests:
  - name: errors page after 5m, not before
    interval: 1m
    input_series:
      - series: 'http_requests_total{job="linkly", env="prod", instance="a", route="/{code}", code="302"}'
        values: '0+600x40'
      - series: 'http_requests_total{job="linkly", env="prod", instance="a", route="/links", code="500"}'
        values: '0+6x10 66+60x30'        # 1% errors, then about 9% from minute 10
      - series: 'up{job="linkly", env="prod", instance="a"}'
        values: '1x40'
    alert_rule_test:
      - {eval_time: 9m, alertname: LinklyHighErrorRate, exp_alerts: []}
      - {eval_time: 14m, alertname: LinklyHighErrorRate, exp_alerts: []}
      - eval_time: 20m
        alertname: LinklyHighErrorRate
        exp_alerts:
          - exp_labels: {severity: page, team: links, job: linkly, env: prod}
            exp_annotations:
              summary: 'linkly 5xx ratio 9.091% in prod'
              runbook_url: https://runbooks.example.com/linkly/high-error-rate
      - {eval_time: 20m, alertname: LinklyDown, exp_alerts: []}

  - name: slow route pages, fast route doesn't
    interval: 1m
    input_series:      # per minute: /links 60 requests, all between 0.3 and 1 s; /{code} 600 under 5 ms
      - {series: 'http_request_duration_seconds_bucket{job="linkly", env="prod", route="/links", le="0.3"}', values: '0x30'}
      - {series: 'http_request_duration_seconds_bucket{job="linkly", env="prod", route="/links", le="1"}', values: '0+60x30'}
      - {series: 'http_request_duration_seconds_bucket{job="linkly", env="prod", route="/links", le="+Inf"}', values: '0+60x30'}
      - {series: 'http_request_duration_seconds_bucket{job="linkly", env="prod", route="/{code}", le="0.005"}', values: '0+600x30'}
      - {series: 'http_request_duration_seconds_bucket{job="linkly", env="prod", route="/{code}", le="+Inf"}', values: '0+600x30'}
    alert_rule_test:
      - eval_time: 20m
        alertname: LinklySlowRoute
        exp_alerts:
          - exp_labels: {severity: page, team: links, job: linkly, env: prod, route: /links}
            exp_annotations: {summary: 'p99 of /links is 993ms'}

  - name: all targets down
    interval: 1m
    input_series:
      - {series: 'up{job="linkly", env="prod", instance="a"}', values: '1x5 0x10'}
      - {series: 'up{job="linkly", env="prod", instance="b"}', values: '1x5 stale'}   # b vanished: Prometheus writes a staleness marker
    alert_rule_test:
      - {eval_time: 6m, alertname: LinklyDown, exp_alerts: []}
      - eval_time: 9m
        alertname: LinklyDown
        exp_alerts:
          - exp_labels: {severity: page, team: links}
            exp_annotations: {summary: 'no healthy linkly target in prod'}

  - name: pool saturation is a ticket
    interval: 1m
    input_series:
      - {series: 'linkly_db_connections_in_use{env="prod", instance="a"}', values: '19x30'}
      - {series: 'linkly_db_connections_max{env="prod", instance="a"}', values: '20x30'}
    alert_rule_test:
      - eval_time: 20m
        alertname: LinklyDBPoolSaturated
        exp_alerts:
          - exp_labels: {severity: ticket, team: links, env: prod}
            exp_annotations: {summary: 'DB pool 95% used in prod'}
YML
promtool check rules rules/linkly.yml
promtool test rules rules/linkly.test.yml
Checking rules/linkly.yml
  SUCCESS: 7 rules found

  SUCCESS

Design choices worth noticing:

  • LinklyDown uses absent(up{…} == 1): it fires when no target is healthy or when the targets vanished entirely (instance b in the test disappears, a goes to 0). A plain up == 0 would miss the second case.
  • The latency alert uses the recorded p99 per route; the bucket at 0.3 s makes "fraction of requests under the SLO" exact for the SRE course's SLO burn-rate alerts, which build on these recording rules.
  • The pool alert is a ticket: saturation predicts trouble but isn't user-visible yet.

Step 4: routing, tested

bash · try it yourself
mkdir -p observability/alertmanager && cd observability
cat > alertmanager/linkly.yml <<'YML'
route:
  receiver: platform-slack
  group_by: [alertname, env]
  routes:
    - matchers: [team="links", severity="page", env="prod"]
      receiver: links-pagerduty
      continue: true
    - matchers: [team="links", severity=~"page|ticket"]
      receiver: links-slack
inhibit_rules:
  - source_matchers: [alertname="LinklyDown"]
    target_matchers: [team="links", alertname!="LinklyDown"]
    equal: [env]
receivers:
  - name: platform-slack
    slack_configs: [{api_url_file: /etc/alertmanager/secrets/slack-platform, channel: '#platform-alerts'}]
  - name: links-slack
    slack_configs: [{api_url_file: /etc/alertmanager/secrets/slack-links, channel: '#links-alerts', send_resolved: true}]
  - name: links-pagerduty
    pagerduty_configs: [{routing_key_file: /etc/alertmanager/secrets/pd-links}]
YML
amtool check-config alertmanager/linkly.yml | head -1
while read -r want labels; do
  got=$(amtool config routes test --config.file=alertmanager/linkly.yml $labels)
  [ "$got" = "$want" ] && echo "ok    $labels -> $got" || echo "FAIL  $labels -> $got (want $want)"
done <<'CASES'
links-pagerduty,links-slack  alertname=LinklyHighErrorRate team=links severity=page env=prod
links-slack                  alertname=LinklyHighErrorRate team=links severity=page env=staging
links-slack                  alertname=LinklyDBPoolSaturated team=links severity=ticket env=prod
platform-slack               alertname=NodeDiskFilling severity=ticket env=prod
CASES
Checking 'alertmanager/linkly.yml'  SUCCESS
ok    alertname=LinklyHighErrorRate team=links severity=page env=prod -> links-pagerduty,links-slack
ok    alertname=LinklyHighErrorRate team=links severity=page env=staging -> links-slack
ok    alertname=LinklyDBPoolSaturated team=links severity=ticket env=prod -> links-slack
ok    alertname=NodeDiskFilling severity=ticket env=prod -> platform-slack

Production pages go to PagerDuty and the team channel; staging never pages; anything without a team falls back to the platform channel. When linkly is completely down, the inhibition stops its other alerts from piling on.

Step 5: the dashboard, smoke-tested on real data

The dashboard is generated (as in Dashboards as Code). A dashboard can be valid JSON and still show "No data" everywhere because of a typo in a metric name. The smoke test extracts every panel query, substitutes the variables, and runs it against a Prometheus loaded with an hour of realistic linkly data; every panel must return at least one series:

bash · try it yourself
mkdir -p observability/dashboards && cd observability
python3 - > dashboards/linkly-red.json <<'PY'
import json
SEL = 'job="linkly", env="$env"'
def ts(pid, title, expr, unit, x, y):
    return {"id": pid, "type": "timeseries", "title": title, "datasource": {"type": "prometheus", "uid": "${datasource}"},
            "gridPos": {"x": x, "y": y, "w": 12, "h": 8}, "fieldConfig": {"defaults": {"unit": unit}},
            "targets": [{"refId": "A", "expr": expr}]}
panels = [
    ts(1, "Requests / s", f'sum by (route) (rate(http_requests_total{{{SEL}}}[$__rate_interval]))', "reqps", 0, 0),
    ts(2, "5xx ratio", f'job_env:http_request_errors:ratio_rate5m{{{SEL}}}', "percentunit", 12, 0),
    ts(3, "p99 by route", f'histogram_quantile(0.99, sum by (route, le) (rate(http_request_duration_seconds_bucket{{{SEL}}}[$__rate_interval])))', "s", 0, 8),
    ts(4, "DB pool used", f'sum(linkly_db_connections_in_use{{env="$env"}}) / sum(linkly_db_connections_max{{env="$env"}})', "percentunit", 12, 8),
    ts(5, "Cache hit ratio", f'sum(rate(linkly_cache_requests_total{{{SEL}, result="hit"}}[$__rate_interval])) / sum(rate(linkly_cache_request_total{{{SEL}}}[$__rate_interval]))', "percentunit", 0, 16),
]
print(json.dumps({"uid": "linkly-red", "title": "linkly / RED", "schemaVersion": 42, "panels": panels,
                  "templating": {"list": [{"name": "env", "type": "query", "query": 'label_values(up{job="linkly"}, env)'}]}}, indent=2))
PY

python3 - > data.om <<'PY'
start = 1767261600                                    # 2026-01-01T10:00:00Z, one hour every 15 s
lab = 'job="linkly",env="prod",instance="api-1"'
print("# TYPE http_requests_total counter")
print("# TYPE http_request_duration_seconds histogram")
print("# TYPE linkly_cache_requests_total counter")
print("# TYPE linkly_db_connections_in_use gauge")
print("# TYPE linkly_db_connections_max gauge")
print("# TYPE up gauge")
for i in range(241):
    t = start + 15 * i
    for route, code, r in (("/{code}", "302", 9), ("/links", "201", 1), ("/links", "500", 0.05)):
        print(f'http_requests_total{{{lab},route="{route}",code="{code}"}} {r * 15 * i:g} {t}')
    for route, cum in (("/{code}", {"0.005": 8, "0.3": 9, "+Inf": 9}), ("/links", {"0.005": 0, "0.3": 0.9, "+Inf": 1.05})):
        for le, r in cum.items():
            print(f'http_request_duration_seconds_bucket{{{lab},route="{route}",le="{le}"}} {r * 15 * i:g} {t}')
    for result, r in (("hit", 8), ("miss", 1)):
        print(f'linkly_cache_requests_total{{{lab},result="{result}"}} {r * 15 * i} {t}')
    print(f'linkly_db_connections_in_use{{{lab}}} {6 + i % 3} {t}')
    print(f'linkly_db_connections_max{{{lab}}} 20 {t}')
    print(f'up{{{lab}}} 1 {t}')
print("# EOF")
PY
promtool tsdb create-blocks-from openmetrics data.om data >/dev/null
echo "global: {}" > prometheus.yml
prometheus --config.file=prometheus.yml --storage.tsdb.path=data --storage.tsdb.retention.time=100y \
  --web.listen-address=127.0.0.1:9090 >prom.log 2>&1 &
for i in $(seq 100); do curl -sf 127.0.0.1:9090/-/ready >/dev/null && break; sleep 0.2; done

fail=0
while IFS=
  

\t' read -r title expr; do
  q=$(printf '%s' "$expr" | sed 's/\$env/prod/g; s/\$__rate_interval/1m/g')
  n=$(curl -s 127.0.0.1:9090/api/v1/query --data-urlencode "query=$q" --data-urlencode time=2026-01-01T10:30:00Z |
      jq '.data.result | length')
  if [ "$n" -gt 0 ]; then echo "ok    $title ($n series)"; else echo "EMPTY $title: $q"; fail=1; fi
done < <(jq -r '.panels[] | [.title, .targets[0].expr] | @tsv' dashboards/linkly-red.json)
exit $fail
ok    Requests / s (2 series)
EMPTY 5xx ratio: job_env:http_request_errors:ratio_rate5m{job="linkly", env="prod"}
ok    p99 by route (2 series)
ok    DB pool used (1 series)
EMPTY Cache hit ratio: sum(rate(linkly_cache_requests_total{job="linkly", env="prod", result="hit"}[1m])) / sum(rate(linkly_cache_request_total{job="linkly", env="prod"}[1m]))

Two panels are empty, and both are real bugs of the kind that ship all the time:

  • 5xx ratio reads a recording rule. The smoke-test server has no rules loaded, so this one is expected: either load rules/linkly.yml into the test Prometheus and let it evaluate, backfill recorded series with promtool tsdb create-blocks-from rules, or test that panel through the rule tests (step 3 already does).
  • Cache hit ratio has a typo: linkly_cache_request_total instead of linkly_cache_requests_total. Without the smoke test it would have shown "No data" in production until someone noticed. Fix the generator and the check passes.

Step 6: one CI script

bash
#!/usr/bin/env bash
# observability/ci.sh: run on every pull request that touches observability/
set -euo pipefail
cd "$(dirname "$0")"
promtool check rules rules/*.yml
promtool test rules rules/*.test.yml
amtool check-config alertmanager/linkly.yml
./routing-tests.sh               # the step 4 loop, with its cases in a file
python3 gen_dashboard.py > dashboards/linkly-red.json && git diff --exit-code dashboards/
./dashboard-smoke-test.sh        # the step 5 loop against a backfilled Prometheus
otelcol-contrib validate --config=collector/otel.yaml

Extensions

  1. Load rules/linkly.yml into the smoke-test Prometheus (rule_files:) and backfill the recorded series with promtool tsdb create-blocks-from rules so the 5xx panel is tested too.
  2. Add a Loki rule that tickets on more than 20 "statement timeout" lines in 5 minutes (LogQL Metric Queries), with a test that pushes fixed log lines to a session Loki.
  3. Add the Collector config from Sampling & Span Metrics and a dashboard row built from traces_span_metrics_*, so RED is visible from traces as well as from the app's own metrics.
  4. Turn the alerts into SLO burn-rate alerts with the SRE course.

Test yourself

Why does LinklyDown use absent(up{…} == 1) rather than up{…} == 0?

  1. It's shorter
  2. It also fires when the targets vanish entirely, not only when they report down
  3. absent is faster
  4. up can't be compared

What did the dashboard smoke test catch that JSON validation could not?

  1. A missing uid
  2. A metric-name typo that would make a panel show "No data"
  3. A wrong colour
  4. A duplicate panel id

Which file in the project encodes "staging alerts never page"?

  1. rules/linkly.yml
  2. alertmanager/linkly.yml (the page route matches env="prod" only), verified by the routing cases
  3. the dashboard
  4. ci.sh