Quick revision
The short answer
I would treat exact totals as a cost the company is paying without deciding to. First quantify it: the database time spent on count queries from pg_stat_statements and the hardware it ties up. Then work with product and design to separate the places where exact numbers matter, such as billing and compliance, from those where estimates or caps are fine, give teams platform patterns (counter services, summary tables, approximate counts, pagination without totals), make cursor pagination without totals the API default, and track adoption and database savings over time.
What to remember
In this answer, we saw how to reduce the cost of exact totals at company scale. We quantify the database time spent on counts with pg_stat_statements and translate it into hardware cost, classify totals with product and design into exact, maintained, estimated or removed, provide platform patterns such as counter services, summary tables, approximate counts and cursor pagination, make pagination without totals the API default, and track adoption and savings so the change keeps its support.
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.
I would treat exact totals as a cost the company is paying without deciding to. First quantify it: the database time spent on count queries from pg_stat_statements and the hardware it ties up. Then work with product and design to separate the places where exact numbers matter, such as billing and compliance, from those where estimates or caps are fine, give teams platform patterns (counter services, summary tables, approximate counts, pagination without totals), make cursor pagination without totals the API default, and track adoption and database savings over time.
Why this question is asked
Totals on every list screen usually arrive one at a time, each reasonable on its own, until count queries are a large share of the database bill and a regular source of slow pages. Changing that is not a technical problem only, because the totals are part of product design, API contracts and habits. Interviewers ask this to see how a senior engineer drives a cross-team change with evidence. In this answer, we will measure the cost, decide with product where exactness matters, provide patterns teams can adopt, set API defaults, and track the result.
1A Quick Recap: Why Exact Totals Are Expensive
In PostgreSQL and other MVCC databases, an exact COUNT must visit every matching row, or index entry, and check that it is visible to the current transaction, because no stored count can be right for every transaction at once. So the cost of a total grows with the data, while the page of 20 rows next to it stays cheap. A paginated endpoint that returns totals often spends most of its database time on the count, and does it again on every click.
2Quantify the Cost First
A company-wide change needs a number everyone can see. pg_stat_statements aggregates execution time per normalized query, so we can measure how much time count queries take compared with everything else, per database and per service.
Notice that the match on query text is rough; ORM-generated counts may look like select count(o1_0.id) and still match, but counts inside larger queries will not, so we treat it as a lower bound. Translating that share into money makes it concrete: if a third of database time on a cluster that costs a known amount per month goes to counts, and replicas were added mainly for list pages, the potential saving is visible in the budget, not just in latency graphs.
3Decide With Product Where Exactness Matters
Engineering cannot remove totals alone, because users and contracts see them. So we review the screens and reports with product managers and designers and classify each total. The question is not 'can we remove it?' but 'what decision does this number support, and what happens if it is approximate or stale?'
| Kind of number | Example | Treatment |
|---|---|---|
| Money and billing | invoice line count, balance | exact, from the source of truth |
| Compliance and legal | records retained, audit totals | exact, computed in batch |
| Operational badges | unread, open tickets | maintained counter, seconds of lag ok |
| List and search totals | '48,210 results' | estimate or '10,000+' cap |
| Deep pagination | 'page 3 of 4,812' | remove; next and previous only |
The result is usually that a small set of numbers really needs to be exact, and the long tail of list totals can become estimates, caps or nothing at all, which most users never notice.
4Give Teams Patterns, Not Just Rules
A guideline without an easy alternative is ignored. The platform team provides ready-made building blocks. A counter service or library maintains counts on the write path, with sharded rows for hot counters and a recomputation job to correct drift. Summary tables give per-period totals for reports. An approximate count helper reads planner estimates or runs a capped count that stops at 10,001 rows. Pagination components in the front end and the API library support cursor-based next and previous without totals, and Spring Data's Slice and Window types make the back end side short.
Each pattern comes with documentation, an example service and, ideally, migration help from the platform team for the first adopters, so the cheapest path for a team is also the efficient one.
5Set API Defaults and Roll Out
The default shapes the future. We change the API guidelines so that list endpoints use cursor pagination without totals unless the classification says a total is needed, and new endpoints are reviewed against that rule. Existing endpoints migrate over time, starting with those that cost the most according to the measurements.
- Measure count share per databasepg_stat_statements, cost per cluster
- Classify totals with productexact, maintained, estimate, none
- Provide patternscounters, summaries, caps, cursors
- Change API defaultcursor pagination without totals
- Migrate top offenders firstlargest database time first
- Report adoption and savingsquarterly, in money and latency
6 steps in order. Play them, or step through them one at a time.
A loop of measuring, changing defaults and showing the saving.
Measurement continues after the rollout. We report the share of database time spent on counts per quarter, the number of endpoints migrated, and capacity released, for example replicas removed or a cluster downsized. Reporting the saving keeps the work funded and shows teams that their migrations mattered.
6Follow-up questions
What if a large customer insists on exact totals?
Ask what they use the number for. If it is for reconciliation or billing, provide it through an export or report computed in batch, where exactness is cheap. If it is just reassurance on a list screen, an estimate with a clear label usually satisfies them once explained.
How do you avoid breaking existing API clients?
Keep the old fields during a deprecation period, possibly returning totals only when a parameter asks for them, and track which clients still use them. Removing a field without a migration path damages trust more than the saving is worth.
Is this premature optimisation?
Not when measurements show counts taking a large share of database time. That is exactly why the first step is to quantify: if counts turned out to be two percent of the load, I would stop and spend the effort elsewhere.
7Conclusion
In this answer, we saw how to reduce the cost of exact totals at company scale. We quantify the database time spent on counts with pg_stat_statements and translate it into hardware cost, classify totals with product and design into exact, maintained, estimated or removed, provide platform patterns such as counter services, summary tables, approximate counts and cursor pagination, make pagination without totals the API default, and track adoption and savings so the change keeps its support.
Open with
I would start by quantifying it, because a cross-team change needs evidence. From pg_stat_statements on each database I would measure the share of execution time spent on count queries and translate it into hardware: replicas or cluster size that exist mainly to serve totals.
Then, if they want more
If that is, say, a third of database time, it is a clear case. Then I would work with product and design to classify the numbers. Billing, balances and compliance totals must be exact and come from the source of truth. Badges like unread or open tickets can come from maintained counters.
Most list and search totals can be estimates or capped, like 10,000 plus, and page X of Y can usually go away.
For teams to follow, I would give them patterns, not just rules: a counter library with sharded counters and a recomputation job, summary tables for reports, a helper for approximate and capped counts, and pagination components using Slice or Window.
I would change the API guidelines so new list endpoints default to cursor pagination without totals, and migrate the most expensive existing endpoints first, keeping old fields through a deprecation period. Finally I would report each quarter on the count share of database time, endpoints migrated and capacity released, so the saving is visible and the programme keeps its support.
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 "Exact totals appear in dozens of UIs and reports, and they drive a large share of...": https://scrivio-interview-library.netlify.app/databases/query-optimization/f0be0eb177/