Quick revision
The short answer
Neither query contains the shard key, so the router cannot pick one shard and must send it to every shard and combine the answers, which is called scatter-gather. count(*) becomes a sum of per-shard counts, and ORDER BY created_at LIMIT 20 needs the top 20 from every shard followed by a merge, so cost grows with the shard count and latency follows the slowest shard. In practice such queries are answered from maintained counters, a warehouse fed by change data capture, or a global secondary index, and APIs are designed so frequent queries include the shard key.
What to remember
In this answer, we saw that queries without the shard key must be scattered to every shard and gathered. count(*) becomes a sum of per-shard counts, and ORDER BY ... LIMIT 20 needs the top 20 from every shard and a merge, so work grows with shard count, latency follows the slowest shard, and one failing shard affects the whole query. These queries are usually answered with maintained counters, a warehouse fed by CDC, or a global secondary index, and APIs are designed so frequent queries carry the shard key.
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.
Neither query contains the shard key, so the router cannot pick one shard and must send it to every shard and combine the answers, which is called scatter-gather. count(*) becomes a sum of per-shard counts, and ORDER BY created_at LIMIT 20 needs the top 20 from every shard followed by a merge, so cost grows with the shard count and latency follows the slowest shard. In practice such queries are answered from maintained counters, a warehouse fed by change data capture, or a global secondary index, and APIs are designed so frequent queries include the shard key.
Why this question is asked
On a single database, SELECT count(*) and ORDER BY ... LIMIT 20 are among the first queries anyone writes. After sharding, they become some of the most expensive ones, and teams are often surprised that the dashboard which used to load instantly now times out. Interviewers ask this to see whether we understand how a sharded system executes a query without its shard key, and what the usual remedies are. In this answer, we will see why the shard key matters for routing, follow both queries through scatter-gather, look at latency and failure effects, and then go through the common ways these queries are answered instead.
1A Quick Recap: Routing Needs the Shard Key
In a sharded system, each row lives on one shard chosen from its shard key, for example customer_id. When a query says WHERE customer_id = 42, the router computes the shard and sends the query there alone. When a query does not mention the shard key, as in WHERE status = 'NEW', the matching rows could be on any shard, so the router has no choice: it sends the query to all of them. This is scatter-gather, scatter the query to every shard, then gather and combine the results.
2How the Two Queries Run Across Shards
For count(*), each shard counts its own NEW orders, and the router adds the numbers. That part is cheap to combine, only one number per shard, but every shard still runs the count, and if the status column has no index on some shard, each count may scan a lot of rows.
ORDER BY created_at LIMIT 20 is more interesting. The newest 20 orders overall could all come from one shard, or be spread over several, so the router cannot take 20 rows from one shard and stop. Each shard must return its own newest 20, and the router merges the 16 lists of 20 by created_at and keeps the first 20. With 16 shards, 320 rows come back to produce 20. Deep pages are worse: page 50, OFFSET 1000 LIMIT 20, needs each shard's top 1,020 rows, so 16,320 rows are fetched to return 20, which is why keyset pagination with a cursor matters even more in sharded systems.
7 messages in order. Play them, or step through them one at a time.
Work and network traffic grow with the number of shards, not with the result size.
3Latency, Load and Failure
Three properties make scatter-gather costly at scale. Latency is set by the slowest shard: if each shard answers in 5 ms at the median but 1 percent of answers take 200 ms, then a query that waits for 64 shards hits at least one slow answer about half the time, so its typical latency approaches the tail latency of a single shard. Load multiplies: one dashboard refresh becomes 64 queries, and a page refreshed by 100 users every few seconds keeps every shard busy. And one failing shard fails the whole query, or forces us to return a partial answer that must be marked as partial, because a count that silently misses a shard is simply wrong.
4How These Queries Are Usually Answered
The first remedy is maintained aggregates. If the business needs the number of NEW orders, keep a counter per status, updated when an order changes status, either in each shard with a cheap scatter-gather of 64 small rows, or in a separate store fed by events. For high write rates, the counter is split into several rows or kept in a store such as Redis, and the exact number is reconciled periodically.
The second remedy is a separate analytics store. Reports, ad-hoc analysis and 'all orders sorted by date' across the business go to a data warehouse or lakehouse, fed by change data capture (CDC) from every shard, with a freshness of seconds to minutes. Analytical databases are built for scans and aggregates across everything, and the shards stay free for customer traffic.
The third remedy is a global secondary index: a separate table, keyed by the attribute we query, that points to the shard key. For example, an index of status and created_at to order_id and customer_id lets 'newest 20 NEW orders' read one index, then fetch the 20 orders from their shards. Some distributed databases maintain such indexes for us; otherwise we build one from events.
| Approach | Good for | Cost |
|---|---|---|
| Scatter-gather | Rare queries, small shard counts | Load and latency grow with shards |
| Maintained counters | Known counts such as orders per status | Update on every change; reconcile |
| Warehouse fed by CDC | Reports, analytics, sorted exports | Seconds to minutes behind |
| Global secondary index | Lookups and top-N by a non-shard key | Extra store, eventual consistency |
| Shard key in the API | Frequent user-facing queries | Design discipline up front |
5Design APIs So Frequent Queries Include the Shard Key
The cheapest cross-shard query is the one we never send. Most user-facing queries naturally belong to one owner: 'my orders', 'orders of this store', 'this tenant's dashboard'. If the API path or the request context always carries that owner, such as GET /customers/{customerId}/orders?status=NEW, every frequent query routes to one shard. Cross-cutting views are then reserved for internal tools and reports, which use the analytics store. Reviewing new endpoints for 'does this query include the shard key?' is a simple habit that prevents most of these problems.
6Follow-up questions
Can we cache scatter-gather results instead?
For slowly changing aggregates such as a dashboard total, caching the result for 30 seconds can cut load by orders of magnitude. It does not fix latency for the first request or failure handling, and it is not suitable for results that must be current.
How does keyset pagination work across shards?
The client sends the last created_at and id it saw. Each shard returns its next 20 rows after that cursor, using an index on (created_at, id), and the router merges and keeps 20. Each page then costs the same, unlike OFFSET, where each shard must skip ever more rows.
Are approximate counts acceptable?
Often, yes, for dashboards. A sum of per-shard estimates, or a counter updated asynchronously, is good enough to show '18.4k new orders'. Financial or billing numbers need exact, reconciled figures from the warehouse or a ledger.
7Conclusion
In this answer, we saw that queries without the shard key must be scattered to every shard and gathered. count(*) becomes a sum of per-shard counts, and ORDER BY ... LIMIT 20 needs the top 20 from every shard and a merge, so work grows with shard count, latency follows the slowest shard, and one failing shard affects the whole query. These queries are usually answered with maintained counters, a warehouse fed by CDC, or a global secondary index, and APIs are designed so frequent queries carry the shard key.
Open with
Both queries lack the shard key, so the router can't pick a shard and has to scatter the query to every shard and gather the results. For count, each shard counts its own NEW orders and the router sums them; combining is cheap but every shard does the work.
Then, if they want more
For ORDER BY created_at LIMIT 20, the newest 20 could be on any shard, so each shard returns its own top 20 and the router merges, say, 16 lists of 20 and keeps 20. Deeper pages get much worse with OFFSET, so keyset pagination matters.
The costs grow with the number of shards: latency is set by the slowest shard, so with 64 shards you almost always hit someone's tail latency, load multiplies because one request becomes 64 queries, and if one shard is down you either fail or return a partial result that has to be marked as partial.
In practice we avoid running these on the shards. For known counts I keep maintained counters, updated on status changes and reconciled periodically. For reports and sorted exports across everything, I use a warehouse fed by CDC from every shard, accepting some minutes of lag.
For lookups or top-N by a non-shard attribute, a global secondary index maps that attribute to the shard key. And the most important part is API design: frequent user-facing queries should carry the shard key, like a customer or tenant id in the path, so they always route to one shard.
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 "In a sharded system, why are queries like SELECT count(*) FROM orders WHERE status =...": https://scrivio-interview-library.netlify.app/databases/partitioning-and-sharding/cd2f0536bb/