Quick revision
The short answer
First stop the damage: move the reports to a read replica and cap the reporting role with statement_timeout and work_mem. Then make the reports cheap: pre-aggregated daily summary tables refreshed incrementally, monthly partitioning with a BRIN index on created_at so queries prune old data, and in the medium term a warehouse fed by CDC (for example Debezium) for BI tools, while agreeing freshness with finance and handling replica conflicts.
What to remember
In this answer, we saw that big reports hurt checkout's p99 by competing for disk, cache and memory. We protected checkout first with a reporting replica and role limits, then reduced the data read with incremental daily summaries, monthly partitions with pruning and a BRIN index, and moved BI to a warehouse fed by CDC, keeping in mind that replica queries can be cancelled and that hot_standby_feedback trades that for bloat on the primary.
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 stop the damage: move the reports to a read replica and cap the reporting role with statement_timeout and work_mem. Then make the reports cheap: pre-aggregated daily summary tables refreshed incrementally, monthly partitioning with a BRIN index on created_at so queries prune old data, and in the medium term a warehouse fed by CDC (for example Debezium) for BI tools, while agreeing freshness with finance and handling replica conflicts.
Why this question is asked
Analytics on the production database is how most companies start, and it works until the data grows. At 1.2 billion orders, a monthly report reads tens of gigabytes, competes with checkout for CPU, memory and disk, and pushes useful pages out of the cache. Interviewers ask this as a scenario because the order of the changes matters as much as the changes: we must protect customers this week while building something better over months. In this answer, we will look at why the reports hurt checkout, then go through the immediate protection, pre-aggregation, partitioning and BRIN, the move to a warehouse, and the caveats of read replicas.
1Why Reports Hurt Checkout
A report that scans months of orders reads millions of pages. Those reads compete with checkout for disk bandwidth and CPU, and every page they pull into shared buffers evicts a page that checkout queries wanted, so checkout suddenly needs disk reads it did not need before. Large sorts and hash aggregates use work_mem per operation, and several parallel workers per query multiply that, so memory pressure grows too.
That is why p99 latency rises rather than the average: most checkout requests still hit the cache, but the unlucky ones wait for disk behind the report. The fix is either to run the reports elsewhere or to make them read far less data, and in the end we do both.
2Immediately: Separate and Limit
The fastest relief is a streaming read replica dedicated to reporting, with its own CPU, memory and cache, and pointing the BI tools and finance jobs at it. In the same week we give reporting its own database role with limits, so a runaway query cannot hurt anyone for long.
These settings apply to every session of that role, on the primary and on the replica. They do not make reports faster; they make the damage bounded and visible while we fix the real cause.
3Next: Pre-Aggregate What Reports Actually Read
Most daily, weekly and monthly reports ask the same questions: revenue and order counts by day, country, channel and product category. If we store those totals once, a monthly report reads about 30 days times a few hundred dimension combinations, a few thousand rows, instead of 40 million orders.
A materialized view is the simpler option, but REFRESH MATERIALIZED VIEW recomputes everything, which on 1.2 billion rows is exactly the work we want to avoid. A summary table refreshed for recent days only is incremental. The window should cover late changes, such as refunds or status updates, and the business zone if reports are by local day.
4Partitioning and BRIN for the Raw Data
Some reports still need raw orders. Declarative partitioning by month splits orders into one table per month, and a query with a created_at range only touches the partitions it needs, which is called partition pruning. Old partitions can be detached and archived cheaply, and vacuum works on smaller tables.
Converting an existing 1.2 billion row table to a partitioned one is a project, not a statement: typically we create the partitioned table, route new writes to it and move history in batches, or attach the old table as one large partition with a check constraint. Inside each partition, a BRIN index on created_at is ideal for append-only time data. BRIN, block range index, stores only the minimum and maximum value per range of pages, so it is tiny, often a few megabytes where a B-tree would be tens of gigabytes, and works because rows arrive roughly in time order.
- Week 1: reporting replica, role limitscheckout protected
- Weeks 2 to 6: daily summary tablesmost reports read thousands of rows
- Months 2 to 4: monthly partitions, BRINraw queries prune old data
- Months 3 to 9: CDC to a warehouseBI tools move off PostgreSQL
- Retire direct production access for reports
5 steps in order. Play them, or step through them one at a time.
5Medium Term: A Warehouse Fed by CDC
PostgreSQL is a row store built for transactions. Columnar warehouses, such as BigQuery, Snowflake, Redshift or ClickHouse, read only the columns a query needs and compress them heavily, so scanning a year of orders by three columns is fast and cheap. We feed them with change data capture, which reads the write-ahead log, for example with Debezium into Kafka and on into the warehouse, so there is no extra load from nightly bulk extracts and data arrives within minutes.
Then BI tools and analysts point at the warehouse, the summary tables can move there too, and the PostgreSQL replica serves only reports that truly need up-to-the-second data.
6Read Replica Caveats
A hot standby, a replica that accepts read queries, replays changes from the primary. When the primary vacuums away row versions that a long report on the replica still needs, replay and query conflict. PostgreSQL waits up to max_standby_streaming_delay, 30 seconds by default, and then cancels the query with a conflict error. Turning on hot_standby_feedback makes the replica tell the primary which rows it still needs, so they are not removed and the report survives.
But there is a catch: the primary then keeps dead rows longer, which causes bloat and slower queries on the primary itself, the very thing we wanted to protect. So we agree freshness with finance, for example a dedicated reporting replica with a large max_standby_streaming_delay that may lag minutes behind, and keep hot_standby_feedback off or watch bloat closely.
7Follow-up questions
What does hot_standby_feedback trade off?
It trades bloat on the primary for fewer query cancellations on the replica. With it on, the replica reports the oldest transaction it still needs, and the primary's vacuum keeps the row versions that transaction might read. Long reports stop being cancelled, but dead rows accumulate on the primary for as long as those reports run, tables and indexes grow, and checkout queries can slow down. With it off, the primary vacuums freely and the replica cancels conflicting queries after max_standby_streaming_delay.
Why not just add more indexes for the reports?
Reports that scan months of data read a large share of the table, and a B-tree index does not make reading 40 million rows cheap. Extra indexes also slow every insert into orders, which is checkout's hot path. Summaries and partitions reduce the data read; indexes do not.
How would you keep finance confident during the move?
Run the old and new report paths in parallel for a month or two, compare the totals daily with an automatic check, and switch each report only when they agree, with finance signing off.
8Conclusion
In this answer, we saw that big reports hurt checkout's p99 by competing for disk, cache and memory. We protected checkout first with a reporting replica and role limits, then reduced the data read with incremental daily summaries, monthly partitions with pruning and a BRIN index, and moved BI to a warehouse fed by CDC, keeping in mind that replica queries can be cancelled and that hot_standby_feedback trades that for bloat on the primary.
Open with
I would go in order of risk. This week, protect checkout: move all reporting to a dedicated read replica, and give reporting its own role with statement_timeout, a work_mem cap, limited parallel workers and a small connection pool.
Then, if they want more
That bounds the damage immediately. Next, make reports read less. Most daily, weekly and monthly reports ask for totals by day and a few dimensions, so I would build summary tables, refreshed hourly for recent days with an upsert, which turn a scan of tens of millions of rows into a few thousand.
A materialized view would need full refreshes, which is the cost we are trying to avoid. Then I would partition orders by month with declarative partitioning so range queries prune old partitions, migrating in batches, and add a BRIN index on created_at, which is tiny and works well because orders are appended in time order.
Over the following months I would stream changes with CDC, for example Debezium, into a columnar warehouse and move BI tools there.
I would also be clear about replica limits: long queries can be cancelled by replay conflicts, and hot_standby_feedback avoids that at the cost of bloat on the primary, so I would agree acceptable freshness with finance rather than chase zero lag.
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, The SQL Language
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 "Teams run daily, weekly and monthly report queries with date bucketing directly against...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/929eddeb52/