SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Cross-Shard Joins

When the data you need lives on different shards: scatter-gather, and ways to avoid it.

⏱ 12 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A cross-shard join combines rows from tables whose data lives on different shards. On one database a join is routine. Across shards it becomes slow, costly and complicated.

  • The query has no single home, so a coordinator must ask many shards and then merge the answers (scatter-gather).
  • Data has to travel across the network, and there is no single optimizer to plan the best join.
  • The best fix is to avoid them: keep related rows together, copy small tables everywhere, or precompute the answer.

02Concept: What is it?

On one database, orders JOIN users is easy. The database has both tables on its disk, picks an index, and returns the result. After sharding, the users table might be split by user_id while orders is split by order_id. Now the orders of one user sit on many shards, and the user row sits on yet another.

There is no machine that holds everything the query needs. Something has to gather the pieces. That something is usually a coordinator (a router, a proxy, or your own application code).

Local join vs cross-shard join
Co-located
🧭Router
↓1 shard
🗄️Shard 2user + their orders
Scattered
🧭Coordinator
↓ask all, then merge
🗄️S1
🗄️S2
🗄️S3
🗄️S4
When the data is together, one shard does the work. When it is not, the data must travel.
🧠Joins and transactions share the same problem
Anything that touches several shards at once (a join, a foreign key check, a multi-row transaction) needs coordination between machines. Transactions across shards need a protocol such as Two-Phase Commit, which is slow and can block. The cheapest cross-shard operation is the one you design away.

03Real-Life Example

🍵Two Filing Cabinets in Two Offices
A company keeps customer cards in an office in London and the matching order forms in an office in Paris. To prepare one customer's invoice, a clerk phones Paris, waits for the forms, and then looks up the card in London. To find "the ten biggest customers", both offices must send everything to one desk, because neither office alone knows the totals. The fix: keep each customer's card and orders in the same office, or keep a photocopy of the small customer-name list in both.
Two offices
Cross-shard join
Customer cards in London, orders in Paris
users and orders on different shards
The clerk who phones both offices
The coordinator
Waiting for the forms by courier
Network transfer and extra latency
Both offices send everything to one desk
Scatter-gather and merge
Keeping a customer's cards and forms together
Co-locating with the same shard key
A photocopied name list in each office
Replicating a small table to every shard
A monthly summary sheet
A precomputed or denormalized result
Four ways around the problem
🤝Co-locatesame shard key
📋Copy small tablesto every shard
🧾Precomputedenormalize
🧠Join in the appbatched lookups
Pick the cheapest one that fits the query.

04Why Do We Need It?

🐌Latency adds up
A query is as slow as the slowest shard, plus the merge, plus any second round of lookups.
📡Network cost
Shipping many rows between machines is slower and more expensive than reading local disk.
🧮No global optimizer
Each shard plans its own part. Nobody plans the best order for the whole join.
🔗No cross-shard foreign keys
Most sharded systems cannot enforce a foreign key between shards, so integrity moves into your code.
⚛️Hard transactions
Changing rows on two shards at once needs a distributed protocol such as 2PC.
🔥Load multiplies
One user query becomes N shard queries, so total load grows with the number of shards.
Sharding gives you scale for queries that carry the key. It charges you for every query that does not.

05Where Do We Use It?

🛒Orders and customers
Shard both by customer_id so a customer's history is one local join.
📖Reference tables
Countries, currencies and product categories are small and rarely change, so copy them to every shard.
📊Reports
Questions across all customers belong in a warehouse or search index fed by the shards, not on the live shards.
🧩Marketplaces
Seller and buyer views of the same order need two copies, or a precomputed view.
💬Social feeds
Build each user's feed ahead of time, instead of joining posts and follows on the fly.
🧰Sharded databases
Vitess, Citus and CockroachDB all do scatter-gather for you, and all advise co-location where you can.

06Types / Parts / How It Works

How a cross-shard query runs

ApproachHow it worksCost
Scatter-gatherSend the query to every shard, then merge, sort and limit at the coordinatorLoad and latency grow with the number of shards
Two-step lookupFetch the main rows, then fetch the related rows by key from the other shardsAn extra round trip for each step
Broadcast joinSend the small table to every shard so each can join locallyFine for small tables, wasteful for big ones
Shuffle joinRe-send rows between shards so matching keys meet on the same machineHeavy network traffic, used by analytic engines
Application-side joinYour code fetches both sides and joins in memorySimple, but you own the batching and correctness

How to avoid it

TechniqueIdeaPrice
Co-locateGive related tables the same shard key (orders and order_items by customer_id)One big customer can make one shard large
Replicate small tablesKeep a full copy of reference data on every shardUpdates must reach every copy
DenormalizeStore the needed user name inside each order rowCopies can go stale, and writes touch more data
MaterializePrecompute the joined result and refresh it on a scheduleResults are slightly old
Analytics storeStream changes (CDC) into a warehouse or search index for cross-entity questionsEventually consistent, one more system
Feeding an analytics store
🗄️Shard 1
🗄️Shard 2
🗄️Shard 3
→↓change stream
🏛️Warehouse / searchjoins across everything
→↓reports
📊Dashboards
Live, sharded Analytics copy
Live shards stay simple. Cross-shard questions run elsewhere.
VisualizerOrder by order_id or by user_id: what does the join cost?Run both queries with each sharding choice. Then copy the users table to every shard and see which cost goes away and which stays.
Orders are sharded by
Query
4 shards: bright border = this shard has to do work for the query. Users are sharded by user_id. Orders by order_id.
Shard 1
Users:
Dia, Hana, Lea
Orders: 7
of Chen: 0
Shard 2
Users:
Ana, Eli, Ivo
Orders: 8
of Chen: 0
Shard 3
Users:
Ben, Fay, Jun
Orders: 8
of Chen: 2
Shard 4
Users:
Chen, Gus, Kai
Orders: 7
of Chen: 0
  1. Orders are spread by order_id, so Chen's 2 orders sit on shards: 1:0, 2:0, 3:2, 4:0.
  2. The coordinator asks ALL 4 shards for the orders and gets 2 rows back.
  3. Round 2: it fetches the user row from shard 4 and joins in memory.
Shards touched
4 of 4
Rows shipped
3
co-located: 2
Network rounds
2
one after the other
Orders are sharded by order_id, so one user's orders are scattered. The query has no shard key to aim at and becomes a scatter-gather: ask every shard, then a second trip to fetch the user row.

A tiny model: 12 users and 30 orders made by a fixed rule, spread over 4 shards. "Rows shipped" counts rows sent from a shard to the coordinator (and the lookup rows of a second round). With millions of rows the gap between the two layouts becomes enormous. The data is invented for teaching.

07How to Use It / Steps / Implementation

Designing so that joins stay local

  1. 1
    Choose one entity as the root
    Often a customer, tenant or account. Make its id the shard key for the whole family of tables that belong to it.
  2. 2
    Shard children by the parent's key
    Orders, order items and invoices all carry customer_id and use it as their shard key. A customer's data stays on one shard.
  3. 3
    Copy the small, stable tables
    Countries, plans, product types: replicate to every shard. Make sure an update goes to all copies.
  4. 4
    Denormalize what you read most
    Store the display name inside the order if the page always needs both. Decide how stale it may be, and how to repair it.
  5. 5
    Push cross-entity questions to another system
    Feed a warehouse or search index using change capture, and run top-N and reports there.
  6. 6
    If you must join, batch
    Fetch the main rows, collect the keys, and ask each shard once for all of them. Never do one lookup per row.
  7. 7
    Limit and sort at the shards
    Ask each shard for its top K only, then merge the K x N rows. Do not pull everything to the coordinator.
💡Top-N across shards
A global top 3 must lie inside the union of each shard's own top 3, but only if each user's data is on one shard. If a user is split over shards, partial totals must be added first, and you cannot prune early.
⚠️Do not fake a foreign key
Without a cross-shard foreign key, nothing stops an order from pointing at a deleted user. Handle it in code (soft deletes, background checks) and in your tests.

08Key Terms to Know

TermMeaning in easy words
Cross-shard joinA join between rows that live on different shards
CoordinatorThe router or proxy that sends a query to shards and merges the answers
Scatter-gatherAsk every shard, then collect and merge the answers
Co-locationKeeping related rows on the same shard by using the same shard key
Broadcast tableA small table copied in full to every shard
ShuffleRe-sending rows across the network so matching keys meet
DenormalizationStoring a copy of related data inside a row to avoid a join
Materialized viewA saved result of a heavy query, refreshed from time to time
Distributed transactionA change that must succeed or fail together on several shards
Partial aggregateA sub-total computed on one shard, which must be added to the others
Change data captureReading a database's change log to feed other systems

09Pros, Cons and Trade-offs

✅ Pros
  • Co-location makes common joins local and fast
  • Small broadcast tables make lookups free
  • Denormalized rows answer a page in one read
  • Moving reports to a warehouse protects live traffic
  • Scatter-gather is still available when you really need it
⚠️ Cons
  • Cross-shard joins are slow and costly
  • Co-location ties your design to one entity
  • Copies and denormalized fields can go stale
  • Foreign keys across shards are not enforced
  • Every new query shape needs a plan

Trade-offs

ChoiceWe gainWe lose
Co-locate by parent keyLocal joins and local transactionsUneven shards if one parent is huge
Replicate a small tableNo lookup costUpdates to many copies and a short stale window
DenormalizeOne read per pageMore storage and write work, and copies can drift
Join in the applicationFull control and simple infrastructureMore code, and the app must batch well
Warehouse for cross-entity queriesLive shards stay simpleResults lag behind and one more system to run
Scatter-gatherWorks for any queryCost grows with the shard count

10Common Problems and Mistakes

Common mistakes

  1. Sharding tables by different keys. Orders by order_id and users by user_id make the most common join cross-shard.
  2. One lookup per row. Fetching each user in a loop turns one query into hundreds of round trips.
  3. Pulling everything to the coordinator. Sorting and limiting should happen on the shards first.
  4. Trusting a stale copy. A denormalized name or a replicated table can be out of date. Decide how stale is fine.
  5. Missing referential checks. Orphan rows appear when no foreign key can be enforced across shards.
  6. Running reports on the live shards. A big scatter-gather query slows every user.
  7. Assuming a distributed transaction is free. Two-Phase Commit across shards is slow and can block.

Things to watch

📈Fan-out
Track how many shards each query touches. A rising number means cost is rising.
🐢Tail latency
A scatter-gather query waits for its slowest shard. One slow shard slows everyone.
🧱Big result merges
Merging many large results uses coordinator memory. Always limit.
🧹Drift
Compare copies with the source regularly and repair differences.

11Real-World Examples

🏢Multi-tenant SaaS
Everything for one tenant is on one shard, so almost all queries are local.
🧰Vitess-style routers
A routing layer sends single-shard queries to one shard and does scatter-gather for the rest.
🧭Reference tables
Sharding extensions often have a way to mark a table as replicated to every node.
🔎Search for cross-entity queries
Product search spans all sellers, so it runs on a search index, not the order shards.
🏛️Warehouses
Company-wide reports run on a warehouse fed by change capture.
📱Feeds
Home timelines are built ahead of time, instead of joining at read time.
📝Note
Which joins a sharded database can do, and how well, differs a lot between products. Check what your database pushes down to the shards.
Mini case: invoice page for one customer
📱Invoice pagecustomer 42
→↓customer_id
🧭Router
→↓one shard
🗄️Shard 2customer + orders + items
With co-location the page is one local query.

12Related Topics to Read Next

Sharding→

The reason cross-shard queries exist at all.

Shard Keys, Hot Shards and Resharding→

The shard key decides which joins stay local.

Denormalization→

Copy data on purpose to avoid the join.

Materialized Views→

Save the joined result and refresh it.

Two-Phase Commit (2PC)→

How a change across shards can succeed or fail together.

Change Data Capture (CDC)→

Feed an analytics store from the live shards.

OLTP vs OLAP→

Why cross-entity questions belong on an analytics system.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Problem: rows to join live on different shards, so data must travel.
  • ✔Scatter-gather: ask all shards, merge at the coordinator. Cost grows with shards.
  • ✔Best fix: co-locate related tables with the same shard key.
  • ✔Small tables: copy them to every shard (broadcast).
  • ✔Hot read paths: denormalize or materialize the answer.
  • ✔Big questions: run them on a warehouse fed by change capture.
  • ✔If you must join: batch the lookups, and limit and sort on the shards first.
  • ✔One line: “Design your keys so the questions you ask often never leave one shard.”
← Previous
Shard Keys, Hot Shards and Resharding
Next →
Backups, RPO, RTO and Disaster Recovery