Chapter 31: Monitoring and Performance Tuning

Key Metrics to Monitor

MetricHealthyAction if Bad
Buffer hit ratio>99%Increase shared_buffers / add RAM
Active connections<80% of maxUse connection pooling (PgBouncer)
Replication lag<1 secondCheck network, replica load
Transaction rateStableInvestigate spikes
Slow queriesFew/noneAdd indexes, optimize queries
Dead tuplesLow ratioTune autovacuum
Disk usage<80%Archive old data, add storage

PostgreSQL Monitoring Queries

-- Active queries right now
SELECT pid, state, query, now() - query_start AS duration
FROM pg_stat_activity WHERE state = 'active';

-- Slow queries (enable pg_stat_statements extension)
SELECT query, calls, mean_exec_time, total_exec_time
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

-- Table bloat (dead tuples needing vacuum)
SELECT relname, n_dead_tup, n_live_tup,
  round(n_dead_tup::numeric/n_live_tup*100,2) AS dead_pct
FROM pg_stat_user_tables WHERE n_live_tup > 0
ORDER BY dead_pct DESC;

-- Index usage (unused indexes waste space and slow writes)
SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes ORDER BY idx_scan ASC LIMIT 10;

Tools

Key Takeaways