ReinDBby Bandlei

13. Ongoing observability

Brett Rosenblatt · Database tuning guide v1.3 · PDF

Tuning fixes today's problem. Observability keeps tomorrow's from reaching users. The goal is simple to state: see problems before users do, with enough history to explain them, and make the right data visible to the right people.

13.1What to track

LayerSignalsWhy
ExperienceApplication latency and error rates; timeoutsThe symptom users feel; from your APM or service metrics
Database loadDatabase time or average active sessions against CPU cores; throughput; connections (active, idle, idle in transaction)Is the database busier than usual for this hour?
StatementsTop statements by total time; regressions against baseline; new heavy statements; plan changesThe most common cause of change
WaitsTime by wait class over timeWhat kind of problem it is
ContentionBlocking time and chains; deadlocks; long transactionsIntermittent timeouts and stalls
ResourcesCPU; memory; storage latency for reads and writes; IOPS and throughput against provisioned limits; networkThe platform underneath (USE method)
Durability and availabilityReplication lag; age of the last good backup; log, WAL or archive status; failover readinessProblems that are invisible until they are disasters
CapacityStorage used and days until full; growth by table; identity and sequence headroom (an INT key nearing 2.1 billion); file and autoextend limits; log and archive spaceOutages you can see coming weeks ahead
MaintenanceStatistics age; cleanup lag and dead rows; failed maintenance jobsSlow decay that turns into bad plans
Configuration and versionsDrift from approved settings; patch level against the rest of the fleetUnplanned change, and known bugs
Security signalsFailed login spikes; privilege changesNot performance, but the same pipeline can carry them

13.2The shape of a monitoring environment

A monitoring environment: databases and hosts feed collectors and exporters, which feed a time-series store; dashboards and alert rules read from it, and alerts are routed to on-call, chat and ticket tools.
A monitoring environment: databases and hosts feed collectors and exporters, which feed a time-series store; dashboards and alert rules read from it, and alerts are routed to on-call, chat and ticket tools.
  • Collectors and exporters read the databases and hosts: Prometheus exporters (postgres_exporter, mysqld_exporter, Oracle's open-source database observability exporter, community SQL Server exporters), node_exporter and windows_exporter for hosts, cloud metrics such as Amazon CloudWatch, and database monitoring tools such as ReinDB.
  • A time-series store keeps the numbers: Prometheus, or a long-term store behind it, or your cloud's metrics service.
  • Dashboards (Grafana is the common choice) turn the numbers into views for different audiences.
  • Alert rules evaluate the numbers continuously and send notifications through routing rules to on-call tools, chat and tickets.
  • Annotations from your deploy pipeline and change process mark when things changed, on every chart.

Keep everything on one clock (UTC), with consistent database names and labels across tools, so a database is called the same thing on every dashboard and in every alert.

13.3Exporting to Grafana

There are three common ways to get database performance data into Grafana:

  1. Exporters scraped by Prometheus. Live, fine-grained metrics with little effort. Exporters give you raw counters, though: baselines, statement history and drift detection are up to you.
  2. A SQL data source. Grafana can query PostgreSQL, MySQL, SQL Server and other databases directly. Point it at a monitoring repository (your own hourly snapshot tables, for example), never at production tables during busy hours.
  3. Files from a monitoring tool. Scheduled exports of already-processed measurements (baselines, flags, top statements), loaded through a plugin or a data lake.

The Prometheus textfile route gives Grafana ReinDB's baselines and flags next to your other metrics:

  1. Run node_exporter with the textfile collector pointed at a directory, for example --collector.textfile.directory=/var/lib/node_exporter/textfile.
  2. Create a ReinDB export in the Prometheus format with an hourly schedule.
  3. Self-hosted: write the export into that directory. Hosted: have a cron job fetch the file through the export's pull link. Either way, write to a temporary file and rename it, so node_exporter never reads half a file.
  4. Build panels and alert rules on the reindb_* metrics, for example reindb_open_flags, reindb_system, reindb_statement_elapsed_seconds, reindb_wait_average_sessions, reindb_database_size_bytes, reindb_replication_lag_seconds and reindb_last_sample_timestamp_seconds.
# Prometheus alert rules on ReinDB metrics (illustrative thresholds)
groups:
  - name: reindb
    rules:
      - alert: ReinDBHighDriftFlags
        expr: reindb_open_flags{severity="HIGH"} > 0
        for: 15m
        labels:
          severity: ticket
        annotations:
          summary: "{{ $labels.database }} has open HIGH drift flags"
          runbook_url: "https://wiki.example.com/runbooks/database-drift"
      - alert: ReinDBMeasurementsStale
        expr: time() - reindb_last_sample_timestamp_seconds > 3 * 3600
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "No new measurement for {{ $labels.database }} in 3 hours"

The CSV and JSON Lines route suits trend dashboards and data lakes: read the files with a Grafana plugin that loads CSV or JSON over HTTP (such as the Infinity data source), or land them in object storage and query them through a lake engine that Grafana already uses.

13.4Designing dashboards people actually use

  • Build in layers: a fleet overview, then one dashboard per database, then a statement drill-down. Link them so a click moves down a layer with the same time range.
  • Show normal on every chart. A band for the usual range at that hour turns a line into an answer. A spike inside the band is just Monday.
  • Annotate changes: deploys, parameter changes, index builds, failovers.
  • Give each panel a question it answers. "Is load higher than usual?" earns its place. "Buffer cache hit ratio" usually doesn't.
  • Use consistent units and time zones, and label units in titles.
  • Build for each audience: on-call needs "what is wrong right now"; DBAs need statement and wait detail; development teams need their own application's statements (filtered by application or module name, see Chapter 9); managers need service levels and capacity.
  • Keep the top of each dashboard sparse. The first screen should answer "is anything wrong?" in five seconds.

A per-database dashboard that works well, from top to bottom: health and open flags; load against its usual band; waits by class (stacked); top statements (a table with time, calls, time per call and change against usual); contention (blocked sessions, longest wait, oldest transaction); capacity (size, growth, days until full); replication and backups.

13.5Alerts: what to set and how to manage them

Principles that keep alerting useful:

  • Page only for things that are urgent, actionable and real. Everything else goes to a ticket queue or a daily digest. If an alert fires and nobody needs to do anything, it shouldn't page.
  • Alert on symptoms and imminent failures, not every cause: user-visible latency, the database being unreachable, a disk about to fill, replication about to break the recovery point objective.
  • Use baseline-relative conditions for load and latency, and absolute conditions for hard limits.
  • Use a pending period ("for 15 minutes") to avoid flapping on brief spikes.
  • Give every alert an owner, a severity, a short description of the impact, a runbook link and a dashboard link.
  • Group and deduplicate related alerts (by cluster or service) so one incident is one notification.
  • Silence during planned maintenance, with an expiry, and test the whole path (rule, routing, notification) regularly.
  • Review alerts monthly. Delete or fix any alert that fired without leading to action. Alert fatigue is how real pages get ignored.

In Grafana Alerting, those principles map directly onto its building blocks: alert rules (a query, a condition and a pending period), labels (severity, team, service), contact points (where notifications go), notification policies (routing by label, grouping and timing), and silences and mute timings for maintenance windows.

A starter alert catalog:

AlertCondition (adjust to your environment)SeverityFirst action
Database unreachableConnection or measurement failing for 2 to 5 minutesPageCheck host, service and network; fail over if needed
Load far above usualLoad at least 3 times the usual for this hour, for 15 minutesPage if users are affected, otherwise ticketTop statements, waits and blocking now
New high-severity regressionA new HIGH drift flagTicket or chatOpen the statement and its plan history
BlockingA session blocked for more than 5 minutes, or more than 5 waiters behind one blockerPageIdentify the blocker; contact its owner; end it if necessary
Replication lagLag above the recovery point objective, for 5 minutesPageReplica health, long transactions, network
Storage85% used (ticket); 95% used, or fewer than 7 days until full (page)Ticket, then pageGrowth by table; purge, extend or tier
Backup ageNo successful backup for more than 26 hoursTicket, or page for critical systemsFix the job; take a backup
Long transactionAn open transaction older than 1 hourTicketFind the session; it holds back cleanup of old row versions and grows undo or version stores
Identity or sequence headroomAbove 80% of the type's maximumTicketPlan the change to a larger type well ahead
DeadlocksMore than a few per hour, or any for critical transactionsTicketRead the deadlock graph; fix the access order
Measurements staleNo new monitoring data for 3 hoursPage (to the monitoring owner)Fix the collector; you are flying blind

13.6Keeping it optimal: a review rhythm

WhenReview
Daily (5 minutes)Open flags and new regressions; anything degraded or down; failed jobs and backups
WeeklyTop statements and their trend; new heavy statements; this week against last; storage growth; blocking and deadlock history
MonthlyAlert review (remove noise, add what was missed); settings drift; unused and duplicate indexes; capacity forecast; forced plans and hints
QuarterlyVersion and patch levels across the fleet; disaster recovery test; baseline sanity; data tiering and retention review
After every releaseThe same hours before and after, for the statements the release touched

Give each review an owner and a place to record what was found. Postmortems should end with a new check, dashboard panel or alert, so each incident makes the system better at catching the next one.

This is one chapter of the free database tuning guide for PostgreSQL, MySQL, SQL Server and Oracle. Download the whole guide as a PDF.