Monitoring, logging & alerting
Shipping a change is half the job; knowing whether production is healthy is the other half. Building on the observability overview in Concepts & practices, this chapter covers Prometheus and PromQL, dashboards, alerting without noise, SLOs and error budgets with real numbers, and centralised logging.
Metrics, logs and traces
| Metrics | Logs | Traces | |
|---|---|---|---|
| What | Numbers over time | Timestamped event records | One request's path through many services |
| Answers | Is something wrong? How much, since when? | What exactly happened, to which request? | Where did the time go? Which service failed? |
| Tools | Prometheus, CloudWatch | Loki, ELK / OpenSearch | OpenTelemetry, Jaeger, Tempo |
A typical investigation uses all three: a metric alert says errors went up, a trace finds the slow service, its logs explain why.
Prometheus: the pull model
Prometheus pulls (scrapes): every few seconds it sends an HTTP GET to each target's /metrics endpoint and stores the values in its time-series database (15 days by default). Apps expose metrics with a client library; for everything else there are exporters, like node_exporter (port 9100) for a Linux machine's CPU, memory, disk and network. Short batch jobs that finish before a scrape can push to a Pushgateway instead.
up == 0. Grafana only draws; Alertmanager only routes.# what Prometheus reads from http://10.0.2.11:3000/metrics
# HELP http_requests_total Total HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 10427
http_requests_total{method="GET",status="500"} 31
# prometheus.yml
global:
scrape_interval: 15s
rule_files:
- alerts.yml
scrape_configs:
- job_name: node
static_configs:
- targets: ["10.0.2.11:9100", "10.0.2.12:9100"]
- job_name: app
static_configs:
- targets: ["10.0.2.11:3000"]
Each series is a metric name plus labels. A counter only goes up (requests, errors), a gauge goes up and down (memory, queue length), a histogram counts observations into buckets (request durations) for percentiles. Because it pulls, Prometheus notices when a target stops answering and records it in the built-in up metric (1 = scrape worked, 0 = failed).
PromQL by example
up == 0 # which targets are down?
rate(http_requests_total[5m]) # requests per second, averaged over 5 min
sum by (status) (rate(http_requests_total[5m])) # per-second rate, grouped by status code
# error ratio: share of requests that returned 5xx
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m]))
# 95th-percentile latency from a histogram
histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))
# CPU busy % per machine
100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))
# will the root disk fill up within 24 hours at the current trend?
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 24 * 3600) < 0
Rule of thumb: a raw counter is useless on a graph (it just climbs), so always wrap counters in rate() before you sum them. Never rate() a gauge.
Grafana dashboards
Grafana stores no data itself; it queries data sources (Prometheus, Loki, CloudWatch, SQL…) and draws panels. Variables like $instance add a dropdown so one dashboard serves every server. Import community dashboards by ID: "Node Exporter Full" (1860) is the classic for Linux hosts. Put the golden signals across the top and details below.
The four golden signals
Google's SRE book suggests that if you can only measure four things about a user-facing service, measure these:
- Latency: how long requests take. Track slow errors separately from slow successes, and use percentiles (p95, p99), since averages hide the unlucky users.
- Traffic: demand, like requests per second.
- Errors: the rate of failed requests (5xx, and also wrong answers or requests that were too slow).
- Saturation: how full the service is: CPU, memory, disk, connection pools, queue length.
Related checklists: RED (Rate, Errors, Duration) for services, USE (Utilisation, Saturation, Errors) for resources.
Alerting and on-call
Prometheus evaluates alerting rules and sends firing alerts to Alertmanager, which groups related alerts, removes duplicates, applies silences during maintenance, and routes them to Slack, email or a paging tool such as PagerDuty or Opsgenie.
# alerts.yml
groups:
- name: app
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m])) > 0.05
for: 5m # must stay true for 5 minutes before firing
labels:
severity: page
annotations:
summary: "More than 5% of requests are failing"
description: "Error ratio is {{ $value | humanizePercentage }}."
$ promtool check config prometheus.yml # also checks the rule files it loads
- Page on symptoms users feel (errors, latency, downtime), not every cause. High CPU with happy users belongs on a dashboard or in a ticket.
- Every page must be actionable, with a short runbook linked in the annotations. If the answer is "ignore it", fix or delete the alert: teams paged constantly start ignoring pages.
for:stops flapping on brief spikes.- On-call is a rotation of engineers who respond to pages, with escalation if nobody acknowledges. After a major incident, write a blameless postmortem: timeline, root cause, follow-ups, focused on the system rather than who slipped.
SLI, SLO, SLA and the error budget, with numbers
A quick reminder: the SLI is what you measure, the SLO is your internal target, the SLA is the contract with customers. Say your API promises customers 99.5% (the SLA, with credits if missed) and targets 99.9% internally (the SLO), measured as "the share of requests that return a non-5xx response within 500 ms, over 30 days". The stricter SLO warns you long before the contract is at risk.
- The API serves 200 requests per minute. 30 days = 43,200 minutes, so 8,640,000 requests.
- Error budget = 100% − 99.9% = 0.1% of requests = 8,640 bad requests allowed in 30 days. (In time terms, 0.1% of 30 days is 43.2 minutes of total outage.)
- On day 12, a bad deploy makes half the requests fail for 30 minutes: 30 × 200 × 50% = 3,000 bad requests. That's about 35% of the budget gone; 5,640 remain.
- Burn rate is how fast you're spending: the actual error rate divided by the allowed one. A steady 0.5% error rate is 0.5 / 0.1 = a burn rate of 5, which would use up a 30-day budget in 30 / 5 = 6 days.
Teams agree in advance what happens when the budget runs low: freeze risky releases and spend the time on reliability. Good SLO alerts page on fast burn; for example, the Google SRE workbook suggests paging when 2% of a 30-day budget is spent within one hour (a burn rate of 14.4).
| SLO | Allowed downtime per 30 days |
|---|---|
| 99% | 7 h 12 min |
| 99.5% | 3 h 36 min |
| 99.9% | 43 min 12 s |
| 99.95% | 21 min 36 s |
| 99.99% | 4 min 19 s |
Centralised logging
With many servers, and containers that vanish with their logs, SSH plus grep doesn't scale. An agent on each machine ships logs to a central store searchable in one place:
- ELK / Elastic Stack: Elasticsearch indexes the full text of every line, Logstash or Beats collect, Kibana searches. Powerful, but indexing everything costs storage and memory. OpenSearch is the open-source fork.
- Grafana Loki: indexes only a few labels (app, env, host) and stores lines compressed, so it's much cheaper, and you query it in Grafana beside your metrics. Collect with Grafana Alloy (Promtail reached end of life in March 2026), Fluent Bit or Vector.
{app="api", env="prod"} |= "error" # lines containing "error"
{app="api"} | json | status >= 500 # parse JSON logs, filter on a field
sum by (app) (rate({env="prod"} |= "error" [5m])) # error lines per second, per app
Log structured JSON with consistent fields (level, message, request ID) so you can filter logs like data and follow one request across services. Never log passwords, tokens or personal data, and set a retention period: logs get expensive.
Common problems
- Target DOWN on Prometheus's Status → Targets page: "connection refused" means nothing listens on that port; "context deadline exceeded" usually means a firewall or security group is blocking the scrape.
- Grafana shows "No data": wrong data source, a time range with no data, or a typo in the metric or label name. Run the query in Prometheus's own UI first.
- Prometheus using huge amounts of memory: high cardinality. Every unique label combination is a separate series, so labels like user ID, email or full URL create millions. Keep label values to small, fixed sets.
- Counters drop to zero after a deploy: they reset on restart.
rate()handles that; raw values don't.