Over the last few months I helped a team running a large B2B ERP on PostgreSQL (RDS for the main database, plus a few self-hosted PostgreSQL 17 servers). Almost every "the database is slow" ticket turned out to be something other than load. CPU was fine, disk was fine, and users were still waiting.
Here are five incidents, what the data showed, and the SQL that found each one. Names, tables, and numbers are simplified, but the patterns are real.
1. "It's slow every day from 4:00 to 5:30 pm" (it was not a cron job)
Everyone's first guess was a scheduled job. There wasn't one: no pg_cron, and the task scheduler only ran small jobs every minute. The database wasn't working harder in that window either. Execution time, rows read, and TPS were all at the daily average.
What changed was this: transactions open longer than 5 minutes appeared 2 to 7 times more per hour, and blocked sessions 3 to 12 times more.
The cause was a batch routine that processed an upload inside one transaction lasting 30 to 67 minutes, with a SAVEPOINT per record and a permission check per record. Field teams uploaded their data at the end of the day, so this routine ran mostly between 4 and 5:30 pm. While it ran, it held row locks that other users' UPDATEs waited on for up to 54 minutes.
This finds it:
-- Transactions open for more than 5 minutes SELECT pid, usename, state, now() - xact_start AS xact_age, wait_event_type, wait_event, left(query, 80) AS last_query FROM pg_stat_activity WHERE xact_start < now() - interval '5 minutes' ORDER BY xact_start; -- Who is blocking whom SELECT blocked.pid AS blocked_pid, now() - blocked.query_start AS waiting_for, blocker.pid AS blocker_pid, blocker.state AS blocker_state, now() - blocker.xact_start AS blocker_xact_age, left(blocker.query, 80) AS blocker_last_query FROM pg_stat_activity blocked CROSS JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) JOIN pg_stat_activity blocker ON blocker.pid = b.pid ORDER BY waiting_for DESC; On one bad afternoon we sampled every 30 seconds: 97% of the time, the long transactions were idle in transaction waiting on ClientRead, which means the database was waiting on the application, not the other way around.
Fix: commit per record or per small batch instead of one giant transaction with savepoints, and move the permission check outside the transaction.
Gotcha: idle_in_transaction_session_timeout does not fix this. The session keeps going between "active" and "idle in transaction", so the timeout never fires. It only helps with transactions someone forgot to close.
2. A report did SET work_mem = '2GB' and took the server down
A self-hosted PostgreSQL 17 server (8 GB RAM, no swap, shared_buffers = 2 GB) went down twice in a week. The kernel log said OOM killer. The PostgreSQL log said which query was running when it died: a heavy report.
The report began with:
SET work_mem = '2GB'; Two details made this worse:
-
work_memis per operation, not per session. A query with several sorts and hashes can use it several times. - Since PostgreSQL 15,
hash_mem_multiplierdefaults to 2.0, so every hash node could use up to 4 GB.
Three users ran the report at the same time. Three backends at 2 to 3.5 GB each, plus shared_buffers, on a box with 7.9 GB and no swap: the OOM killer kicked in.
Then the second surprise: the whole cluster stayed down. PostgreSQL knows how to survive a killed backend (it resets the other connections and runs crash recovery in seconds). But systemd's default OOMPolicy=stop stopped the entire postgresql@17-main unit as soon as the kernel killed one of its processes. Someone had to start it by hand.
What we changed:
# /etc/systemd/system/postgresql@17-main.service.d/oom-recovery.conf [Service] OOMPolicy=continue Restart=on-failure RestartSec=5s sudo systemctl daemon-reload # no PostgreSQL restart needed We also added swap (8 GB) as a safety margin. The real fix is in the report itself, because ALTER ROLE ... SET work_mem only sets a default and cannot stop a session from running its own SET. The report also queried data since the year 2000 by default. With a six-month range it took one minute instead of eleven.
3. Deadlocks from SELECT ... FOR UPDATE on a join
21 deadlocks in 15 minutes, all from the same application server. Two code paths:
-- Path A: find today's plan for a location and lock it SELECT d.* FROM daily_plan d JOIN location_stay s ON s.id = d.stay_id WHERE d.location_id = $1 AND d.plan_date = $2 ORDER BY d.id DESC LIMIT 1 FOR UPDATE; -- Path B: lock the same plan by id (an ORM .get() inside select_for_update) SELECT * FROM daily_plan WHERE id = $1 FOR UPDATE; FOR UPDATE without OF locks the matching rows in every table in the join. Path A locked daily_plan and location_stay, path B locked daily_plan and then went for location_stay, and they met in opposite order.
Fix: lock only the table you mean to change, and use the weaker lock when you don't change the key:
... FOR NO KEY UPDATE OF d; In Django that is select_for_update(of=("self",), no_key=True). FOR NO KEY UPDATE also stops conflicting with the FOR KEY SHARE locks that foreign-key checks take, which is the most likely explanation for the last three deadlocks: they happened at COMMIT, which is when Django's deferred FK constraints are checked.
4. A query killer that cancelled the victims
To protect production from runaway queries, we deployed a small script that cancels anything running longer than 60 minutes (later 30). It ran in dry-run mode for days, then for real.
The first real problem was not a runaway query. The killer cancelled four UPDATEs that were waiting on a lock held by an idle in transaction session. The UPDATEs had been "running" for over 30 minutes because they were waiting, and they were exactly the work that had to finish. The blocker, meanwhile, was idle.
Two rules came out of that:
- Never cancel a session whose
wait_event_type = 'Lock'. It is the victim. Go after the blocker (pg_blocking_pids). -
pg_cancel_backend()does nothing to anidle in transactionsession, because there is no running query to cancel. You needpg_terminate_backend(), and you need to know what you are rolling back.
-- Candidates, excluding sessions that are only waiting on someone else SELECT pid, usename, state, now() - query_start AS running_for, left(query, 80) FROM pg_stat_activity WHERE state = 'active' AND now() - query_start > interval '30 minutes' AND coalesce(wait_event_type, '') <> 'Lock' AND backend_type = 'client backend'; 5. After upgrading to PostgreSQL 16+, monitoring went blind
After a server was migrated to PostgreSQL 17, the monitoring user saw <insufficient privilege> in every row of pg_stat_activity, even though it had been granted pg_monitor.
PostgreSQL 16 added the INHERIT option to role grants, and the grant came over with INHERIT FALSE:
SELECT r.rolname AS granted_role, m.rolname AS member, a.inherit_option FROM pg_auth_members a JOIN pg_roles r ON r.oid = a.roleid JOIN pg_roles m ON m.oid = a.member WHERE r.rolname = 'pg_monitor'; -- Fix GRANT pg_monitor TO monitoring_user WITH INHERIT TRUE; If your dashboards suddenly show empty query text after an upgrade, check this first.
What these have in common
None of these incidents showed up as high CPU. They were waits: on locks, on the application, on memory that wasn't there. A per-minute CPU graph shows none of that. What helped was:
- sampling
pg_stat_activityoften (every few seconds) and keeping the samples, so you can see 4:25 pm after the fact; - recording the blocking chain, not just "N sessions waiting";
- tracking transaction age, not just query duration.
Disclosure: I build PG Monitoring, a PostgreSQL monitoring tool, and these incidents shaped how it samples sessions and records lock chains. But every query above works on its own in psql. If you are stuck on a query plan, the EXPLAIN analyzer is free, runs in your browser, and doesn't upload anything.
What is the strangest "the database is slow" incident you have debugged that turned out not to be the database?
