System Design blueprint · Social & Fintech
Database sharding & replication
Splitting one huge table across machines by a shard key, with a replica behind every shard.
- Steps
- 6
- Subjective questions
- 32
- Objective questions
- 32
The problem and the outcome
Problem: One database can no longer hold the rows or absorb the writes.
Outcome: Data and write load split evenly across machines, each with a standby.
Architecture
How it works, step by step
- Every query carries the shard key, here user_id.
- The router hashes the key (consistent hashing) to pick exactly one shard, so data spreads evenly.
- Each shard holds a slice of the rows and takes only its share of the writes.
- Every shard has replicas for read scaling and failover.
- Adding a shard with consistent hashing moves only a fraction of the keys, not all of them.
- Cross-shard joins are expensive, so pick a key that keeps related rows together.
Tech stack
- PostgreSQL with Citus, or Vitess for MySQL
- MongoDB / Cassandra (built-in sharding)
- Consistent hashing
- Replica per shard
- Shard-map service
Key design decisions
- Choose a shard key that matches the main access pattern (often user_id), so most queries touch one shard.
- Consistent hashing or many small virtual shards, so adding a machine moves only a fraction of the data.
- A replica behind every shard for failover and read scaling.
Common mistakes
- A low-cardinality or skewed key (country, created_date) that creates hot shards.
- Cross-shard joins and transactions that become slow and complex.
- Sharding before it is needed, when indexes, caching or a bigger machine would do.
What to measure
- Data size and QPS per shard (skew)
- Share of queries that fan out to all shards
- Rebalancing time and replica lag
Most-asked interview questions
Subjective questions 32
1How do you choose a good shard key?Asked almost every time
High cardinality, an even spread of data and traffic, and present in most queries so they hit a single shard. user_id or tenant_id are common. Avoid monotonically increasing keys with range sharding (all new writes hit one shard) and keys with a few huge values.
2What is the difference between sharding and replication?Asked almost every time
Sharding splits the data, so each machine holds a different part and write capacity grows. Replication copies the same data to several machines for availability and read scaling. Production systems usually do both: every shard has replicas.
3What are the main sharding strategies?Asked almost every time
Range-based (by key ranges such as dates or IDs; good for range queries, risks hot spots), hash-based (spreads load evenly, poor for ranges), directory-based (a lookup service maps keys to shards; flexible but adds a dependency), and geo-based (by region for latency and data residency).
4How do you handle queries that need data from many shards?Asked almost every time
Avoid them on hot paths by choosing a shard key that matches the main access pattern. When needed, scatter-gather in parallel and merge results, maintain denormalised or secondary indexes (global indexes or a search engine), or precompute aggregates.
5How do you reshard without downtime?Asked almost every time
Use many logical shards mapped to fewer physical nodes so you move logical shards rather than rehashing; or double-write to old and new layouts, backfill, verify, switch reads, then stop old writes. Consistent hashing limits how much data moves.
6How does consistent hashing help when adding a node?Very often asked
Keys and nodes sit on a hash ring, and each key belongs to the next node clockwise. Adding a node takes over only the keys between it and its neighbour, about 1/N of the data, instead of reshuffling everything as hash mod N would. Virtual nodes even out the load.
7What is a hot shard and how do you fix it?Very often asked
A shard receiving far more traffic than others, often due to a celebrity key or sequential IDs in range sharding. Fix by splitting the shard, salting hot keys across shards, caching hot data, or choosing a higher-cardinality shard key.
8How do you keep IDs unique across shards?Very often asked
Use globally unique IDs like UUIDv7, Snowflake-style IDs (timestamp, machine ID and sequence) or ID ranges per shard, rather than per-database auto-increment, which would collide.
9How do transactions work across shards?Very often asked
Cross-shard transactions need two-phase commit or a distributed database, which is slower and complex. Prefer designs where a transaction touches one shard (shard by tenant or user) and use sagas for multi-shard workflows.
10Synchronous vs. asynchronous replication: what are the trade-offs?Very often asked
Synchronous replication waits for replicas before confirming, so no data is lost on failover but writes are slower. Asynchronous replication is faster but recent writes can be lost if the primary fails. Semi-synchronous waits for at least one replica.
11How does failover work for a sharded, replicated database?Very often asked
Each shard has a primary and replicas. A failure detector or consensus system promotes a replica, updates routing (via a proxy or service discovery), and fences the old primary so it cannot accept writes. Clients retry briefly during the switch.
12What does a query router or proxy do in a sharded system?Very often asked
It receives queries, determines which shard holds the data from the shard key, forwards the query, and merges results for multi-shard queries, hiding sharding from the application (Vitess, Citus, MongoDB mongos).
13How does sharding by tenant work for SaaS?Very often asked
Each tenant's data lives on one shard, so queries and transactions stay local and noisy tenants can be moved to dedicated shards. Very large tenants may need their own shards or further splitting.
14How would you choose a shard key for a social app's posts table?Very often asked
Choose the key that matches the main access path and spreads load: author ID keeps a user's posts together for profile pages, while a hash of post ID spreads writes evenly. Check that hot users will not create hot shards and that the common queries hit one shard.
15How do you enforce a unique constraint, such as email, across shards?Very often asked
Keep a separate lookup table or service keyed by the unique value that maps to the owning record, insert into it first with its own uniqueness guarantee, then write the record. Alternatively shard by that value so uniqueness is checked within one shard.
16What is replication lag and how do you deal with it?Often asked
The delay before a replica applies the primary's changes. Route reads that need fresh data to the primary (or use session stickiness after a write), monitor lag, and avoid replicas for consistency-critical reads.
17What is the difference between leader-follower and multi-leader replication?Often asked
Leader-follower has one writable primary per shard, which is simple. Multi-leader accepts writes in several places (often regions), lowering write latency but requiring conflict resolution for concurrent updates.
18How does quorum replication work?Often asked
In leaderless systems like Cassandra, a write goes to N replicas and succeeds after W acknowledgements; reads query R replicas. If R + W > N, reads overlap with the latest write, giving tunable consistency.
19When should you not shard?Often asked
When vertical scaling, read replicas, caching, archiving old data, better indexes or partitioning within one database still work. Sharding adds lasting operational and application complexity.
20What is table partitioning and how does it differ from sharding?Often asked
Partitioning splits a table into parts within one database server (for example by month), helping maintenance and query pruning. Sharding spreads data across servers to scale capacity.
21How do you back up a sharded database consistently?Often asked
Back up each shard with point-in-time recovery, coordinate snapshots when cross-shard consistency matters, test restores regularly and keep the shard map versioned with backups.
22How do you run schema migrations on many shards?Often asked
Automate them with a tool that applies the same migration to every shard, make migrations backward compatible, roll out gradually and track which shards are on which version.
23What is consistent hashing with virtual nodes?Often asked
Each physical node owns many points on the hash ring, so load spreads evenly and adding or removing a node moves small pieces of data from many nodes rather than a big chunk from one.
24How do you paginate results merged from many shards?Often asked
Query each shard for its top N by the sort key, merge them in the router, and return the global top N with a cursor holding the last sort value. Avoid OFFSET pagination, which forces every shard to read and skip more rows as pages go deeper.
25What is a secondary index in a sharded database and why is it tricky?Often asked
An index on a column other than the shard key. A local index lives on each shard, so a lookup must query all shards; a global index is itself sharded by the indexed value, so lookups are fast but writes update two places and can drift without careful consistency.
26How do you move a single large tenant to its own shard?Often asked
Copy the tenant's data to the new shard while capturing changes, replay the change stream until caught up, briefly pause writes for that tenant, switch the directory entry to the new shard, resume, then delete the old copy after verification.
27How do you handle analytics queries on a sharded OLTP database?Often asked
Do not run them on the shards. Stream changes (CDC) into a warehouse or OLAP store such as BigQuery, Snowflake or ClickHouse, where full scans and joins across all data are cheap, and keep the OLTP shards for short transactional queries.
28How do you monitor a sharded system?Sometimes asked
Track per-shard QPS, latency, storage, CPU, replication lag and error rates, and watch for imbalance between shards so hot spots are found early.
29Which databases provide automatic sharding?Sometimes asked
Distributed SQL databases like CockroachDB, YugabyteDB, Spanner and TiDB, MongoDB with sharded clusters, Cassandra and DynamoDB partition automatically; Citus and Vitess add sharding to PostgreSQL and MySQL.
30How do you choose the number of shards?Sometimes asked
Estimate data size and throughput growth for several years, divide by what one node handles comfortably, and create more logical shards than nodes so you can rebalance without resharding.
31What is read-your-writes consistency?Sometimes asked
A guarantee that after a user writes, their own subsequent reads see that write, even if other users see it later. Implement by reading from the primary for a short time after a write, or tracking replication positions.
32What is a split-brain in a replicated database and how is it prevented?Sometimes asked
Two nodes both believe they are primary and accept conflicting writes, usually after a network partition. It is prevented with a consensus or quorum-based election, fencing tokens or STONITH so the old primary cannot write, and clients that follow the elected leader.
Objective questions 32
1Why is hash(key) mod N a problem when N changes?Asked almost every time
Why: Changing N changes the result for most keys, so nearly all data must move.
2Which strategy spreads load evenly but makes range queries hard?Asked almost every time
Why: Neighbouring keys land on different shards.
3What should a shard key match?Asked almost every time
Why: Keeps hot queries on one shard.
4Why use many logical shards on fewer nodes?Asked almost every time
Why: Growth later means moving shards, not rehashing.
5Which query is most expensive in a database sharded by user_id?Very often asked
Why: A query without the shard key must fan out to every shard and merge the results.
6What causes a hot shard with range sharding on IDs?Very often asked
Why: The newest range takes all writes.
7Which IDs are safe across shards?Very often asked
Why: Globally unique without coordination.
8Asynchronous replication risks…Very often asked
Why: Replicas may lag behind.
9What prevents an old primary from writing after failover?Very often asked
Why: Fencing avoids a split-brain cluster.
10Which tool adds sharding to MySQL?Very often asked
Why: Used at YouTube scale.
11Sharding by tenant keeps…Very often asked
Why: Local queries and transactions.
12A unique email across shards is usually enforced with…Very often asked
Why: One place must own the uniqueness decision.
13Deep OFFSET pagination across shards is costly because…Very often asked
Why: Cursor pagination with the last sort value avoids it.
14What does a replica behind each shard provide?Often asked
Why: The replica holds a copy of the shard's data, ready to take over or serve reads.
15In quorum systems, R + W > N gives…Often asked
Why: This gives tunable consistency.
16Partitioning differs from sharding because it…Often asked
Why: Sharding spreads across servers.
17What do virtual nodes improve in consistent hashing?Often asked
Why: Each node owns many ring points.
18Multi-leader replication requires…Often asked
Why: Concurrent writes can conflict.
19When should sharding be avoided?Often asked
Why: It adds lasting complexity.
20How should cross-shard workflows be handled?Often asked
Why: Each step stays local.
21Which component routes queries to the right shard?Often asked
Why: Hides sharding from the app.
22Read-your-writes means…Often asked
Why: Often read from the primary after writing.
23A local secondary index means lookups by that column…Often asked
Why: Each shard indexes only its own rows.
24Where should cross-shard analytics run?Often asked
Why: Analytics scans would slow transactional traffic.
25Moving a tenant to a new shard ends with…Often asked
Why: The directory points requests at the tenant's new home.
26Split-brain happens when…Often asked
Why: Conflicting writes then diverge the data.
27Which database shards automatically?Sometimes asked
Why: It is a distributed SQL database.
28What should be monitored per shard?Sometimes asked
Why: Detect imbalance early.
29How should migrations run across shards?Sometimes asked
Why: Track versions per shard.
30Semi-synchronous replication waits for…Sometimes asked
Why: A middle ground between sync and async.
31Directory-based sharding uses…Sometimes asked
Why: Flexible but adds a dependency.
32Sharding posts by author ID makes which query fast?Sometimes asked
Why: All of one author's posts live on one shard.
Track your progress through every blueprint in your dashboard.
Start learning