Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A query that joins a 2 billion row fact table with a 100 million row table runs well on PostgreSQL in one region but badly on a sharded setup. What does distribution change about join strategies?

On one server, a join reads both tables from the same memory and disk. On a sharded setup, rows that must be joined may live on different machines, so the join needs data movement: joins on the shard key, where matching rows sit on the same shard, run locally and in parallel, while other joins must broadcast one table to every shard or repartition both tables by the join key over the network. Broadcasting a small table is cheap, but repartitioning a 2 billion and a 100 million row table is very expensive in network and memory. So we choose shard keys that co-locate the most important joins, such as tenant_id on every table, move some queries to an analytical engine, and read the distributed plan to see where data moves.

Why this question is asked

Sharding is usually introduced to scale writes and storage, and it works: each shard holds part of the data and handles part of the load. What surprises teams is that queries which were fast on one server become slow or impossible, and joins are the main reason. Interviewers ask this scenario to see whether we understand what distribution does to join strategies and whether we design the data layout around the joins that matter. In this answer, we will recap how sharding places rows, see the three ways a distributed join can run, put numbers on our tables, and then look at shard key design, analytical engines and how to read a distributed plan.

1A Quick Recap: Where Rows Live After Sharding

Sharding splits a table across several database nodes. A shard key, a column such as customer_id or tenant_id, decides where each row goes, typically by hashing the key and mapping hash ranges to shards. A coordinator, or the application, routes each query to the shards that hold the relevant rows. A query that targets one key goes to one shard; a query over many keys runs on all shards in parallel and the coordinator combines the results.

For a join, what matters is whether the rows to be joined are on the same shard. On the single server, the planner could pick any join algorithm because all rows were local. After sharding, the location of the rows comes first, and the algorithm second.

2Three Ways a Distributed Join Can Run

If both tables are sharded on the join key, using the same hashing and shard count, matching rows are guaranteed to be on the same shard. Each shard joins its own part locally, in parallel, and nothing crosses the network except results. This is a co-located join, and it is as fast as the single-server join divided across the nodes.

If one table is small, we can copy it to every shard, either permanently as a reference table, or for the duration of the query as a broadcast. Each shard then joins its part of the big table with the full copy of the small one. The cost is sending the small table once to each node.

If neither applies, the system must repartition: re-hash one or both tables by the join key and send each row to the shard responsible for that key, so that matching rows meet. This moves a large part of both tables across the network, needs memory or temp space at the receiving end, and is usually the slowest plan by far.

Distributed join strategies
StrategyWhen it appliesData moved
Co-locatedBoth tables sharded on the join keyOnly results
Broadcast / referenceOne table small enough to copy to all shardsSmall table x shard count
Repartition one sideOne table already sharded on the join keyThe other table, mostly
Repartition bothNeither sharded on the join keyMost of both tables

3Putting Numbers on Our Query

Our fact table has 2 billion rows, say order_lines, and the other table has 100 million rows, say products. On one PostgreSQL server, a hash join builds a hash on the filtered products, or uses an index, and reads order_lines once, all locally. Now suppose the cluster has 32 shards and order_lines is sharded by customer_id while products is sharded by product_id. The join is on product_id, so the rows do not line up.

SQL
-- The query
SELECT p.category, sum(l.amount)
FROM order_lines l JOIN products p ON p.id = l.product_id
WHERE l.created_at >= DATE '2026-01-01'
GROUP BY p.category;
-- Broadcast products: 100M rows x 32 shards = 3.2 billion rows sent (at ~100 bytes, about 320 GB)
-- Repartition order_lines by product_id: most of 2B rows moved (about 200 GB), plus memory on receivers
-- Co-located (both by product_id, or products as a reference table): almost nothing moved

Neither non-local option is attractive. Broadcasting 100 million rows to every shard is too much to do per query, and repartitioning the fact table is worse. That is why the query that ran well in one region runs badly here: the plan now spends most of its time moving data. If we only needed products' id and category, a narrow broadcast of two columns is smaller, but it is still heavy for an interactive query.

4Choosing Shard Keys for the Important Joins

The lasting fix is in the data layout. We list the most important queries, by frequency and business value, and choose shard keys so that their joins are co-located. In a multi-tenant system this is usually simple: put tenant_id on every table, include it in primary keys and foreign keys, and shard every table by tenant_id. Then every join within a tenant is local, which covers almost all application queries.

Tables that are needed by all tenants and are not too large, such as countries, currencies or a shared catalogue of moderate size, become reference tables, replicated to every node, so joins to them are local too. A 100 million row products table is large for a reference table, but if it is per tenant, it can be sharded by tenant_id along with order_lines. What we cannot do is co-locate every possible join: a table can only be sharded one way, so we choose for the critical queries and accept that others will move data or run elsewhere.

Step throughA layout that keeps joins local
  1. Coordinatorroutes by tenant_id; combines results
  2. Shard 1 .. 32: orders, order_lines, productsall sharded by tenant_id, joins local
  3. Reference tables on every nodecountries, currencies, small shared lists
  4. Analytical storecross-tenant reports, fed by CDC

4 layers, from the top down. Step through them one at a time.

5Analytical Queries and Reading Distributed Plans

Some queries do not belong on the OLTP shards at all. A report that joins all order lines of all tenants with all products by category is analytical: it scans billions of rows across every shard. Systems built for that, column stores and warehouses with massively parallel execution, are designed to shuffle data efficiently and compress columns, and they can be fed by change data capture from the shards. Moving such reports there protects the OLTP cluster and usually makes the report faster.

Whatever the system, we read its plan to see data movement. In Citus, a distributed PostgreSQL extension, EXPLAIN shows a Custom Scan (Citus Adaptive) node with a task count, one task per shard for a co-located query, and repartition joins appear as separate steps that only run if repartition joins are enabled (citus.enable_repartition_joins; check your version). Other systems show exchange, shuffle, broadcast or redistribute operators. The question to ask of every plan is the same: which operators move rows between nodes, and how many.

Java
EXPLAIN SELECT ... FROM order_lines l JOIN products p ON p.tenant_id = l.tenant_id AND p.id = l.product_id
WHERE l.tenant_id = 42;
-- Custom Scan (Citus Adaptive)
-- Task Count: 1 <- routed to the one shard that holds tenant 42
-- -> Task
-- -> Hash Join (local on the worker)

6Follow-up questions

What happens if the shard key is customer_id but most joins are on order_id?

Then joins between orders and order_lines are only co-located if order_lines also carries customer_id and is sharded by it, joining on both columns. That is the usual trick: denormalise the shard key into child tables, so every join can include it. Without it, every order-to-lines join may need repartitioning, which defeats the purpose of sharding.

Is broadcasting a table per query ever a good idea?

Yes, when the table, after filtering and selecting only the needed columns, is small, say a few thousand to a few hundred thousand rows. The cost is that size times the number of shards, which is cheap in that range. It becomes a problem when the broadcast side is large or the query runs very often, in which case a reference table or a different shard key is better.

How do you decide the shard count?

Start from data size and growth per shard, write throughput, and how the system rebalances. Many systems recommend more logical shards than nodes, for example 32 or 64 shards on 4 nodes, so that adding nodes later means moving whole shards rather than resharding. Joins do not change much with shard count when they are co-located, but repartition costs grow with it.

7Conclusion

In this answer, we saw that sharding puts joined rows on different machines, so joins become co-located when both tables share the shard key, broadcast when one table is small, or repartitioned when neither applies, and that repartitioning billions of rows dominates the cost. We chose shard keys such as tenant_id on every table to keep important joins local, used reference tables for small shared data, moved cross-tenant analytics to an analytical engine, and read distributed plans to find data movement.

What to say in the interviewAbout 100 seconds aloud

Open with

On a single server every row is local, so the planner just picks a hash, merge or nested loop join. After sharding, the first question is where the matching rows live.

Then, if they want more

If both tables are sharded on the join key, the join is co-located: each shard joins its own data in parallel and only results move, which is great.

If one table is small, it can be broadcast to every shard or kept as a reference table on every node, so the join is still local, at the cost of copying it.

Otherwise the system has to repartition, re-hash one or both tables by the join key and ship rows across the network so that matches meet, and with a 2 billion row fact table and a 100 million row table that means hundreds of gigabytes of transfer plus memory on the receiving nodes.

Even broadcasting 100 million rows to 32 shards is 3.2 billion rows sent. That is why it was fast in one region and slow sharded. My fix is mainly design.

I would pick the shard key from the most important joins, in a multi-tenant system usually tenant_id on every table, included in keys and join conditions, so almost all joins are local. Small shared tables become reference tables. Cross-tenant reports that need the big join should run in an analytical engine fed by CDC rather than on the OLTP shards.

And I would read the distributed plan, for example Citus's task count and repartition steps, to see exactly where data moves.

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 query that joins a 2 billion row fact table with a 100 million row table runs well on...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/ae74a7f9da/