SQL · Module 14 · Lesson 62 min read

Backups, Monitoring & Slow Queries

Backups

Logical backups – pg_dump

  • pg_dump -Fc -d mydb -f backup.dump (custom format, compressed)
  • Restore: pg_restore -d newdb backup.dump
  • Schema only: --schema-only; data only: --data-only; one table: -t expenses
  • Plain SQL: pg_dump -d mydb > backup.sql → psql -d newdb -f backup.sql
  • Whole server (roles too): pg_dumpall

Physical backups & Point-In-Time Recovery (PITR)

Continuous copies of the WAL let you restore to any moment ("just before that accidental DELETE at 14:32"). Tools: pgBackRest, Barman, WAL-G.

Supabase

  • Daily backups on paid plans; PITR as an add-on
  • Download backups from the dashboard, or run pg_dump with your connection string
  • supabase db dump from the CLI

The 3-2-1 rule

3 copies, on 2 different media, 1 off-site. And test your restores regularly.

Monitoring

WhatWhere
Slowest / most frequent queriespg_stat_statements ⭐
Running queries, locks, idle transactionspg_stat_activity
Table activity, dead rows, vacuum timespg_stat_user_tables
Index usage (find unused indexes)pg_stat_user_indexes
Cache hit ratio (should be > 99%)pg_statio_user_tables
Database / table sizespg_database_size, pg_total_relation_size
SupabaseReports, Query Performance, Advisors (security & performance lints)

Finding and fixing slow queries

  1. Enable pg_stat_statements; sort by total_exec_time (total load) and mean_exec_time
  2. EXPLAIN (ANALYZE, BUFFERS) the worst ones
  3. Add/fix indexes, rewrite queries, remove N+1 patterns
  4. Set statement_timeout so a runaway query can't hang the app
  5. Kill a stuck query: SELECT pg_cancel_backend(pid) (or pg_terminate_backend)

Other production habits

  • Connection pooling (Supavisor, PgBouncer) — Postgres connections are expensive
  • Alerts on disk space, CPU, replication lag and error rates
  • Keep PostgreSQL and extensions up to date
  • Read-only replicas for heavy reporting

Example

SQL
-- 🖥️ Backups (run in a terminal)
-- $ pg_dump -Fc "postgresql://user:pass@host:5432/postgres" -f budgetbuddy_2026-11-24.dump
-- $ pg_restore --clean --if-exists -d "postgresql://…/postgres_restore_test" budgetbuddy_2026-11-24.dump
-- $ supabase db dump -f supabase_backup.sql

-- Database and table sizes
SELECT pg_size_pretty(pg_database_size(current_database())) AS database_size;
SELECT relname AS table_name, pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 5;

-- Active queries right now (and how long they've been running)
SELECT pid, usename, state, now() - query_start AS running_for, left(query, 50) AS query
FROM pg_stat_activity
WHERE datname = current_database() AND state <> 'idle' AND pid <> pg_backend_pid();

-- Cache hit ratio (aim for > 99% on a busy database)
SELECT round(100.0 * sum(heap_blks_hit) / NULLIF(sum(heap_blks_hit) + sum(heap_blks_read), 0), 2) AS cache_hit_pct
FROM pg_statio_user_tables;

-- Indexes that are never used (candidates to drop — check on production stats!)
SELECT relname AS table_name, indexrelname AS index_name, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY relname;

-- Protect the app from runaway queries
SET statement_timeout = '5s';          -- per session (or ALTER ROLE … SET statement_timeout)
SHOW statement_timeout;
RESET statement_timeout;

-- Cancel a stuck query (replace 12345 with a real pid from pg_stat_activity)
-- SELECT pg_cancel_backend(12345);

-- ⭐ Top queries by total time (needs pg_stat_statements; enabled by default on Supabase)
-- CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 2) AS avg_ms,
--        left(query, 60) AS query
-- FROM pg_stat_statements
-- ORDER BY total_exec_time DESC
-- LIMIT 10;