Postgres count(*) Slow? The Narrow Index Barely Helps
A tile that answered in 130 ms and still felt slow
The admin dashboard has a tile in the top row that reads Total orders. I added it in a hurry last quarter: one SELECT count(*) behind the endpoint, cached for thirty seconds, done. On staging with forty thousand rows it beat the spinner, so I never looked again. Production hit five million orders by fall and the tile became the slowest thing on the first screen.
I rebuilt the table on a scratch Postgres 16.15 cluster so the numbers were rerunnable: five million synthetic orders, a 482 MB heap, indexes on created_at and status, a default 256 MB shared_buffers, twelve cores. Everything below is warm cache.
Nothing in Postgres is counting
There is no row counter to read. Under MVCC visibility depends on who is asking, so two sessions can see different totals from the same page at the same instant. MyISAM kept one in the header and paid with table locks; InnoDB and Postgres decided the count wasn't worth that contention, so count(*) walks every row version that might be visible and tests it against your snapshot.
Which is why the famous micro-optimization does nothing. count(1) and count(id) came back in 146 and 148 ms against 139 for count(*), same Parallel Seq Scan, same row estimates. The row gets visited either way.
The index buys a fifth, not a factor of ten
The advice I kept running into was to give the count a narrow index so it runs as an index-only scan. So I went rung by rung.
| Plan, five million rows, warm | Time |
|---|---|
| serial seq scan | 320 ms |
| parallel seq scan, 2 workers (default) | 133 ms |
| parallel index-only scan, 33 MB index | 100 ms |
| parallel index-only scan, 4 workers | 56 ms |
WHERE status = 'paid', index-only | 17.6 ms |
sum(cnt) from a summary table | 0.2 ms |
The 33 MB status index holds the same five million entries the heap holds rows, so the scan still loops five million times. A tenth of the bytes buys a quarter off the clock, no more, and none of these plans examine fewer than five million rows.
The lever that moved was workers. max_parallel_workers_per_gather defaults to 2, so the scan ran on two of twelve cores; setting it to 4 dropped the same count to 56 ms. Asking for 6 got me 4.
Where an index really pays
The tile doesn't have to count the whole table. Beside it sits a paid-orders number:
SELECT count(*) FROM orders WHERE status = 'paid';
833,218 of the five million rows qualify, and the index on status turns that into a Parallel Index Only Scan with an Index Cond at 17.6 ms. With index-only scans disabled the planner used a Bitmap Heap Scan: 262 ms, pulling 833,218 rows out of the index and then fetching the heap for each one. Same answer, fifteen times the work.
That is the dividing line. An index helps a count when it lets you visit fewer rows, never when it only lets you visit smaller ones. Heap Fetches: 0 only holds while the visibility map is clean, so recent writes without a vacuum turn the index-only scan back into a heap read, as that counter shows.
The count that held the vacuum back
I found this by accident, with a session left open on the plan.
BEGIN;
SELECT count(*) FROM orders;
SELECT pg_sleep(30);
COMMIT;
During those thirty seconds I deleted 835,342 orders and ran VACUUM (VERBOSE):
tuples: 0 removed, 5500000 remain, 835342 are dead but not yet removable
removable cutoff: 741, which was 1 XIDs old when operation ended
Nothing reclaimed. The count had pinned a snapshot, and its xmin is the horizon vacuum has to stay behind, so rows deleted after it started stay out of reach. After the COMMIT, the next vacuum reported 835342 removed in 0.33 seconds.
In autocommit the window is one statement, which is harmless. It matters inside something longer: a nightly report that counts and then runs five more queries, a session someone left open on a Friday. Dead rows stack up, the heap and every index on it grow, and the next count is slower because there is more to walk. Autovacuum falling behind, caused by a read.
Estimates, and the counter I ship now
The tile needs a number that is roughly right and always fast, so it reads reltuples from pg_class: 0.04 ms warm, against 133 ms for the truth.
It gets stale, though. After VACUUM ANALYZE it said 4,999,948 for five million rows, off by 52. I then bulk-loaded 500,000 more and it still said 4,999,948 while n_live_tup had already moved to 5,499,948, because the stats system counts inserts as they land and reltuples only moves on ANALYZE or VACUUM. Nine percent low on a table that was ten percent bigger. Both are estimates, and the tile is labelled as one.
The weekly report needs the same number at 9am and at 5pm, so it reads a summary table keyed by day and status. 2,924 rows, 344 kB, and sum(cnt) lands in 0.2 ms:
INSERT INTO order_counts (day, status, cnt)
VALUES ($1, $2, 1)
ON CONFLICT (day, status) DO UPDATE
SET cnt = order_counts.cnt + 1;
That runs in the same transaction as the order insert, or the counter drifts and nobody notices for months. It also serializes on one row per day and status, fine at our volume and a genuine hotspot if a promotion hammers a single bucket.
The SQL and plans live in Snippet Ark next to the pagination queries, since the next person to add a tile copies whichever version they find first.