Quick revision
The short answer
48,000,000 calls at 0.9 ms each is about 43,000 seconds, roughly 12 hours of database time, more than any individually slow query, so it is worth optimising. The first question is who calls it so often: usually an N+1 pattern, a missing cache or polling, and reducing calls often beats making each call faster. Then we check shared_blks_hit and rows per call for a missing index, consider batching, caching or folding the check into one query, and measure the result by snapshotting or resetting pg_stat_statements before and after.
What to remember
In this answer, we saw that 48 million calls at 0.9 ms add up to about 43,000 seconds of database time, more than any slow query, so the statement deserves attention. We found the caller with application_name, SQL comments or tracing, recognised N+1 patterns, missing caches and polling as the usual causes, checked blocks per row for a missing index, reduced calls with batching, caching or folding the check into one query, and measured the effect by resetting or snapshotting pg_stat_statements.
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.
48,000,000 calls at 0.9 ms each is about 43,000 seconds, roughly 12 hours of database time, more than any individually slow query, so it is worth optimising. The first question is who calls it so often: usually an N+1 pattern, a missing cache or polling, and reducing calls often beats making each call faster. Then we check shared_blks_hit and rows per call for a missing index, consider batching, caching or folding the check into one query, and measure the result by snapshotting or resetting pg_stat_statements before and after.
Why this question is asked
A query that takes under a millisecond never shows up in a slow query log and never looks like a problem in a single trace. Yet in pg_stat_statements it can sit at the top of the list because it runs tens of millions of times. Interviewers use this scenario to see whether we think in total cost, and whether we look at the application's behaviour rather than only at the SQL. In this answer, we will calculate what the query really costs, find where the calls come from, check whether each call is efficient, look at the ways to reduce calls, and measure the result properly.
1What This Query Really Costs
pg_stat_statements groups executions of the same normalised statement and keeps totals. The cost of a statement on the server is its mean time times its number of calls, which is exactly what total_exec_time holds.
48,000,000 x 0.9 ms = 43,200,000 ms = 43,200 seconds, which is 12 hours of execution time. If the statistics cover one day, this single statement keeps, on average, half a CPU core busy all day. A report that takes 20 seconds and runs 100 times costs 2,000 seconds, twenty times less. So yes, this is the most expensive query on the server, and it is worth our time, even though each execution looks fast.
2Finding the Caller
The numbers in pg_stat_statements tell us what the database does but not why. The next step is to find the code that sends this query, and the call count is the first clue. 48 million calls a day is about 555 per second. Does the business do 555 of anything per second? If not, something calls it far more often than needed.
Three causes are common. An N+1 pattern: the code loads a list of 100 items and then runs this query once per item, often hidden in a JPA lazy-loaded association or a loop calling a repository method. A missing cache: the result changes rarely, like a price list or a feature flag, but every request asks the database again. Polling: a worker asks every 100 ms whether there is new work. To connect the query to a service, application_name per service, SQL comments added by tools like sqlcommenter, or tracing spans around JDBC calls show which endpoint or job is responsible.
6 messages in order. Play them, or step through them one at a time.
Each query is fast; the page makes a hundred of them.
3Is Each Call Efficient?
Before or alongside reducing calls, we check whether each call does more work than it should. The ratio of blocks to rows is a good signal. Our query returns 1 row per call but touches 40 blocks of 8 kB. A good index lookup for one row usually touches 3 to 5 blocks: a few index levels and one table page. 40 suggests the query uses an index on product_id but then filters many rows by another condition, such as a validity date, visiting many table pages to find the one current price.
EXPLAIN (ANALYZE, BUFFERS) on one call with typical parameters confirms it. A composite index such as (product_id, valid_from DESC) would turn it into a direct lookup touching perhaps 4 blocks, cutting the per-call cost severalfold. On 48 million calls, that alone saves hours of database time per day.
4Reducing the Number of Calls
The bigger win is usually fewer calls. For the N+1 pattern, we batch: one query for all products on the page, with = ANY(?) in PostgreSQL or an IN list, or a join that loads lines with their prices. In JPA, a fetch join, an entity graph or Hibernate's batch fetching does the same for associations.
| Change | Effect on calls | Effect per call |
|---|---|---|
| Composite index (product_id, valid_from) | none | 40 blocks -> about 4 |
| Batch with = ANY(?) or a join | 100 per page -> 1 | slightly more rows each |
| Cache rarely changing results | most calls removed | none |
| Replace polling with notifications | from constant to on change | none |
If the data changes rarely, we cache it: an in-process cache with a short time to live, or a shared cache such as Redis, removes most calls entirely. If the caller is polling, we can poll less often, use LISTEN and NOTIFY or a queue, or move the check into the query that already runs, for example by returning the flag with the main result. Each of these can cut calls by ten or a hundred times, which no index can do.
5Measuring the Improvement
pg_stat_statements counters are cumulative since the last reset, so comparing today's total with last week's tells us little. We either reset the statistics before the change, with pg_stat_statements_reset(), which in recent versions can reset a single statement by its queryid, or take snapshots of the view at regular intervals into a table and compare the difference over equal periods of similar traffic.
We then compare calls per hour, mean time and total time before and after deployment. If batching worked, calls drop by about the batch size; if the index worked, mean time and blocks per call drop. Database CPU usage during peak hours confirms the effect on the whole server.
6Follow-up questions
Why not just make the query faster and leave the calls alone?
Because there is a floor on per-call cost: each execution pays network round trip, parsing or plan lookup, locking and result handling, often a few hundred microseconds, regardless of how good the index is. Reducing calls removes all of that, and it also reduces latency for the user, since one round trip replaces a hundred. The best result usually combines both: a good index and far fewer calls.
How do I find the caller if all services use the same database user?
Set application_name in each service's connection string, which appears in pg_stat_activity and can be included in log lines, and add SQL comments with the endpoint or code location, for example with sqlcommenter. Distributed tracing with spans around JDBC calls shows the exact request that issued each query and how many times.
Could caching cause problems here?
Yes, stale data. For prices, serving an old price after a change might be unacceptable, so the time to live must match the business rule, or the cache must be invalidated when prices change. For truly static data, caching is simple and safe.
7Conclusion
In this answer, we saw that 48 million calls at 0.9 ms add up to about 43,000 seconds of database time, more than any slow query, so the statement deserves attention. We found the caller with application_name, SQL comments or tracing, recognised N+1 patterns, missing caches and polling as the usual causes, checked blocks per row for a missing index, reduced calls with batching, caching or folding the check into one query, and measured the effect by resetting or snapshotting pg_stat_statements.
Open with
First I would put the number in perspective: 48 million calls at 0.9 milliseconds is about 43,000 seconds, roughly 12 hours of database time, so even though each call is fast, it is the most expensive statement on the server and worth optimising.
Then, if they want more
Then I would find out why it runs so often, because reducing calls usually beats making each call faster. 48 million a day is over 500 per second, and the usual causes are an N+1 pattern, for example a loop or a lazy association that runs one query per item on a page, a missing cache for data that rarely changes, or a worker polling.
To find the caller I would use application_name per service, SQL comments with sqlcommenter, or tracing. In parallel I would check efficiency per call from pg_stat_statements: rows per call and shared blocks hit per call.
If it returns one row but touches 40 blocks, an index is probably missing or not selective enough, and a composite index could cut that to a few blocks.
The fixes are batching, one query with ANY or IN for the whole page or a join or fetch join in JPA, caching stable results with a sensible time to live, replacing polling with notifications, or folding the check into a query that already runs.
Finally I would measure it properly: reset pg_stat_statements or snapshot it before and after, and compare calls, mean time and total time over similar traffic.
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 "pg_stat_statements shows one query with calls=48,000,000, mean_exec_time=0.9 ms and the...": https://scrivio-interview-library.netlify.app/databases/query-optimization/9673fb2a4b/