[{"data":1,"prerenderedAt":6},["ShallowReactive",2],{"post-content-postgres-count-star-slow-fix":3},{"content":4,"lastModified":5},"\u003Ch2>A tile that answered in 130 ms and still felt slow\u003C\u002Fh2>\n\n\u003Cp>The admin dashboard has a tile in the top row that reads Total orders. I added it in a hurry last quarter: one \u003Ccode>SELECT count(*)\u003C\u002Fcode> 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.\u003C\u002Fp>\n\n\u003Cp>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 \u003Ccode>created_at\u003C\u002Fcode> and \u003Ccode>status\u003C\u002Fcode>, a default 256 MB shared_buffers, twelve cores. Everything below is warm cache.\u003C\u002Fp>\n\n\u003Ch2>Nothing in Postgres is counting\u003C\u002Fh2>\n\n\u003Cp>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 \u003Ccode>count(*)\u003C\u002Fcode> walks every row version that might be visible and tests it against your snapshot.\u003C\u002Fp>\n\n\u003Cp>Which is why the famous micro-optimization does nothing. \u003Ccode>count(1)\u003C\u002Fcode> and \u003Ccode>count(id)\u003C\u002Fcode> came back in 146 and 148 ms against 139 for \u003Ccode>count(*)\u003C\u002Fcode>, same Parallel Seq Scan, same row estimates. The row gets visited either way.\u003C\u002Fp>\n\n\u003Ch2>The index buys a fifth, not a factor of ten\u003C\u002Fh2>\n\n\u003Cp>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.\u003C\u002Fp>\n\n\u003Ctable>\n  \u003Cthead>\n    \u003Ctr>\u003Cth>Plan, five million rows, warm\u003C\u002Fth>\u003Cth>Time\u003C\u002Fth>\u003C\u002Ftr>\n  \u003C\u002Fthead>\n  \u003Ctbody>\n    \u003Ctr>\u003Ctd>serial seq scan\u003C\u002Ftd>\u003Ctd>320 ms\u003C\u002Ftd>\u003C\u002Ftr>\n    \u003Ctr>\u003Ctd>parallel seq scan, 2 workers (default)\u003C\u002Ftd>\u003Ctd>133 ms\u003C\u002Ftd>\u003C\u002Ftr>\n    \u003Ctr>\u003Ctd>parallel index-only scan, 33 MB index\u003C\u002Ftd>\u003Ctd>100 ms\u003C\u002Ftd>\u003C\u002Ftr>\n    \u003Ctr>\u003Ctd>parallel index-only scan, 4 workers\u003C\u002Ftd>\u003Ctd>56 ms\u003C\u002Ftd>\u003C\u002Ftr>\n    \u003Ctr>\u003Ctd>\u003Ccode>WHERE status = 'paid'\u003C\u002Fcode>, index-only\u003C\u002Ftd>\u003Ctd>17.6 ms\u003C\u002Ftd>\u003C\u002Ftr>\n    \u003Ctr>\u003Ctd>\u003Ccode>sum(cnt)\u003C\u002Fcode> from a summary table\u003C\u002Ftd>\u003Ctd>0.2 ms\u003C\u002Ftd>\u003C\u002Ftr>\n  \u003C\u002Ftbody>\n\u003C\u002Ftable>\n\n\u003Cp>The 33 MB \u003Ccode>status\u003C\u002Fcode> 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.\u003C\u002Fp>\n\n\u003Cp>The lever that moved was workers. \u003Ccode>max_parallel_workers_per_gather\u003C\u002Fcode> 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.\u003C\u002Fp>\n\n\u003Cfigure>\n  \u003Cimg src=\"https:\u002F\u002Fimages.pexels.com\u002Fphotos\u002F38195854\u002Fpexels-photo-38195854.jpeg?auto=compress&amp;cs=tinysrgb&amp;fit=crop&amp;w=1200&amp;h=800\" alt=\"Cardboard boxes stacked on warehouse racking, each bay labelled with a location code\" loading=\"lazy\" width=\"1200\" height=\"800\">\n\u003C\u002Ffigure>\n\n\u003Ch2>Where an index really pays\u003C\u002Fh2>\n\n\u003Cp>The tile doesn't have to count the whole table. Beside it sits a paid-orders number:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">SELECT count(*) FROM orders WHERE status = 'paid';\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>833,218 of the five million rows qualify, and the index on \u003Ccode>status\u003C\u002Fcode> turns that into a Parallel Index Only Scan with an \u003Ccode>Index Cond\u003C\u002Fcode> 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.\u003C\u002Fp>\n\n\u003Cp>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. \u003Ccode>Heap Fetches: 0\u003C\u002Fcode> only holds while the visibility map is clean, so recent writes without a vacuum turn the index-only scan back into a heap read, \u003Ca href=\"\u002Fposts\u002Fpostgres-index-only-scan-heap-fetches\u002F\">as that counter shows\u003C\u002Fa>.\u003C\u002Fp>\n\n\u003Ch2>The count that held the vacuum back\u003C\u002Fh2>\n\n\u003Cp>I found this by accident, with a session left open on the plan.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">BEGIN;\nSELECT count(*) FROM orders;\nSELECT pg_sleep(30);\nCOMMIT;\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>During those thirty seconds I deleted 835,342 orders and ran \u003Ccode>VACUUM (VERBOSE)\u003C\u002Fcode>:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>tuples: 0 removed, 5500000 remain, 835342 are dead but not yet removable\nremovable cutoff: 741, which was 1 XIDs old when operation ended\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>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 \u003Ccode>COMMIT\u003C\u002Fcode>, the next vacuum reported \u003Ccode>835342 removed\u003C\u002Fcode> in 0.33 seconds.\u003C\u002Fp>\n\n\u003Cp>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. \u003Ca href=\"\u002Fposts\u002Fpostgres-table-bloat-autovacuum-falling-behind\u002F\">Autovacuum falling behind\u003C\u002Fa>, caused by a read.\u003C\u002Fp>\n\n\u003Ch2>Estimates, and the counter I ship now\u003C\u002Fh2>\n\n\u003Cp>The tile needs a number that is roughly right and always fast, so it reads \u003Ccode>reltuples\u003C\u002Fcode> from \u003Ccode>pg_class\u003C\u002Fcode>: 0.04 ms warm, against 133 ms for the truth.\u003C\u002Fp>\n\n\u003Cp>It gets stale, though. After \u003Ccode>VACUUM ANALYZE\u003C\u002Fcode> 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 \u003Ccode>n_live_tup\u003C\u002Fcode> had already moved to 5,499,948, because the stats system counts inserts as they land and \u003Ccode>reltuples\u003C\u002Fcode> 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.\u003C\u002Fp>\n\n\u003Cp>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 \u003Ccode>sum(cnt)\u003C\u002Fcode> lands in 0.2 ms:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-sql\">INSERT INTO order_counts (day, status, cnt)\nVALUES ($1, $2, 1)\nON CONFLICT (day, status) DO UPDATE\n  SET cnt = order_counts.cnt + 1;\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>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.\u003C\u002Fp>\n\n\u003Cp>The SQL and plans live in \u003Ca href=\"\u002Fsnippetark\u002F\">Snippet Ark\u003C\u002Fa> next to the \u003Ca href=\"\u002Fposts\u002Fkeyset-pagination-postgres-page-2-backwards\u002F\">pagination queries\u003C\u002Fa>, since the next person to add a tile copies whichever version they find first.\u003C\u002Fp>\n","2026-12-03",1796349652838]