Video in progress

Strong Middle 🏗️ System design

The data is sharded by `user_id`. Now you need to search by another field and join across shards. What do you do?

The main routes: a global index table for the secondary key (email -> user_id), moving search to a separate system (Elasticsearch), copying small reference tables to every shard, or, if needed, querying all shards and merging the results.

📖 Answer

After sharding, the SQL freedom of "WHERE on any column, any JOIN" is gone. For every new query you have to ask "which shard does this go to?".

Case by case:

Search by a secondary key. Login is by email, while the shard is by user_id. A separate email_index(email PK, user_id) table — which is itself sharded by email. Login: first get the user_id from the index, then go to the right shard. The problem is writing to two places: at signup the index was written, the user wasn't. So: first the index (reserving uniqueness), then the user, and if it fails, clean up or repair through an outbox.

Complex search (by name, category, price range) — don't do it in a sharded DB. Through CDC into Elasticsearch/OpenSearch, search there, get IDs as the result, then fetch the full data from the shard.

Joins with reference data (countries, currencies, categories). They're small and rarely change — a copy on every shard. The join stays inside the shard.

Joins of two big tables (orders and products). Often denormalization: copy the product name and price into the order. That's the right thing anyway — the price on an order should be the price on that day.

Scatter-gather: a parallel query to all shards, merging the results in the application. It's acceptable for rarely used admin queries; with ORDER BY ... LIMIT 20, you take 20 from each shard, merge, and keep 20 again. Don't put it in the main user flow — the slowest shard sets the latency for everyone.