Quick revision
The short answer
First, we give the query an index on (project_id, status) so PostgreSQL can count from the index alone, and we tune autovacuum on the table so the visibility map stays fresh enough for that index-only scan to skip the heap. Then we stop running the query for every user: we cache each project's counts for a few seconds, and for the hottest dashboards we keep a small summary table of counts. We measure each step with EXPLAIN (ANALYZE, BUFFERS).
What to remember
In this answer, we made a hot dashboard query fast in layers. An index on (project_id, status) lets PostgreSQL count from the index, but only pages marked all-visible in the visibility map avoid heap fetches, so we lowered autovacuum_vacuum_scale_factor for the table to keep that map fresh. Then we stopped running the query per user with a short per-project cache, and for the hottest cases kept a summary table updated in the same transaction or by an event consumer, with reconciliation. EXPLAIN (ANALYZE, BUFFERS) confirmed each step by showing heap fetches and page reads drop.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
First, we give the query an index on (project_id, status) so PostgreSQL can count from the index alone, and we tune autovacuum on the table so the visibility map stays fresh enough for that index-only scan to skip the heap. Then we stop running the query for every user: we cache each project's counts for a few seconds, and for the hottest dashboards we keep a small summary table of counts. We measure each step with EXPLAIN (ANALYZE, BUFFERS).
Why this question is asked
Dashboards are where a harmless-looking query turns into a capacity problem. One count per project is cheap once, but thousands of users refreshing every few seconds turn it into hundreds of identical queries per second against a table that never stops changing. Interviewers ask this scenario because the answer has layers: an index helps, but in PostgreSQL its benefit depends on vacuum, and past a certain load the right answer is not to run the query at all. In this answer, we will recap what an index-only scan needs, build the index, see why constant updates weaken it, tune autovacuum, add caching and a summary table, and measure the result.
1A Quick Recap of Index-Only Scans
An index-only scan is a plan where the database answers a query from the index without visiting the table rows. It is possible when every column the query touches is stored in the index. Our query reads project_id and status and counts rows, so an index on (project_id, status) holds everything it needs.
In PostgreSQL there is a catch. Table rows live in the heap, the main storage of the table, and each row version carries visibility information that says which transactions can see it. Index entries do not carry that information. So before PostgreSQL trusts an index entry, it must know whether the row is visible to our transaction. It checks the visibility map, a small bitmap with one bit per heap page that says 'every row on this page is visible to everyone'. If the bit is set, the heap page is skipped. If not, PostgreSQL must fetch the heap page anyway, and EXPLAIN reports it as a heap fetch.
2Building the Index and Reading the Plan
We create the index without blocking writes, then look at the plan with buffer counts, which show how many pages each step touched.
Notice that the index entries for project 42 are already sorted by status, so the aggregate can count each status in one pass without sorting. The plan shape is right. The weak point is the heap fetches line: 95,000 of 180,000 rows still made PostgreSQL read heap pages. The reason is the constant updates. Every update creates a new row version and clears the all-visible bit for the page it touches, and the bit is only set again when vacuum processes that page. On a table that changes all the time, a large part of the pages are not all-visible at any moment, and the index-only scan quietly becomes an index scan with extra work.
3Tuning Autovacuum So More Pages Stay All-Visible
Autovacuum, the background process that runs vacuum, starts on a table when dead rows exceed a threshold plus a fraction of the table, set by autovacuum_vacuum_scale_factor. The default fraction is 0.2, which on 500 million rows means vacuum waits for about 100 million dead rows. That is far too late for our visibility map. We lower the fraction for this table only, and allow vacuum to work faster.
So vacuum now runs often, each run sets the all-visible bits on pages that have settled, and the index-only scan reads almost no heap pages. The numbers in the comments are illustrative, but the direction is what we look for: heap fetches and buffer reads drop sharply. There is a limit, though. Rows that are being updated right now will always be on pages that are not all-visible, so on a very hot table we reduce the cost but never make it zero.
4Not Running the Query for Every User
Even a fast query is wasted when it is run thousands of times for the same answer. All users looking at project 42 see the same five numbers. A short cache, for example five seconds per project in Redis or in a local Caffeine cache, turns hundreds of queries per second into one query per project every five seconds. Users do not notice counts that are a few seconds old, because the dashboard already refreshes on a timer.
For the very hottest dashboards, we go one step further and keep a summary table, ticket_counts(project_id, status, n), with one row per project and status. There are two ways to keep it current. We can update it in the same transaction that inserts or changes a ticket, which keeps it exact but adds a hot row that many writers lock. Or an event consumer reads ticket changes from an outbox or change data capture and applies them, which keeps writes fast and accepts a small lag. The dashboard query then reads five rows instead of counting 180,000.
- Request for project 42 countsthousands of users, every few seconds
- Cached within 5 seconds?YesReturn the cached countsNoAsk the database
- Summary table enabled?YesRead 5 rows from ticket_countsNoCount with the index-only scan
- Store the result in the cachethe next requests stay in memory
4 steps in order. Play them, or step through them one at a time.
Most requests stop at the cache; the database answers once per project per few seconds.
5Keeping the Summary Table Correct
A status change must move one count from the old status to the new one. The safe way is to apply both changes together, in one statement or one transaction, using the old and new values of the row.
If the counts come from an event consumer, each event must carry the old and the new status, the consumer must ignore events it has already applied (by storing the last processed event id), and a nightly job should recount a few projects from the source table and correct any drift. That reconciliation is what makes eventual consistency safe: mistakes are found and fixed instead of accumulating.
6Follow-up questions
How would you keep the summary table correct when rows change status?
Every change event must carry both the old and the new status, and the update must decrement one count and increment the other in the same transaction. Inserts add one to the new status and deletes subtract one from the old status. If an event consumer applies the changes, it must be idempotent, which means it records the id of each event it applied and skips duplicates. A periodic reconciliation job recounts a sample of projects from the tickets table and repairs differences, so any missed event is corrected within a day.
Would a materialized view work instead of a summary table?
A materialized view is a stored query result that PostgreSQL refreshes only when we run REFRESH MATERIALIZED VIEW, and each refresh recomputes the whole result. On 500 million rows, a refresh every few seconds is impossible. It suits counts that may be minutes or hours old. For near-real-time counts, an incrementally maintained summary table is the better fit.
7Conclusion
In this answer, we made a hot dashboard query fast in layers. An index on (project_id, status) lets PostgreSQL count from the index, but only pages marked all-visible in the visibility map avoid heap fetches, so we lowered autovacuum_vacuum_scale_factor for the table to keep that map fresh. Then we stopped running the query per user with a short per-project cache, and for the hottest cases kept a summary table updated in the same transaction or by an event consumer, with reconciliation. EXPLAIN (ANALYZE, BUFFERS) confirmed each step by showing heap fetches and page reads drop.
Open with
I would attack this in layers. First, an index on project_id and status, because then PostgreSQL can do an index-only scan: the entries for one project are already grouped by status, so it just counts them.
Then, if they want more
But on a constantly updated table, that scan still goes to the heap for every page that is not marked all-visible in the visibility map, and updates keep clearing those bits. So I would lower autovacuum_vacuum_scale_factor for this table, something like half a percent instead of twenty, and raise the cost limit so vacuum keeps up.
I would check with EXPLAIN ANALYZE BUFFERS that heap fetches drop. Second, thousands of users seeing the same project's counts do not need thousands of queries. I would cache the result per project for a few seconds, so the database answers once per project per refresh interval.
Third, if a dashboard is extremely hot, I would maintain a summary table with one row per project and status, updated either in the same transaction or by an event consumer that applies old and new status from each change. The consumer must be idempotent, and a nightly job recounts a sample of projects to catch drift.
I would measure before and after at each step and stop as soon as the latency target is met.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A dashboard endpoint runs SELECT status, count(*) FROM tickets WHERE project_id = ?...": https://scrivio-interview-library.netlify.app/databases/indexing/6d06d40f0f/