Troubleshooting a Database
Troubleshooting a database means finding out why it misbehaves, using evidence the database itself provides, and fixing the cause rather than the symptom. Sooner or later every app hears "the site is slow" or "payments are failing". Restarting the server or adding a random index can make the noise stop for an hour, and then it comes back. In this lesson, we will learn a five-step method, symptom, evidence, cause, fix, prevent, and then work through five short incident drills on the Fee Tracker: a slow query, an update that hangs, running out of connections, a replica showing old data, and a disk that keeps filling. For each one, you'll see the queries that gather evidence and what they really return.
In One Minute
- Method: describe the symptom, gather evidence, find the cause, fix it, then prevent it from coming back.
- Slow queries: find them (slow-query log,
pg_stat_statements), then read their plan withEXPLAIN (ANALYZE). - Blocked queries:
pg_stat_activityandpg_blocking_pids()show who waits for whom. - Too many connections: count sessions by
state; look foridle in transaction. - Replica lag:
pg_stat_replicationon the primary;pg_last_xact_replay_timestamp()on the replica. - A filling disk: find the biggest tables, check for bloat, and check for forgotten replication slots.
The Method: Symptom, Evidence, Cause, Fix, Prevent
Most bad incident fixes skip the evidence step. A calm, repeatable order keeps you from guessing:
| Step | Question | Example |
|---|---|---|
| 1. Symptom | What exactly is wrong, for whom, since when? | "The payments page takes 4 seconds for every student since 9 a.m." |
| 2. Evidence | What does the database show? | Slow-query log, pg_stat_activity, EXPLAIN (ANALYZE), server CPU and disk graphs |
| 3. Cause | Which single fact explains all of the evidence? | "The query scans all 20,000 payments because there's no index on student_id" |
| 4. Fix | What is the smallest safe change? | CREATE INDEX CONCURRENTLY ... |
| 5. Prevent | How do we stop it, or notice sooner, next time? | Review query plans for new pages; alert on slow queries |
Write things down as you go: the time, what you looked at, what you changed. During an incident it is easy to forget which change fixed things; afterwards, these notes become a short incident review, written without blame, that explains what happened and what changes.
Drill 1: The Slow Page
Symptom: "A student's payment history takes seconds to load, and it gets worse as the school grows."
Evidence, part 1: which queries are slow? Two tools answer that on a real server. The slow-query log writes every statement that takes longer than a limit you set; it is off by default:
SHOW log_min_duration_statement; log_min_duration_statement
----------------------------
-1
(1 row)Explanation: -1 means off. Setting it to '500ms' in the server's settings (or a parameter group on a managed service, see Database Hosting) logs every statement slower than half a second, with its duration. The other tool is the pg_stat_statements extension, which keeps running totals for every distinct query: how many times it ran, total and average time, and rows returned. The Try it database doesn't include it, but on a real server this query lists the five queries that use the most time overall:
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 1) AS avg_ms, query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 5;A query that runs 50,000 times a day at 20 ms each costs more than one that runs once at 10 seconds. Sort by total time first.
Evidence, part 2: why is it slow? Run the suspect query with EXPLAIN (ANALYZE), which shows the plan the database really used and how many rows each step touched. We'll use a 20,000-row copy of payments:
CREATE TABLE big_payments (
payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
student_id INTEGER NOT NULL, paid_on DATE NOT NULL,
amount_usd NUMERIC(8,2) NOT NULL, method TEXT
);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method)
SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400),
(ARRAY['card', 'check', 'cash'])[1 + g % 3]
FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT paid_on, amount_usd FROM big_payments WHERE student_id = 1234;CREATE TABLE
INSERT 0 20000
ANALYZE
QUERY PLAN
-----------------------------------------------------
Seq Scan on big_payments (actual rows=4.00 loops=1)
Filter: (student_id = 1234)
Rows Removed by Filter: 19996
(3 rows)Cause: The plan is a Seq Scan: to return 4 rows, PostgreSQL read all 20,000 and threw away 19,996 (Rows Removed by Filter). There is no index on student_id, so every page view reads the whole table, and the work grows with every new payment.
Fix: Add the index. On a busy production table, build it with CONCURRENTLY so writes keep working (Schema Migrations):
CREATE TABLE big_payments (
payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
student_id INTEGER NOT NULL, paid_on DATE NOT NULL,
amount_usd NUMERIC(8,2) NOT NULL, method TEXT
);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method)
SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400),
(ARRAY['card', 'check', 'cash'])[1 + g % 3]
FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
CREATE INDEX CONCURRENTLY big_payments_student_idx ON big_payments (student_id);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT paid_on, amount_usd FROM big_payments WHERE student_id = 1234;CREATE TABLE
INSERT 0 20000
ANALYZE
CREATE INDEX
QUERY PLAN
--------------------------------------------------------------------------------
Bitmap Heap Scan on big_payments (actual rows=4.00 loops=1)
Recheck Cond: (student_id = 1234)
Heap Blocks: exact=4
-> Bitmap Index Scan on big_payments_student_idx (actual rows=4.00 loops=1)
Index Cond: (student_id = 1234)
Index Searches: 1
(6 rows)Explanation: Now the plan uses the index to find the 4 matching rows directly. A Bitmap Index Scan collects the matching row locations from the index, and the Bitmap Heap Scan fetches just those rows. The work no longer grows with the size of the table.
Prevent: Turn on the slow-query log or pg_stat_statements, alert when average time rises, and look at the plan of every new query on a big table before it ships (Reading EXPLAIN).
Drill 2: The Update That Hangs
Symptom: "Saving a payment spins forever. Other pages work."
Evidence: A statement that doesn't fail but never finishes is usually waiting for a lock. pg_stat_activity lists every session with what it is doing, and pg_blocking_pids(pid) returns the sessions blocking it. This query lists every waiting session next to its blockers:
SELECT pid, state, wait_event_type, pg_blocking_pids(pid) AS blocked_by,
left(query, 50) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0; pid | state | wait_event_type | blocked_by | query
-----+-------+-----------------+------------+-------
(0 rows)Explanation: Try it runs a single session, so nothing is waiting and the result is empty, which is what you hope to see. On a server with the problem, each row is a waiting session: wait_event_type is Lock, and blocked_by holds the process ids that hold the lock. Look those pids up in pg_stat_activity next. A common finding is a session whose state is idle in transaction: it ran BEGIN and an UPDATE, then the app stopped doing anything with the connection, maybe stuck on a slow API call, while the row lock stays held.
What locks does an open transaction hold? We can see our own in pg_locks:
BEGIN;
UPDATE payments SET method = 'card' WHERE payment_id = 5;
SELECT relation::regclass AS locked, mode, granted
FROM pg_locks
WHERE pid = pg_backend_pid() AND locktype = 'relation'
ORDER BY 1::text, 2;
ROLLBACK;BEGIN
UPDATE 1
locked | mode | granted
---------------+------------------+---------
pg_locks | AccessShareLock | t
payments_pkey | RowExclusiveLock | t
payments | RowExclusiveLock | t
(3 rows)
ROLLBACKExplanation: Until COMMIT or ROLLBACK, the transaction holds a RowExclusiveLock on payments and its primary key index, plus a lock on payment 5's row itself. Row locks don't appear in pg_locks by name; they are stored in the row. Any other session that tries to update payment 5 waits for this one to finish. (AccessShareLock on pg_locks is just our own SELECT reading the view.)
Cause: A transaction left open by the app holds a row lock that the save needs.
Fix: First try SELECT pg_cancel_backend(pid);, which cancels the blocking session's current query. A session that is idle in transaction has no running query to cancel, so it needs SELECT pg_terminate_backend(pid);, which closes the whole session and rolls its transaction back. Then fix the code path that left the transaction open.
Prevent: Keep transactions short, never wait on outside services inside one, and set limits so a stuck session can't hold locks forever:
SET idle_in_transaction_session_timeout = '30s';
SET lock_timeout = '5s';
SHOW idle_in_transaction_session_timeout;
SHOW lock_timeout;SET
SET
idle_in_transaction_session_timeout
-------------------------------------
30s
(1 row)
lock_timeout
--------------
5s
(1 row)Explanation: With these settings, a session idle inside a transaction for 30 seconds is ended (and its transaction rolled back), and a statement that waits more than 5 seconds for a lock fails with an error instead of hanging. Set here, they last for this session; set on the server or the app's database user (ALTER ROLE fee_app SET lock_timeout = '5s';), they apply to every new session.
Drill 3: Out of Connections
Symptom: "Errors say FATAL: sorry, too many clients already", or the app logs "timed out waiting for a connection from the pool".
Evidence: Count sessions by state and compare with the limit:
SELECT current_setting('max_connections') AS max_connections;
SELECT state, count(*) AS sessions
FROM pg_stat_activity
WHERE backend_type IN ('client backend', 'standalone backend')
GROUP BY state
ORDER BY sessions DESC; max_connections
-----------------
100
(1 row)
state | sessions
--------+----------
active | 1
(1 row)Explanation: Try it has one session, our own, and it is active. On a server in trouble, you'll typically see one of three patterns. Many idle sessions: app pools are too big in total, holding connections nobody uses. Many idle in transaction: code opens transactions and doesn't finish them, often a missing COMMIT or an error path that never rolls back. Many active: the database really is overloaded, usually because of slow queries (back to Drill 1).
Cause and fix by pattern:
| What you see | Likely cause | Fix |
|---|---|---|
Many idle | Too many app copies times too large a pool | Smaller pools, or PgBouncer (Replication and Scaling) |
Many idle in transaction | A code path that never commits or rolls back | Fix the code; set idle_in_transaction_session_timeout |
Many active, high CPU | Slow or repeated queries | Find them with pg_stat_statements; add indexes |
| Connections climb after each deploy and never fall | A connection leak: connections opened but not closed | Close connections with try-with-resources or finally; check pool settings |
Prevent: Alert when connections pass about 80% of max_connections. Raising max_connections is rarely the fix: each connection costs memory, and more active sessions than CPU cores only makes them wait for each other. A superuser can still connect when the limit is reached, because a few slots are reserved for administrators (superuser_reserved_connections, 3 by default).
Drill 4: The Replica Shows Old Data
Symptom: "Reports are missing this morning's payments, but the payments page shows them."
Evidence: The reports read from a replica (Replication and Scaling). On the primary, check each replica's lag; on the replica, check when it last replayed a change:
SELECT client_addr, state, replay_lag
FROM pg_stat_replication;
SELECT pg_is_in_recovery() AS is_replica,
pg_last_xact_replay_timestamp() AS last_replayed; client_addr | state | replay_lag
-------------+-------+------------
(0 rows)
is_replica | last_replayed
------------+---------------
f | NULL
(1 row)Explanation: Try it is a primary with no replicas, so the first query returns no rows and the second returns f and NULL. On a lagging replica, pg_is_in_recovery() is t, and now() - pg_last_xact_replay_timestamp() gives the lag as a time, such as 47 minutes. (On a quiet primary with no writes, this number grows even when nothing is wrong, so compare it with the primary's pg_stat_replication.)
Common causes: a long-running query on the replica that conflicts with changes it must replay (PostgreSQL then delays the replay, up to max_standby_streaming_delay), a burst of writes such as a huge UPDATE or index build on the primary, a replica server smaller than the primary, or a slow network.
Fix: Find and stop the long query on the replica, give the replica the same size as the primary, and break big writes into batches. Prevent: Alert on replay_lag, send reads that must be current to the primary, and keep large reports to replicas dedicated to them.
Drill 5: The Disk Keeps Filling
Symptom: "Disk usage alert: 90% full, and it was 60% last month."
Evidence, part 1: what is big? List tables by total size, including indexes:
SELECT relname AS table_name,
pg_size_pretty(pg_total_relation_size(oid)) AS total_size
FROM pg_class
WHERE relkind = 'r' AND relnamespace = 'public'::regnamespace
ORDER BY pg_total_relation_size(oid) DESC
LIMIT 5; table_name | total_size
-------------+------------
students | 40 kB
courses | 40 kB
cities | 24 kB
enrollments | 24 kB
payments | 24 kB
(5 rows)Evidence, part 2: is a table bloated? An UPDATE in PostgreSQL writes a new version of each row and leaves the old one as a dead row until VACUUM cleans it (MVCC). If autovacuum can't keep up, or something stops it from removing dead rows, the table grows even though the number of live rows doesn't:
CREATE TABLE big_payments AS
SELECT g AS payment_id, 100 + (g % 400)::numeric(8,2) AS amount_usd
FROM generate_series(1, 20000) AS g;
SELECT pg_size_pretty(pg_relation_size('big_payments')) AS size_at_start;
UPDATE big_payments SET amount_usd = amount_usd + 1;
UPDATE big_payments SET amount_usd = amount_usd + 1;
SELECT pg_size_pretty(pg_relation_size('big_payments')) AS after_two_updates;
VACUUM big_payments;
SELECT pg_size_pretty(pg_relation_size('big_payments')) AS after_vacuum;
VACUUM FULL big_payments;
SELECT pg_size_pretty(pg_relation_size('big_payments')) AS after_vacuum_full;SELECT 20000
size_at_start
---------------
1024 kB
(1 row)
UPDATE 20000
UPDATE 20000
after_two_updates
-------------------
2744 kB
(1 row)
VACUUM
after_vacuum
--------------
2744 kB
(1 row)
VACUUM
after_vacuum_full
-------------------
872 kB
(1 row)Explanation: The table still holds 20,000 live rows, but two full-table updates left the old versions behind as dead rows, and the file grew from 1,024 kB to 2,744 kB, almost three times its size. Plain VACUUM marks that space as free for new rows in this table, but the file stays the same size. VACUUM FULL rewrites the table into a new, compact file (872 kB here) and gives the space back, but it locks the table for the whole rewrite, so on a large production table teams use it rarely, at a quiet time, or use an online tool such as the pg_repack extension.
Other common causes of a filling disk:
| Cause | Evidence | Fix |
|---|---|---|
An old open transaction stops VACUUM removing dead rows | pg_stat_activity shows a very old xact_start | End it; set idle_in_transaction_session_timeout |
| A replication slot nobody reads keeps WAL forever | pg_replication_slots shows an inactive slot | Drop the slot if it's no longer needed |
| Old data never removed | One table keeps growing month after month | Archive and delete, or drop old partitions (Partitioning) |
| Unused indexes | pg_stat_user_indexes.idx_scan stays 0 for weeks | Drop them after checking |
| Server logs or temporary files | Disk graphs show non-table growth | Rotate logs; fix queries that spill big sorts to disk |
Prevent: Alert on disk use well before it is full (a full disk can stop PostgreSQL from writing at all), keep an eye on the biggest tables, and check pg_replication_slots after any replica or tool is removed.
Common Mistakes
Fixing before looking. Restarting the server clears the symptom and the evidence along with it. Capture pg_stat_activity and the slow queries first.
Changing several things at once. You can't tell what helped. Change one thing, then check.
Raising max_connections as the fix. More connections use more memory and add contention. Find out why connections pile up.
Killing sessions without reading them. pg_terminate_backend rolls back work. Check what the session is doing, and who owns it, first.
Running VACUUM FULL on a busy table. It locks the table for the whole rewrite. Use plain VACUUM, tune autovacuum, or an online tool.
No alerts. Most of these incidents give hours or days of warning (slower queries, growing lag, rising disk use) to anyone who is watching.
Interview Corner
A page became slow. How do you investigate?
Confirm the symptom, find the slow query (slow-query log or pg_stat_statements), run it with EXPLAIN (ANALYZE), and compare rows read with rows returned. A sequential scan that discards most rows usually means a missing or unused index.
An UPDATE hangs. What do you check?
pg_stat_activity with pg_blocking_pids() to find the blocking session, often one that is idle in transaction. Cancel or terminate it, fix the code that left it open, and set lock_timeout and idle_in_transaction_session_timeout.
What is table bloat, and how do you fix it?
Space taken by dead row versions left by updates and deletes. Regular VACUUM (autovacuum) makes the space reusable; VACUUM FULL or pg_repack shrinks the file. Also look for what blocks vacuum, such as long-open transactions.
The database ran out of connections. What are the usual causes?
Pools that are too large in total, connections leaked by code that doesn't close them, transactions left open, or slow queries keeping sessions busy. Count sessions by state to tell which.
Practice
Challenge (module checkpoint): Srihitha says "Searching payments by method and date is slow." The query is SELECT count(*) FROM big_payments WHERE method = 'check' AND paid_on >= '2025-06-01' AND paid_on < '2025-07-01';. Gather the evidence with EXPLAIN (ANALYZE), add the index that fixes it, and show the new plan.
Show solution
CREATE TABLE big_payments (
payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
student_id INTEGER NOT NULL, paid_on DATE NOT NULL,
amount_usd NUMERIC(8,2) NOT NULL, method TEXT
);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method)
SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400),
(ARRAY['card', 'check', 'cash'])[1 + g % 3]
FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*) FROM big_payments
WHERE method = 'check' AND paid_on >= '2025-06-01' AND paid_on < '2025-07-01';
CREATE INDEX big_payments_method_paid_idx ON big_payments (method, paid_on);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*) FROM big_payments
WHERE method = 'check' AND paid_on >= '2025-06-01' AND paid_on < '2025-07-01';CREATE TABLE
INSERT 0 20000
ANALYZE
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
-> Seq Scan on big_payments (actual rows=270.00 loops=1)
Filter: ((paid_on >= '2025-06-01'::date) AND (paid_on < '2025-07-01'::date) AND (method = 'check'::text))
Rows Removed by Filter: 19730
(4 rows)
CREATE INDEX
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
-> Bitmap Heap Scan on big_payments (actual rows=270.00 loops=1)
Recheck Cond: ((method = 'check'::text) AND (paid_on >= '2025-06-01'::date) AND (paid_on < '2025-07-01'::date))
Heap Blocks: exact=33
-> Bitmap Index Scan on big_payments_method_paid_idx (actual rows=270.00 loops=1)
Index Cond: ((method = 'check'::text) AND (paid_on >= '2025-06-01'::date) AND (paid_on < '2025-07-01'::date))
Index Searches: 1
(7 rows)Before the index, the plan reads all 20,000 rows and the filter removes almost all of them. The index puts the column compared with = (method) first and the range column (paid_on) second, so all the June check payments sit next to each other in the index and the plan reads only those. In a real incident you'd build it with CONCURRENTLY and write the steps into the incident notes.
Key Takeaways
| You want to | Use |
|---|---|
| See a query's real plan | EXPLAIN (ANALYZE) SELECT ... |
| Find the costliest queries | pg_stat_statements, ordered by total_exec_time |
| Log slow statements | log_min_duration_statement = '500ms' |
| See who blocks whom | pg_stat_activity with pg_blocking_pids(pid) |
| Stop a session | pg_cancel_backend(pid), then pg_terminate_backend(pid) |
| Count connections by state | SELECT state, count(*) FROM pg_stat_activity GROUP BY state |
| Check replica lag | pg_stat_replication.replay_lag on the primary |
| Find big tables | pg_total_relation_size(oid) from pg_class |
| Check forgotten slots | SELECT * FROM pg_replication_slots; |
Was this tutorial helpful?