Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A dashboard query aggregates 300 million order rows and takes 40 seconds. Product wants it under 1 second with data at most 5 minutes old. Compare a materialized view refreshed every 5 minutes, a summary table updated incrementally, and an external analytics store.

A materialized view refreshed every 5 minutes is the simplest option, but each refresh recomputes all 300 million rows, which at this size can take longer than 5 minutes and loads the primary. An incremental summary table that adds only new rows since a watermark is cheap per run but needs more code and care with late or updated rows. An external analytics store fed by CDC scales furthest and removes load from the primary, at the cost of a pipeline. For most teams, an incremental summary by hour or day plus a small live query for the current bucket is the best fit.

Why this question is asked

This scenario is a real product conversation in miniature: a slow dashboard, a latency target, a freshness target, and three technical options with very different costs. Interviewers ask it to see whether we can do the arithmetic before choosing, and whether we think about growth, operations and the team that will maintain the result. In this answer, we will estimate what each option costs at 300 million rows, look at the incremental design in detail because it is the most common winner, cover the external store, and finish with how to decide and what to monitor.

1Understanding the Targets

The dashboard needs two things. Latency under 1 second means it cannot scan 300 million rows on each page load; it must read a precomputed result of perhaps a few thousand rows. Freshness of at most 5 minutes means the precomputed result must include orders placed up to 5 minutes ago. Every option precomputes; they differ in how much work each update costs and where it runs.

Let us assume the dashboard shows revenue and order counts by day and region for the last two years, that 300 million rows took several years to accumulate, and that about 200,000 new orders arrive per day, roughly 700 every 5 minutes. Those numbers drive the whole decision.

2Option 1: A Materialized View Refreshed Every 5 Minutes

This is a few lines of SQL. The problem is that every refresh recomputes the entire aggregate. The original query takes 40 seconds, but that may be with warm caches; a refresh with CONCURRENTLY also has to diff the result, and under production load it competes with order traffic. Suppose it takes 3 minutes. Then the primary spends 60 percent of the time refreshing a dashboard, and as the table grows, the refresh eventually exceeds the 5-minute interval, refreshes queue up, and freshness is lost. All this work processes 300 million rows to account for 700 new ones.

SQL
CREATE MATERIALIZED VIEW sales_by_day AS
SELECT created_at::date AS day, region, count(*) AS orders, sum(total) AS revenue
FROM orders GROUP BY 1, 2;
CREATE UNIQUE INDEX ON sales_by_day (day, region);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_by_day; -- 2 to 4 minutes, scans all 300 million rows

So it works today but has no headroom. It is a fine choice when the data is small or the freshness target is hours, not here.

3Option 2: An Incremental Summary Table

An incremental summary table stores aggregates per time bucket, here per hour and region, and a job adds only the rows that arrived since the last run. The job remembers a watermark, the point up to which it has processed rows. Each run reads perhaps 700 rows using an index, and upserts a few summary rows. The dashboard reads the summary, which for two years by hour and region is about 17,520 hours times 10 regions, 175,000 small rows, well under a second with an index.

There is a catch with watermarks based on created_at: a transaction that started before the watermark moved but committed after it can be missed. A safer watermark is a monotonically assigned id or an ingestion sequence, and a common extra safety is to reprocess a small overlap, say the last 10 minutes, on every run, which is cheap when the upsert recomputes each touched bucket.

SQL
CREATE TABLE sales_hourly (
bucket timestamptz, region text, orders bigint, revenue numeric,
PRIMARY KEY (bucket, region));
-- Every 5 minutes: recompute the buckets touched in the last 10 minutes
INSERT INTO sales_hourly (bucket, region, orders, revenue)
SELECT date_trunc('hour', created_at), region, count(*), sum(total)
FROM orders
WHERE created_at >= date_trunc('hour', now() - interval '10 minutes')
GROUP BY 1, 2
ON CONFLICT (bucket, region) DO UPDATE
SET orders = EXCLUDED.orders, revenue = EXCLUDED.revenue; -- INSERT 0 20, about 50 ms
Step throughOne run of the incremental job
  1. Read buckets touched since the last runuses an index on created_at
  2. Recompute those bucketsabout 700 rows, not 300 million
  3. Upsert into sales_hourlyON CONFLICT DO UPDATE
  4. Changed old orders since last run?
    YesRecompute their buckets tooNoDone
  5. Record run time and stalenessfor the dashboard and alerts

5 steps in order. Play them, or step through them one at a time.

Each run costs milliseconds because it touches only new and changed data.

Notice that this version recomputes whole buckets instead of adding deltas, which makes it idempotent: running it twice gives the same result. Late updates are the other care point. If an order's total can change or an order can be cancelled days later, those changes must also reach the summary, for example by recording an updated_at and recomputing the buckets of changed orders, or by treating corrections as new events.

4Option 3: An External Analytics Store

The third option moves the problem out of the transactional database. Change data capture, for example Debezium reading the PostgreSQL write-ahead log, streams every committed insert and update into Kafka, and from there into an analytical store such as ClickHouse or a cloud warehouse. These systems store data by column and are built to aggregate billions of rows in well under a second, and ClickHouse can maintain aggregates as rows arrive. End-to-end latency is typically seconds to a minute, inside the 5-minute target.

The benefits are scale and isolation: the primary does no dashboard work at all, and the analytics store handles growth to billions of rows and new questions without new summary tables. The cost is a pipeline with several components to run, monitor and secure, schema changes that must flow through it, and the skills to operate it. For one dashboard, that is a lot; for a company with many analytical needs, it pays for itself.

5Choosing, and the Hybrid That Often Wins

The decision rests on growth, freshness and team skills. If the data grows slowly and the team is small, the incremental summary table is the best value. If many dashboards are coming and the company already runs Kafka, the external store is a strategic investment. The materialized view is only right if the freshness target relaxes to an hour or more.

A hybrid often works best: an incremental summary per hour or per day for everything up to the last complete bucket, plus a small live query for the current bucket, which aggregates at most an hour of orders from the base table using an index. The dashboard unions the two, so the current hour is exact to the second while the expensive history is precomputed. Whatever we pick, we monitor two numbers: the duration of each refresh or job run, so we see it creeping toward the interval, and staleness, the age of the newest data in the result, with an alert above the 5-minute target.

SQL
SELECT bucket, region, orders, revenue FROM sales_hourly
WHERE bucket >= now() - interval '30 days' AND bucket < date_trunc('hour', now())
UNION ALL
SELECT date_trunc('hour', created_at), region, count(*), sum(total)
FROM orders WHERE created_at >= date_trunc('hour', now())
GROUP BY 1, 2; -- about 60 ms in total

6Follow-up questions

Why not just add an index to make the original query fast?

An index helps find a few rows, but this query aggregates hundreds of millions of rows; even an index-only scan must read them all. Precomputing is the only way to answer in under a second without reading the history every time.

How do you backfill the summary table the first time?

Run the aggregate for the history once, bucket by bucket, in batches outside peak hours, ideally on a replica, and then start the incremental job from the point where the backfill ended. Because the job recomputes whole buckets, a small overlap at the boundary is harmless.

7Conclusion

In this answer, we compared three ways to make a 40-second dashboard fast and fresh. A materialized view is simple but recomputes all 300 million rows every 5 minutes and loads the primary. An incremental summary table processes only new and changed rows per run, at the cost of watermark and late-update handling. An external analytics store fed by CDC scales furthest and isolates the primary, at the cost of a pipeline. Often an hourly incremental summary plus a live query for the current hour fits best, and in every case we monitor refresh duration and staleness.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start with the numbers. 300 million rows and maybe 700 new orders every 5 minutes means a full recomputation every 5 minutes does an enormous amount of work to account for very little new data.

Then, if they want more

A materialized view refreshed every 5 minutes is simple, but each refresh rescans everything, it may take minutes on its own, it loads the primary, and as the table grows it will eventually take longer than the interval.

An incremental summary table, say per hour and region, is updated by a job that recomputes only the buckets touched since the last run, with a small overlap so it is idempotent. Each run takes milliseconds and the dashboard reads a small indexed table. The extra work is careful watermarks and handling late changes such as cancellations.

An external store, Debezium CDC into Kafka and then ClickHouse or a warehouse, scales best and removes all load from the primary, but it is a pipeline to build and operate, so it makes sense if more analytics is coming and the team has those skills.

My usual choice would be the hybrid: an hourly incremental summary for history plus a live indexed query for the current hour, unioned in the dashboard. Whatever we choose, I would monitor job duration and staleness and alert when the data is older than 5 minutes.

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.
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 query aggregates 300 million order rows and takes 40 seconds. Product wants...": https://scrivio-interview-library.netlify.app/databases/stored-code/187528dbcb/