Quick revision
The short answer
I would not run a grouped ranking over live orders on every page view. Instead I would keep a small read model of sales per city and seller, either updated incrementally by a consumer of order events, in Redis sorted sets or a summary table indexed by (city_id, sales DESC), or recomputed by a job every 30 to 60 seconds, and serve the widget from it. The window, such as the last 7 days, uses bucketed counters, and refunds, fraud removals and cache warm-up after failover are part of the design.
What to remember
In this answer, we replaced a top N per group query on every page view with a small read model. Order events update counters per city and seller, in Redis sorted sets with ZINCRBY and a top 10 read by rank, or in a summary table indexed by (city_id, sales DESC); a simpler first version recomputes the summary every 30 to 60 seconds from hourly aggregates. We defined the window precisely, using hourly buckets so a sliding 7 day window can expire old sales, and planned for refunds and fraud removals as negative, deduplicated events, and for cache warm-up and fallback after a failover.
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 not run a grouped ranking over live orders on every page view. Instead I would keep a small read model of sales per city and seller, either updated incrementally by a consumer of order events, in Redis sorted sets or a summary table indexed by (city_id, sales DESC), or recomputed by a job every 30 to 60 seconds, and serve the widget from it. The window, such as the last 7 days, uses bucketed counters, and refunds, fraud removals and cache warm-up after failover are part of the design.
Why this question is asked
A home page widget is a read problem disguised as a query problem. The team's plan, running a top N per group query on every page view, is correct SQL and a bad architecture: the home page may get thousands of views per second, each one asking the database to aggregate and rank recent orders for a city. Interviewers ask this design question to see whether we separate how data is written from how it is read, and whether we can pick between incremental and batch designs on cost and correctness. In this answer, we will estimate the cost of the original plan, design an incremental read model, compare it with a scheduled recompute, define the time window properly, and handle refunds and failover.
1Why the Per-View Query Does Not Scale
The query the team has in mind looks like this: sum the last 7 days of orders per city and seller, rank sellers within each city, and keep the top 10 for the visitor's city. Even with good indexes, each page view has to read every order of the last 7 days in that city. At 2,000 orders per second, a week is about 1.2 billion orders across 3,000 cities, roughly 400,000 per average city and far more for the largest. Reading and grouping hundreds of thousands of rows per page view, at hundreds of page views per second, would need more CPU than the orders database has, and it would compete with the 2,000 writes per second the business actually depends on.
Notice the mismatch. The answer changes slowly, at most once a minute by the requirement, and it is tiny: 10 rows per city, 30,000 rows in total. Recomputing it from raw orders on every view is doing the same work thousands of times.
2An Incremental Read Model
The alternative is to maintain the answer as orders arrive. A consumer reads order events, for example from Kafka, and for each order adds its amount to a counter for that city and seller. Redis sorted sets fit this well: a sorted set keeps members ordered by a score, ZINCRBY adds to a member's score, and reading the top 10 is a single range command.
6 messages in order. Play them, or step through them one at a time.
Writes update small counters; reads never touch the orders table.
2,000 increments per second is light work for Redis, and the page view becomes one read of 10 members, typically under a millisecond. The ZRANGE ... REV form replaced ZREVRANGE in Redis 6.2; check your version. A summary table in the database, sales_by_city_seller(city_id, seller_id, hour, sales) with an index on (city_id, sales DESC) for the rolled-up totals, follows the same idea for teams that prefer to keep everything in SQL, with an application cache in front.
3The Simpler Alternative: Recompute Every Minute
An incremental pipeline has moving parts: event delivery, idempotent consumers, bucket expiry. A scheduled job is easier to reason about. Every 30 to 60 seconds, it computes the top 10 per city from a pre-aggregated hourly table and replaces the results in a small table that the widget reads.
| Design | Freshness | Moving parts | Best when |
|---|---|---|---|
| Query per page view | real time | few | never at this load |
| Job every minute | up to 60 s | job, aggregate table | first version, simple ops |
| Event counters in Redis | seconds | consumer, buckets, warm-up | high traffic, tighter freshness |
The ranking query still runs, but once a minute on hourly aggregates instead of hundreds of times a second on raw orders. The cost is staleness of up to a minute, which the requirement allows, and a small amount of extra write work for the hourly upsert. Note that a busy seller's hourly row becomes a hot row under 2,000 writes per second; if that shows up, the job can aggregate from the orders of the last minute instead. For most teams I would start here, and move to the event-driven counters only if the minute job becomes too slow or freshness must improve.
4Defining the Time Window
"Top sellers" needs a precise definition before anyone writes code: today, the last 24 hours, or the last 7 days? A calendar window like today is easy: one counter per city per day, reset at midnight in the city's time zone. A sliding window like the last 7 days is harder, because sales must leave the window as they age. A single running counter cannot forget old sales, so we keep counters per bucket, here per hour, and the 7 day total is the sum of the latest 168 buckets. Old buckets simply expire. The bucket size sets the precision: hourly buckets mean the window edge moves in one hour steps, which is invisible on a home page.
5Refunds, Fraud and Failover
Sales do not only go up. A refund or a fraud removal must lower the seller's total, so the consumer handles OrderRefunded events by adding a negative amount to the bucket of the original sale's hour, if that bucket is still inside the window. Because events can be delivered twice, the consumer records processed event ids, with a short-lived Redis key per event id, and skips repeats, so a redelivered refund is not subtracted twice.
Redis is a cache here, not the source of truth. After a failover or a restart without persistence, the counters may be empty or stale, and the widget would show nonsense. So we keep a rebuild path: a job that recomputes the hourly buckets for the last 7 days from the orders database, or from the sales_hourly table, and the widget falls back to the last good top_sellers table or hides itself until the rebuild completes. A nightly comparison between Redis totals and the database catches drift from missed events.
6Follow-up questions
How would you handle refunds in the incremental counter design?
Treat the refund as an event with a negative amount and apply it to the hourly bucket of the original sale, if that bucket is still within the window, with deduplication by event id so redelivery does not subtract twice. If the original sale has already left the window, there is nothing to correct for the widget.
Why not cache the result of the per-view query for a minute?
That helps, but the first view after each expiry for each of 3,000 cities still runs the heavy query, and many expire at once. Precomputing on a schedule gives the same freshness without the stampede and keeps the work predictable.
How do you make the scheduled job safe if it runs long?
Use a lock so only one instance runs at a time, for example a PostgreSQL advisory lock or ShedLock in Spring, replace the results in one transaction, and alert if a run takes longer than its interval.
7Conclusion
In this answer, we replaced a top N per group query on every page view with a small read model. Order events update counters per city and seller, in Redis sorted sets with ZINCRBY and a top 10 read by rank, or in a summary table indexed by (city_id, sales DESC); a simpler first version recomputes the summary every 30 to 60 seconds from hourly aggregates. We defined the window precisely, using hourly buckets so a sliding 7 day window can expire old sales, and planned for refunds and fraud removals as negative, deduplicated events, and for cache warm-up and fallback after a failover.
Open with
I would not run a grouped ranking over live orders per page view. Over seven days that is hundreds of thousands of orders per city per request, at home page traffic, on the same database taking 2,000 writes a second, while the answer is only ten rows per city and may be up to a minute old.
Then, if they want more
So I would build a read model. My first version is simple: the write path upserts sales into an hourly aggregate per city and seller, and a job every 30 to 60 seconds ranks the last 168 hours with ROW_NUMBER per city and replaces a small top sellers table in one transaction. The widget reads ten rows by index.
If traffic or freshness needs grow, I would move to event-driven counters: a consumer of order events does ZINCRBY on a Redis sorted set per city per hour bucket, every minute a ZUNIONSTORE builds the seven day set, and the page reads the top ten with ZRANGE REV.
Defining the window matters: a sliding seven day window needs bucketed counters so old sales expire. Refunds and fraud removals are negative events applied to the original sale's bucket, deduplicated by event id.
And since Redis is a cache, I need a rebuild job from the database, a fallback to the last good table after a failover, and a nightly drift check.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Redis 6
- 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 "A product team wants a "top 10 sellers per city" widget on the home page, updated within...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/0797bc9eb4/