Sub topic 7
Spotting I/O-heavy queries with buffer counters
This chapter assumes you have enabled pg_stat_statements, can run the total-time and mean-time rankings from earlier chapters, and know that a query plan is a tree of nodes. You should also know that PostgreSQL stores table and index data in 8 kB pages, which it calls blocks.
Time rankings tell you which queries are expensive. They don't tell you why. The buffer counters give a first answer to one cause: how much data a query touches, and where that data comes from.
What the buffer counters measure
PostgreSQL keeps recently used blocks in a memory area called shared buffers. When a query needs a block, one of two things happens:
- The block is already in shared buffers. This is a hit.
- The block is not there, so PostgreSQL asks the operating system for it. This is a read.
pg_stat_statements adds up these events for every execution of a normalized query. The main columns are:
| Column | Meaning |
|---|---|
| `shared_blks_hit` | Block requests served from shared buffers |
| `shared_blks_read` | Blocks requested from the operating system |
| `shared_blks_dirtied` | Blocks the query modified for the first time since they were last written out |
| `shared_blks_written` | Dirty blocks the query's own backend had to write out |
| `local_blks_hit`, `local_blks_read`, `local_blks_dirtied`, `local_blks_written` | The same counters for temporary tables, which use backend-local buffers |
| `temp_blks_read`, `temp_blks_written` | Blocks of temporary files used by sorts, hashes, and similar work (covered in a later chapter) |
All of these are cumulative since the last reset, summed over every call. To get a per-call figure, divide by calls.
A read is not always a disk read
shared_blks_read means "not found in shared buffers." The operating system may still have the block in its own page cache, so the request can be satisfied from RAM without touching a disk. The counter therefore tells you how much data a query pulled in from outside PostgreSQL's cache. It does not tell you how much physical disk I/O happened. To measure real read time, you need I/O timing, covered below.
Ranking by blocks read
Start with the query from the plan. It sorts by shared_blks_read and computes a hit percentage:
SELECT queryid,
calls,
shared_blks_hit,
shared_blks_read,
round(100.0 * shared_blks_hit
/ nullif(shared_blks_hit + shared_blks_read, 0), 1) AS hit_pct,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY shared_blks_read DESC
LIMIT 10;nullif turns a zero denominator into NULL, so statements that touched no shared blocks show hit_pct as NULL instead of raising a division-by-zero error.
The table below shows how to read typical results.
| Pattern | Likely meaning |
|---|---|
| High `shared_blks_read`, low `hit_pct` | The query touches data that is not cached. Possible causes are a large scan, a working set bigger than shared buffers, or a cold cache after a restart. |
| High `shared_blks_read`, high `hit_pct` | The query touches so many blocks that even a small miss rate adds up. The query is large, not necessarily badly cached. |
| Low `shared_blks_read`, very high `shared_blks_hit` | The query is served from memory but may still be expensive in CPU. Repeated index lookups or a nested loop re-reading the same blocks produce this pattern. |
| `shared_blks_dirtied` high | The query is a heavy writer (UPDATE, DELETE, or INSERT). It may also have set hint bits while reading. |
Convert blocks to megabytes
Block counts are hard to compare by feel. This query converts them to megabytes using the server's actual block size and divides by calls to get a per-call figure:
SELECT queryid,
calls,
round(shared_blks_read::numeric
* current_setting('block_size')::int / 1024 / 1024, 1) AS read_mb,
round(shared_blks_read::numeric / calls, 1) AS read_blks_per_call,
left(query, 80) AS query
FROM pg_stat_statements
WHERE calls > 0
ORDER BY shared_blks_read DESC
LIMIT 10;A query that reads 50,000 blocks per call (about 400 MB) is scanning a lot of data every time. A query that reads 3 blocks per call but runs two million times is a different problem, and it needs a different fix, such as caching in the application or fewer round trips.
Why hit percentage can mislead
The hit percentage is a useful screen, but keep these gotchas in mind:
- Hits count requests, not distinct blocks. A nested loop that fetches the same index page 100,000 times adds 100,000 hits. A 99.9% hit ratio can sit on top of a plan that does far too much work.
- A good ratio does not make a query cheap. Look at the absolute numbers. A query with 99% hits and 40 million hit blocks per call is still doing a lot of work.
- A poor ratio can be normal. A reporting query that scans a large table once a day will always read. Compare it against how often it runs and how much time it takes.
- Cold caches distort the numbers. After a restart or failover, every query looks I/O-heavy for a while. Reset the statistics after the cache warms up, or read the numbers with the restart time in mind.
- Shared buffers are only one cache layer. A low hit ratio with a fast query can mean the operating system cache is doing the work.
Adding I/O timing
To find out how long reads and writes took, turn on track_io_timing. It is off by default because it calls the system clock for each I/O, which is cheap on most modern hardware but can cost more on some virtualized systems. PostgreSQL ships the pg_test_timing tool to measure that cost on your server.
ALTER SYSTEM SET track_io_timing = on;
SELECT pg_reload_conf();The setting takes effect after a configuration reload, with no restart. Only I/O that happens after the change is timed.
The timing columns changed names in PostgreSQL 17. On PostgreSQL 16 and earlier, use blk_read_time and blk_write_time:
SELECT queryid,
calls,
shared_blks_read,
round(blk_read_time::numeric, 2) AS read_ms,
round((blk_read_time / nullif(shared_blks_read, 0))::numeric, 3) AS ms_per_blk,
left(query, 80) AS query
FROM pg_stat_statements
WHERE shared_blks_read > 0
ORDER BY blk_read_time DESC
LIMIT 10;On PostgreSQL 17 and later, the same data is in shared_blk_read_time and shared_blk_write_time, with separate local_blk_read_time and local_blk_write_time columns for temporary tables. Replace blk_read_time with shared_blk_read_time in the query above.
The ms_per_blk column is the useful part. Values well under a millisecond per block suggest that most "reads" came from the operating system cache. Values of several milliseconds per block point to real disk waits. Compare read_ms with total_exec_time to see what fraction of the query's time went to waiting for blocks. If read time is a small part of the total, the query is not I/O-bound, even if it has a lot of reads.
A triage workflow
The following flowchart summarizes how to decide where to look next.
If the answer is a large scan, move to EXPLAIN. Take real parameter values from your application, because the plan may depend on them:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;Each plan node reports Buffers: shared hit=... read=.... The node with the largest read count is where the I/O happens. The following chapter on EXPLAIN covers how to read this output in detail.
Edge cases
- Mixed-up call patterns. One normalized query can run with a small parameter value one time and a huge one the next. The averages per call hide this. If the numbers look odd, compare with
max_exec_timeandstddev_exec_time. - Writes and dirtied blocks.
shared_blks_writtencounts only blocks the query's own backend wrote, typically when it had to evict a dirty buffer to make room. Most writing is done by the background writer and the checkpointer, so a low value here does not mean the system is write-light. - Temporary tables. Queries on temporary tables report
local_blks_*, notshared_blks_*. A ranking by shared reads will miss them. - Cache sharing between queries. One query's reads can evict blocks that another query needs. The second query then shows more reads even though its own plan didn't change. Look at the whole workload, not one row.
- Statistics are per database and per server run. A reset or an eviction of the entry from the statistics table removes the history for that query.
Exercise
A query shows sharedblkshit = 9,000,000, sharedblksread = 1,000, calls = 3,000, and hitpct of 99.9. Another query shows sharedblkshit = 4,000,000, sharedblks_read = 2,000,000, and calls = 40. Which one should you investigate first for I/O, and what extra column would confirm it?
Show answer
The second query. It reads 50,000 blocks per call (2,000,000 / 40), about 400 MB with 8 kB blocks, and its hitpct is only about 67%. The first query reads about 0.3 blocks per call and is served almost entirely from memory. To confirm the second query is I/O-bound, enable trackiotiming and compare its read time (blkreadtime, or sharedblkreadtime on PostgreSQL 17+) with totalexectime. Then run EXPLAIN (ANALYZE, BUFFERS) to find the plan node that does the reads.
Exercise
Why does a high sharedblksread value not always mean the disk was busy?
Show answer
sharedblksread counts blocks that were not found in shared buffers. PostgreSQL requested them from the operating system, which may have returned them from its page cache without any physical disk read. Only the I/O timing columns, with trackiotiming on, show how long those requests actually took.