Playground: the consistent hashing ringPlayground: consistent hashing ring
24 keys live on the ring, each owned by the next node clockwise. Add or remove a node and count how many keys move. Then flip to naive modulo and see why nobody uses it.24 keys ring pe hain, har ek ka malik clockwise agla node. Node add ya remove karo aur gino kitni keys move hoti hain. Phir naive modulo pe flip karo aur dekho kyun koi use nahi karta.
When one database is not enough
Read scaling is solved by replicas; the wall that remains is writes and storage. One primary accepts every write, and one machine holds every byte. When writes exceed what one primary can absorb, or the dataset outgrows one disk (or one backup window), you split the data across machines: sharding. Each shard is a full database holding a subset; the app knows which shard owns which rows.
The shard key: the decision you cannot undo cheaply
What do you split by? A good shard key does two things: spreads load evenly and keeps common queries inside one shard. Common choices:
- user_id: all of a user's data on one shard; user-centric queries are single-shard and fast. Risk: the celebrity problem (one user with 100M followers is one very hot shard).
- time: recent data on the newest shard. Great for time-series retention (drop old shards instead of deleting rows), but all of today's writes hit one shard: a permanent hotspot.
- geography: users sharded by region; low latency and data-residency compliance, uneven distribution.
Changing the shard key later means rewriting every row. Choose like you mean it.
Routing: hash mod N vs consistent hashing
hash(key) % N: perfectly even, but adding one server changes N and remaps almost every key: a full data migration. Consistent hashing: keys and servers both sit on a ring; each key belongs to the next server clockwise. Adding a server moves only ~1/N of keys. Add virtual nodes (each physical server claims many ring positions) and the spread smooths out. DynamoDB, Cassandra and CDNs all use versions of this.
What sharding costs (say this part out loud)
- Joins die: data that joins now lives on different machines; you join in application code or denormalize.
- Transactions die (mostly): cross-shard atomicity needs two-phase commit, which is slow and fragile; most teams design to avoid it.
- Cross-shard queries: "top posts globally" now means querying all shards and merging (scatter-gather): slow and expensive.
- Resharding and ops: N databases to back up, monitor, migrate and rebalance.
Hence the rule: shard last. First indexes, caching, read replicas, vertical scale, archiving old data. Most systems never need sharding; some need it for one table only.
The celebrity problem deserves its own paragraph
Even perfect hash distribution fails when load is not uniform: one key gets 30% of traffic and melts its shard. Fixes: split hot keys with a suffix (key becomes key:0..key:99, spread across shards, merge on read), cache aggressively, or special-case known hot entities. Naming this problem before the interviewer does is free points.
Worked example: sharding a social app's posts
500M users, 2 TB of posts/year. Shard by user_id with consistent hashing, 64 logical shards to start (over-shard logically so physical rebalancing is cheap). Feed reads hit one shard per author. Celebrities (>1M followers): their posts are pulled at read time instead of pushed, so no single write fans out onto one shard 100M times.
Common interview traps
- Sharding as the first scaling step.
- A shard key that forces every common query across all shards.
- No plan for hotspots, resharding, or cross-shard queries.
Interview Q&A
Q: Your DB is at 80% disk and writes are climbing. Walk me through it.
A: First confirm what is growing (one table? logs?), then: archive/delete old data, add read replicas if it is read load, vertical scale as a bridge, and only then shard, choosing the key from the access patterns. Sharding is the last resort with the highest long-term cost.
Q: How do you generate unique IDs across shards?
A: Auto-increment breaks across machines. Options: UUIDs (no coordination, long and unordered), Twitter-Snowflake-style IDs (timestamp + machine id + sequence, 64-bit, roughly time-ordered, no coordination), or a dedicated ID service.
Jab ek database kaafi nahi hota
Read scaling replicas se solve hoti hai; jo deewar bachti hai wo hai writes aur storage. Ek primary har write leta hai, aur ek machine har byte rakhti hai. Jab writes ek primary ki capacity paar kar jaayen, ya dataset ek disk (ya ek backup window) se bada ho jaaye, to data ko machines mein baantte hain: sharding. Har shard ek poora database hai jo subset rakhta hai; app jaanti hai kaunsi row kis shard ki hai.
Shard key: wo decision jo sasti mein undo nahi hota
Kis basis par baanto? Accha shard key do cheezein karta hai: load barabar failata hai aur common queries ko ek shard ke andar rakhta hai. Common choices:
- user_id: user ka saara data ek shard par; user-centric queries single-shard aur fast. Risk: celebrity problem (100M followers wala user = ek bahut hot shard).
- time: naya data sabse naye shard par. Time-series retention ke liye badhiya (purane rows delete karne ki jagah purane shard drop karo), par aaj ki saari writes ek shard par: permanent hotspot.
- geography: region se users shard; low latency aur data-residency compliance, par distribution uneven.
Shard key baad mein badalna matlab har row rewrite. Soch samajh kar choose karo.
Routing: hash mod N vs consistent hashing
hash(key) % N: bilkul even, par ek server add karte hi N badalta hai aur almost har key remap: poori data migration. Consistent hashing: keys aur servers dono ring par; har key clockwise agle server ki. Ek server add karne par sirf ~1/N keys move hoti hain. Virtual nodes (har physical server kayi ring positions) se spread aur smooth. DynamoDB, Cassandra aur CDNs sab isi ke versions use karte hain.
Sharding ki keemat (ye hissa zor se bolna)
- Joins mar jaate hain: join hone wala data ab alag machines par; application code mein join karo ya denormalize karo.
- Transactions mar jaate hain (mostly): cross-shard atomicity ke liye two-phase commit chahiye, jo slow aur fragile hai; zyadatar teams isse avoid karne ka design karte hain.
- Cross-shard queries: "globally top posts" ab saare shards query + merge (scatter-gather): slow aur mehenga.
- Resharding aur ops: N databases ko backup, monitor, migrate aur rebalance karna.
Isliye rule: shard last. Pehle indexes, caching, read replicas, vertical scale, purana data archive. Zyadatar systems ko sharding kabhi chahiye hi nahi; kuch ko sirf ek table ke liye chahiye.
Celebrity problem ka apna paragraph
Perfect hash distribution bhi fail hoti hai jab load uniform na ho: ek key par 30% traffic aur uska shard melt. Fixes: hot keys ko suffix se split karo (key ban jaati hai key:0..key:99, shards par faili, read par merge), aggressively cache karo, ya known hot entities ko special-case karo. Interviewer se pehle ye problem name karna free points hai.
Worked example: social app ke posts shard karna
500M users, 2 TB posts/saal. user_id se shard, consistent hashing, shuruaat mein 64 logical shards (logically over-shard karo taaki physical rebalancing sasti ho). Feed reads har author ke liye ek shard. Celebrities (>1M followers): unke posts push nahi, read time par pull hote hain, taaki ek write ek shard par 100M baar fan-out na ho.
Common interview traps
- Pehla scaling step hi sharding.
- Aisa shard key jo har common query ko saare shards par bhej de.
- Hotspots, resharding ya cross-shard queries ka koi plan nahi.
Interview Q&A
Q: DB 80% disk par hai aur writes badh rahi hain. Batao kya karoge.
A: Pehle confirm karo kya badh raha hai (ek table? logs?), phir: purana data archive/delete, read load hai to read replicas, bridge ke liye vertical scale, aur sirf tab shard, key access patterns se choose karke. Sharding last resort hai jiska long-term cost sabse zyada hai.
Q: Shards ke across unique IDs kaise banate ho?
A: Auto-increment machines ke across toot jaata hai. Options: UUIDs (no coordination, lambe aur unordered), Twitter-Snowflake-style IDs (timestamp + machine id + sequence, 64-bit, roughly time-ordered, no coordination), ya dedicated ID service.