Monitoring & Operations

A database in production is never finished. It grows, its workload shifts, its hardware ages, and its maintenance tasks must keep pace. Operations is the discipline of knowing how the database is doing before users complain, and of handling routine work and incidents through written, repeatable procedures. This final lesson ties the roadmap together with service objectives, monitoring, capacity planning and runbooks. Examples use PostgreSQL. For monitoring platforms in general, see the TechOps lesson Observability & Monitoring.

Service Level Objectives

Monitoring starts with a definition of healthy. Without it, teams either alert on everything and learn to ignore alerts, or alert on nothing and learn about outages from users.

SLIs and SLOs

A service level indicator (SLI) is a measurement of what users experience; a service level objective (SLO) is the target for it over a period. For a database that serves an application, typical choices are:

SLIExample SLO (30 days)
Availability: share of successful connection and query attempts99.9% — about 43 minutes of failure budget
Latency: 95th percentile duration of key queries< 50 ms for the order lookup
Freshness: replica lag for read traffic< 5 s for 99% of the time
Recoverability: last successful restore test< 7 days old

The gap between 100% and the SLO is the error budget. When it is nearly spent, prioritize reliability work over new changes; when plenty remains, the team can take planned risks such as a major-version upgrade.

Alert on Symptoms, Investigate Causes

Page a person only for symptoms that threaten an SLO or will soon cause an outage: rising error rates, latency above target, or a disk that will be full within hours. Record causes — high CPU, many connections, a long-running query — as dashboards and low-urgency tickets that help diagnosis. Every page should be actionable and linked to a runbook; an alert that never needs action should be deleted.

What to Monitor

Collect metrics continuously with an exporter (for example the Prometheus postgres_exporter) or an agent, and keep enough history to compare today with last month. These are the signals that most often predict PostgreSQL incidents.

Connections and Activity

Each PostgreSQL connection is a server process, and max_connections is a hard limit. Watch the number of connections by state, and look for long-running statements and transactions left open:

SELECT state,
       count(*)                          AS sessions,
       max(now() - xact_start)           AS oldest_xact,
       max(now() - query_start)          AS oldest_query
  FROM pg_stat_activity
 WHERE backend_type = 'client backend'
 GROUP BY state
 ORDER BY sessions DESC;

Many idle connections usually mean the application should use a connection pool such as PgBouncer. Sessions idle in transaction for minutes hold locks and block cleanup; see Transactions & Concurrency.

Vacuum, Bloat and Transaction ID Age

Because of MVCC, updates and deletes leave dead row versions behind. Autovacuum removes them and also freezes old rows, which protects against transaction ID wraparound — a condition in which PostgreSQL eventually refuses new writes to protect data. Monitor both:

-- Tables with the most dead rows, and when they were last vacuumed.
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum, last_autoanalyze
  FROM pg_stat_user_tables
 ORDER BY n_dead_tup DESC
 LIMIT 10;

-- Transaction ID age per database; autovacuum forces freezing at
-- autovacuum_freeze_max_age (200 million by default). Alert well before that.
SELECT datname, age(datfrozenxid) AS xid_age
  FROM pg_database
 ORDER BY xid_age DESC;

If autovacuum cannot keep up, tune it per table (for example, lower autovacuum_vacuum_scale_factor on large, busy tables) rather than disabling it. A long-open transaction or an abandoned replication slot can prevent cleanup everywhere; those are the first things to check when dead rows keep growing.

Storage, Replication and Errors

  • Disk: free space of data and WAL volumes, and the growth rate — alert on time until full, not on a fixed percentage.
  • Cache efficiency: the share of reads served from shared buffers (blks_hit vs blks_read in pg_stat_database), interpreted against the workload's baseline.
  • Replication: lag and slot retention, as shown in Replication & High Availability.
  • Archiving and backups: failed WAL archive attempts in pg_stat_archiver and the age of the last successful backup.
  • Errors: deadlocks, conflicts and failed connections per minute from pg_stat_database and the server log.
  • Query performance: top statements by total time from pg_stat_statements, tracked over time to catch regressions after deployments (see Query Optimization).

Capacity Planning

Capacity problems are the most predictable incidents of all: the trend line was visible for months. Capacity planning turns trends into dated decisions.

-- Largest tables, including their indexes and TOAST data.
SELECT relname,
       pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
       pg_size_pretty(pg_relation_size(relid))       AS table_size
  FROM pg_statio_user_tables
 ORDER BY pg_total_relation_size(relid) DESC
 LIMIT 10;

Record database size, peak connections, peak transactions per second and storage throughput weekly. Fit a simple trend, and calculate when each will cross the limit of the current hardware or plan, including the headroom needed for maintenance: a REINDEX, a major upgrade or a restore test may temporarily need much more space.

Plan the Next Step

For each resource approaching its limit, decide ahead of time which lever comes next and how long it takes to pull: archive or delete old data (with a retention policy), partition large tables by time, add read replicas for read-heavy workloads, add a connection pooler, scale the server vertically, or — last and most complex — shard the data across several databases. Lead times for hardware, budget approval and migrations are measured in weeks; start when the forecast says you have months left.

Runbook-Driven Operations

A runbook is a written, tested procedure for a specific task or alert. Runbooks let any on-call engineer act correctly at 3 a.m., reduce the dependency on one expert, and make operations reviewable like code.

Write Useful Runbooks

Keep runbooks in version control next to the infrastructure code, link each alert to its runbook, and give every runbook the same structure:

# Runbook: Replication lag above 60 seconds

**Alert:** pg_replication_lag_seconds > 60 for 5 minutes
**Impact:** replica reads may be stale; failover now could lose recent commits.

## Diagnose
1. On the primary, run the pg_stat_replication query from the dashboard README.
2. Check replica disk I/O and CPU; check for long queries on the replica
   that conflict with WAL replay (pg_stat_database_conflicts).

## Mitigate
- Heavy reporting query on the replica: cancel it with pg_cancel_backend(pid).
- Network saturation: pause bulk loads on the primary.

## Escalate
- Lag still growing after 30 minutes: page the database on-call lead.

## Verify
- Lag below 5 seconds for 15 minutes; alert resolved.

Schedule Routine Maintenance

  • Weekly: automated restore test; review of slow-query trends and of autovacuum activity on the largest tables.
  • Monthly: apply the engine's minor release (bug and security fixes) after testing on staging; review unused indexes and privilege grants.
  • Quarterly: capacity forecast; failover and recovery drill; review of alerts that fired without needing action.
  • Yearly: plan the next major-version upgrade before the current version's end-of-life date.

Handle Incidents and Learn

During an incident, stabilize first and investigate later: restore service with the runbook, communicate status on a fixed schedule, and keep a timeline of actions. Afterwards, write a blameless post-incident review that asks how the system made the failure possible, and turn its findings into tracked actions — a new alert, a fixed runbook step, an automated check. The TechOps lesson Incident Response covers the process in depth.

Practice Lab

Use a local PostgreSQL instance with pg_stat_statements enabled; optionally add Prometheus and Grafana via containers.

Build a Health Dashboard

  1. Write one SQL query per signal in this lesson: connections by state, dead rows, transaction ID age, largest tables, replication lag and top statements.
  2. Define one SLO for availability and one for latency, and write down how each would be measured.
  3. Run a load generator such as pgbench and watch which signals move.

Write and Test a Runbook

  1. Choose a failure: a session left idle in transaction that blocks a migration.
  2. Write the runbook in the structure above, then reproduce the failure in two terminal sessions.
  3. Have someone else follow your runbook without help, and fix every step they had to ask about.
You have reached the end of the Database Administration roadmap. Return to the roadmap index to review your progress, deepen your SQL with the PL/SQL roadmap, or continue with TechOps to operate the rest of the stack.