wrkm.app
Search
Databases

fahri cap: How to investigate a slow PostgreSQL database: six checks, tested on PostgreSQL 18

“The database is slow” is a symptom with about six common causes, and they need different fixes. Adding memory does nothing for a missing index. An index does nothing for a query stuck behind a lock. This article gives an order of checks for a slow PostgreSQL database, and for each one shows what the diagnostic looks like when that cause is present. Every output below comes from a lab we ran on 3 December 2026: PostgreSQL 18.7 in Docker, a small shop database with 100,000 customers and

Editor
Dec 3, 2026 · 18 min read
fahri cap: How to investigate a slow PostgreSQL database: six checks, tested on PostgreSQL 18

“The database is slow” is a symptom with about six common causes, and they need different fixes. Adding memory does nothing for a missing index. An index does nothing for a query stuck behind a lock. This article gives an order of checks for a slow PostgreSQL database, and for each one shows what the diagnostic looks like when that cause is present. Every output below comes from a lab we ran on 3 December 2026: PostgreSQL 18.7 in Docker, a small shop database with 100,000 customers and 3 million orders, and one deliberate fault per step. The lab is one laptop with small tables, so read the numbers as direction, not as timings to expect on your system. You can download the lab and run it yourself in about ten minutes.

99.8%of database time spent in one statement 47,696buffers read per call before the index, 23 after 12 severy query on a table waited behind one ALTER TABLE 6xtable size after five updates without vacuum

Order of checks pg_stat_statements EXPLAIN ANALYZE Locks Sorts on disk Dead rows PgBouncer RDS and Cloud SQL

The short answer

Start with what is running now (pg_stat_activity): a lock queue looks like a slow database and no amount of tuning fixes it. Then ask where the time went (pg_stat_statements). In our lab one statement took 99.8% of it. Read the plan of that statement with EXPLAIN (ANALYZE, BUFFERS) and look at buffers and rows removed, not only at the time. Only then look at settings: sorts spilling to disk, dead rows, and connection limits. PgBouncer makes a database survive more clients. It does not make queries faster.

The order of checks

StepQuestionWhere to look

1Is something blocked right now?pg_stat_activity, pg_blocking_pids() 2Which statements take the time?pg_stat_statements, the slow query log 3Why is that statement slow?EXPLAIN (ANALYZE, BUFFERS) 4Are sorts and hashes spilling to disk?Plan output, temp_blks_written 5Are tables full of dead rows?pg_stat_user_tables 6Are there too many connections?pg_stat_activity, the server log

Step 1 comes first because it is the only one that is urgent and the only one that statistics hide: a blocked query uses no CPU and reads nothing, so it barely shows up anywhere except in the list of sessions.

Where the time goes: pg_stat_statements pg_stat_statements records every statement the server runs, with constants replaced by placeholders, and adds up calls, time and buffers for each. It ships with PostgreSQL but is off by default. It needs a line in postgresql.conf, a restart, and one statement per database: shared_preload_libraries = 'pg_stat_statements' # restart needed track_io_timing = on # adds read and write times to plans and statistics CREATE EXTENSION IF NOT EXISTS pg_stat_statements; Our shop ran a mixed workload for 60 seconds with eight clients: look up a customer, look up an order, insert an order, and list a customer’s latest orders. It managed 32 transactions per second. Then we asked where the time went: SELECT round(total_exec_time::numeric / 1000, 1) AS total_s, calls, round(mean_exec_time::numeric, 2) AS mean_ms, round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct, shared_blks_read + shared_blks_hit AS buffers, left(query, 78) AS query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 6; total_s | calls | mean_ms | pct | buffers | query ---------+-------+---------+------+----------+---------------------------------------------------------------- 480.3 | 498 | 964.47 | 99.8 | 23681741 | SELECT id, status, amount, created_at FROM orders WHERE customer_id = $1 ORDER 0.4 | 469 | 0.94 | 0.1 | 1900 | SELECT status, amount FROM orders WHERE id = $1 0.4 | 483 | 0.80 | 0.1 | 1449 | SELECT email, country FROM customers WHERE id = $1 0.1 | 500 | 0.17 | 0.0 | 3287 | INSERT INTO orders (customer_id, status, amount, created_at) VALUES ($1, $2, $ Three things to take from this output:

Sort by total time, not by mean time. The statement to fix is the one the server spends most of its time on. Here it is also the slowest per call, but often it is a 5 ms query called a million times. Look at buffers per call. 23.7 million buffers over 498 calls is about 47,500 pages, or roughly 370 MB of table, read for every call that returns 20 rows. That ratio says “missing index” before you open a plan. The other three statements are fine, and they were still slow for users, because all four shared the same eight busy CPU cores.

The figures are totals since the last reset. Call pg_stat_statements_reset() before a test, or compare two snapshots, or an old problem will hide a new one.

The slow query log The log gives what the statistics cannot: the actual parameter values and the time of day. Set a threshold and every statement above it is written to the server log: log_min_duration_statement = 250 # milliseconds; no restart needed log_lock_waits = on # log any lock wait longer than deadlock_timeout 2026-12-03 09:24:54.867 UTC [123] LOG: duration: 527.639 ms statement: SELECT id, status, amount, created_at FROM orders WHERE customer_id = 60552 ORDER BY created_at DESC LIMIT 20; The same run wrote 518 such lines. Use the log to get a real example to explain, and to see whether slowness comes in bursts at certain times. Use pg_stat_statements to decide what matters. Both settings are described under error reporting and logging.

Why it is slow: EXPLAIN (ANALYZE, BUFFERS) Take the statement from the top of the list, put in a real value from the log, and run it with EXPLAIN ANALYZE. This executes the query, so wrap anything that writes in a transaction you roll back. EXPLAIN (ANALYZE, BUFFERS) SELECT id, status, amount, created_at FROM orders WHERE customer_id = 4242 ORDER BY created_at DESC LIMIT 20; Limit (actual time=156.756..170.205 rows=20.00 loops=1) Buffers: shared hit=15901 read=31795 -> Gather Merge (actual time=156.753..170.190 rows=20.00 loops=1) Workers Planned: 2 Workers Launched: 2 -> Sort (actual time=151.389..151.395 rows=11.67 loops=3) Sort Key: created_at DESC Sort Method: quicksort Memory: 25kB -> Parallel Seq Scan on orders (actual time=13.483..151.230 rows=13.67 loops=3) Filter: (customer_id = 4242) Rows Removed by Filter: 1000153 Buffers: shared hit=15825 read=31795 Execution Time: 170.370 ms (Cost estimates are removed here to keep the lines short; the full output is in the lab.) How to read it:

Parallel Seq Scan on orders: PostgreSQL read the whole table, with three processes. Rows Removed by Filter: 1000153, per process: it read 3 million rows to keep 41. A large “rows removed” next to a small “rows” is the signature of a missing index. Buffers: 47,696 pages touched. Buffers are a better measure than time, because time depends on what else is running. Alone, this query took 170 ms; under the eight-client workload the same query averaged 964 ms.

The fix is an index that matches both the filter and the sort order. On a live table, build it with CONCURRENTLY, which does not block writes. It cannot run inside a transaction, and if it fails it leaves an invalid index behind that you must drop. CREATE INDEX CONCURRENTLY orders_customer_created_idx ON orders (customer_id, created_at DESC); -- 4.0 s on 3 million rows in the lab Limit (actual time=0.095..0.428 rows=20.00 loops=1) Buffers: shared hit=7 read=16 -> Index Scan using orders_customer_created_idx on orders (actual time=0.094..0.420 rows=20.00 loops=1) Index Cond: (customer_id = 4242) Index Searches: 1 Execution Time: 0.493 ms 23 buffers instead of 47,696, and no sort step at all, because the index already returns rows in the order asked for. We ran the same 60-second workload again:

Same workload, eight clientsBefore the indexAfter the index

Transactions per second328,184 Average latency249 ms0.98 ms Mean time of the orders-by-customer query964 ms0.21 ms Mean time of the customer lookup (not changed)0.80 ms0.02 ms

The last row is the point people miss. The customer lookup was never changed. It became 40 times faster because the query next to it stopped using every core. One bad statement makes a whole database slow, which is why step 2 comes before any tuning.

Check what is blocked: locks This is step 1 in the order of checks, shown here after the query work because it needs a different way of looking. We left a transaction open after updating one customer, which is what an application does when it starts a transaction and then waits for something else. Then a migration ran an ALTER TABLE, and two ordinary queries arrived. SELECT pid, state, wait_event_type AS wait_type, wait_event, pg_blocking_pids(pid) AS blocked_by, round(extract(epoch FROM now() - xact_start)::numeric, 1) AS xact_s, left(query, 58) AS query FROM pg_stat_activity WHERE datname = current_database() AND backend_type = 'client backend' ORDER BY xact_start; pid | state | wait_type | wait_event | blocked_by | xact_s | query -----+--------+-----------+------------+------------+--------+------------------------------------------------- 786 | active | Timeout | PgSleep | {} | 7.0 | SELECT pg_sleep(14) 793 | active | Lock | relation | {786} | 5.0 | ALTER TABLE customers ADD COLUMN vip boolean 806 | active | Lock | relation | {793} | 3.0 | SELECT email FROM customers WHERE id = 2 807 | active | Lock | relation | {793} | 3.0 | UPDATE customers SET country = 'IE' WHERE id = 1 Read the blocked_by column from the bottom up. The plain SELECT of a different customer (pid 806) is not blocked by the open transaction. It is blocked by the ALTER TABLE, which is itself waiting. ALTER TABLE needs an exclusive lock on the table; while it queues for that lock, every later query on the table queues behind it. Adding a column takes milliseconds, yet in the lab it made the whole table unreadable for 12 seconds, until the open transaction ended: LOG: process 793 still waiting for AccessExclusiveLock on relation 16429 of database 16384 after 1000.086 ms LOG: process 806 still waiting for AccessShareLock on relation 16429 of database 16384 after 1000.078 ms LOG: process 793 acquired AccessExclusiveLock on relation 16429 of database 16384 after 12019.926 ms Those lines appear because log_lock_waits is on. Three settings prevent this class of outage (see client connection defaults and explicit locking):

SET lock_timeout = '3s' at the top of every migration, so a schema change gives up and can be retried instead of queueing in front of the application. idle_in_transaction_session_timeout, so a session that opens a transaction and goes quiet is disconnected. statement_timeout for application roles, so one runaway query cannot hold locks and CPU for an hour.

In a real incident the first row is usually idle in transaction rather than a sleep: look for that state with an old xact_start.

Sorts and hashes that spill to disk Each sort or hash step may use up to work_mem of memory, 4 MB by default. Above that it writes temporary files. The plan says so directly: SET work_mem = '4MB'; Sort Method: external merge Disk: 64128kB Buffers: ... temp read=16030 written=16073 Execution Time: 3915.380 ms

SET work_mem = '512MB'; Sort Method: quicksort Memory: 195904kB Execution Time: 2824.494 ms Sorting 3 million rows took 3.9 seconds on disk and 2.8 seconds in memory. Notice the cost: the in-memory sort needed about 190 MB, three times the size of the temporary file. work_mem is a limit per sort or hash step, not per connection, so a query with four such steps on 100 connections can ask for 400 times the setting. Raise it for the session or role that runs reports, not for the whole server. In pg_stat_statements, the temp_blks_written column finds the statements that spill. The setting is described under resource consumption.

Dead rows and tables that only grow PostgreSQL does not overwrite a row on update. It writes a new version and leaves the old one for vacuum to clean up later. If autovacuum cannot keep up, or is switched off for a table, or is held back by a long transaction, the table fills with dead rows and every scan reads them. We created a 500,000-row table with autovacuum off and updated every row five times: SELECT n_live_tup, n_dead_tup, last_autovacuum, pg_size_pretty(pg_table_size('sessions')) AS table_size FROM pg_stat_user_tables WHERE relname = 'sessions';

n_live_tup | n_dead_tup | last_autovacuum | table_size ------------+------------+-----------------+------------ 500000 | 2499949 | | 710 MB

State of the tableSizeTime to count the rows

Fresh118 MB80 ms After five full updates, no vacuum710 MB1,283 ms After VACUUM710 MB129 ms After VACUUM FULL118 MB69 ms

Two honest notes on this table. The 1,283 ms figure includes one-off work the first scan after a bulk update has to do, so the steady-state penalty is smaller than it looks. And plain VACUUM made the space reusable but did not return it: the file stayed at 710 MB, and the scan still had to walk six times as many pages as the fresh table. VACUUM FULL rewrites the table and gives the space back, but it holds an exclusive lock for the whole rewrite, which on a large table is the lock queue from the previous section for minutes or hours. Prefer to stop the growth: find out why autovacuum is behind. The usual reasons are a long-running or idle transaction that keeps old row versions alive, autovacuum disabled on a table, or thresholds too relaxed for a large, busy table. Look for tables where n_dead_tup is a large share of n_live_tup and last_autovacuum is old or empty.

Too many connections: what PgBouncer does and does not do Every PostgreSQL connection is a server process. The server has a fixed max_connections, and when the application opens more, new connections are refused. We set the limit to 60 and started 100 clients: pgbench: error: connection to server at "pgslow-db", port 5432 failed: FATAL: sorry, too many clients already To the application this looks like a database outage. Raising max_connections into the thousands is not the fix, because each connection costs memory and the server does not do more work with 1,000 active processes than with a few dozen. The fix is a pooler. PgBouncer sits between the application and the server, accepts many client connections and shares a small number of server connections among them. We put PgBouncer 1.26.1 in front of the same server, in transaction mode with a pool of 20 server connections: [databases] shop = host=pgslow-db port=5432 dbname=shop

[pgbouncer] pool_mode = transaction default_pool_size = 20 max_client_conn = 500 max_prepared_statements = 200

ClientsPathResultTransactions per secondAverage latency

20DirectOK41,2520.49 ms 100DirectRefused: too many clientsnonenone 100PgBouncer, 20 server connectionsOK15,6476.4 ms 400PgBouncer, 20 server connectionsOK12,72031 ms

Read this table carefully, because it does not say what PgBouncer’s reputation suggests. Through the pooler, 400 clients were served by 20 server connections with no errors. But throughput was lower than 20 direct connections, and latency rose with the number of clients, because clients now wait their turn for a server connection and PgBouncer itself runs on a single CPU core. In this lab that one core was the limit; pgbench and the database also shared the machine. So: a pooler turns “connection refused” into “wait a few milliseconds”. It protects the server. It does not make a slow query faster, and if the 20 server connections are all busy with slow queries, clients queue in PgBouncer instead (SHOW POOLS on its admin console shows them as cl_waiting). Transaction mode has a price. A client keeps a server connection only for the length of one transaction, so anything that belongs to a session does not carry over: session-level SET, session-level advisory locks, LISTEN, and temporary tables that outlive the transaction. Session-level PREPARE does not work either, but protocol-level prepared statements, the kind most drivers use, do: PgBouncer has supported them in transaction mode since 1.21, and max_prepared_statements has defaulted to 200 since 1.24. The PgBouncer feature table lists what each pooling mode supports; check your framework against it before switching.

On Amazon RDS and Cloud SQL Everything above works on managed PostgreSQL, with these differences:

Settings are changed in a parameter group (Amazon RDS and Aurora) or as database flags (Cloud SQL), not in postgresql.conf. pg_stat_statements is available on both; you still run CREATE EXTENSION yourself. The consoles show the same data in charts. On AWS that is CloudWatch Database Insights, which builds on Performance Insights; on Google Cloud it is Query Insights. Both rank statements by load and show what sessions wait on, which covers steps 1 and 2. For step 3 you still need EXPLAIN. Pooling is offered as a service: RDS Proxy on AWS and Managed Connection Pooling on Cloud SQL, which needs the Enterprise Plus edition and has prepared-statement support switched off by default. The limits of transaction pooling described above apply to them too. Resize last. A larger instance would have taken our orders query from slow to slightly less slow at several times the price. The index cost four seconds.

If the database is also on an old major version, check its end-of-life date before investing in tuning: see our PostgreSQL 14 end of life and upgrade guide.

Method and limits

PostgreSQL 18.7 (official postgres:18 Docker image) and PgBouncer 1.26.1 from the PostgreSQL apt repository, run on 3 December 2026. PostgreSQL 19 was released two weeks earlier; we tested 18 because it is what most servers will run for some time, and every view and setting used here exists in both. One laptop: AMD Ryzen 7 PRO 5850U (16 threads), 37 GB RAM. Database, load generator and pooler all ran on it, so they competed for CPU. Default PostgreSQL settings except those named in the text (shared_preload_libraries, log_min_duration_statement = 250, track_io_timing, log_lock_waits, deadlock_timeout = 1s, max_connections = 60). Load from pgbench with custom scripts, eight clients for 60 seconds in the index test, 30 seconds in the connection tests. Each test ran once. Tables are small (436 MB of orders) and fit in memory. On a database larger than memory the missing index would cost far more, and the disk sort would be slower. Plans in the article have cost estimates and repeated buffer lines removed for width. The complete outputs, the schema and the scripts are in the lab download.

Frequently asked questions How do I find slow queries in PostgreSQL? Enable pg_stat_statements and sort by total_exec_time to see which statements the server spends its time on. Set log_min_duration_statement to log individual slow statements with their parameter values. What is the difference between EXPLAIN and EXPLAIN ANALYZE? EXPLAIN shows the plan PostgreSQL would use, with estimates. EXPLAIN ANALYZE runs the statement and adds the real row counts and times. Add BUFFERS to see how many pages each step touched; from PostgreSQL 18 it is included automatically. Does PgBouncer make PostgreSQL faster? Not per query. It lets many clients share few server connections, which prevents “too many clients” errors and protects the server from connection storms. In our test, throughput through the pooler was lower than with a small number of direct connections. Why is a query slow only sometimes? The usual causes are lock waits, a different plan for different parameter values, or competition for CPU and disk with other statements. Compare pg_stat_activity during a slow period with a normal one, and check the log for lock wait lines. Should I run VACUUM FULL to fix a bloated table? Only when you can afford the exclusive lock for the whole rewrite. Plain VACUUM makes the space reusable without blocking. First find out why autovacuum fell behind, or the table will grow again.

	The post How to investigate a slow PostgreSQL database: six checks, tested on PostgreSQL 18 appeared first on Oreon IT.

Kaynak: Planet PostgreSQL

#PostgreSQL
Share

From other categories