When your data or write volume gets too large for one database, you shard it: split the rows across several machines, each owning a slice. Data modeling matters here because the shard key decides which queries stay cheap. A good key keeps related data together; a bad one turns everyday queries into fan-outs across every shard.
Shard by your primary access pattern#
Pick the shard key from the query you run most often. The database hashes that key to decide which shard owns each row:
- If most reads ask for one student's data (their enrollments, progress and reviews), shard by
student_id. Everything about a student sits on one shard, so the query touches one database. - If most reads scan recent activity across every student, such as the last hour of lesson completions, consider partitioning by time ranges instead. The catch is that the newest range gets all the writes.
Avoid cross-shard queries#
Any shard key makes some query fan out. Say you've sharded by student_id and a course page needs every review of that course. Those reviews were written by students on many shards, so you query each and merge the results (scatter-gather). That's slower and more complex. Designs usually work around it, for example by keeping a second copy of reviews keyed by course_id or caching the course page, rather than fanning out on every read.
Choose carefully#
Since the key decides which queries stay on one shard, it's hard to undo. The shard key is often effectively permanent: it shapes every query, and changing it means migrating live data. A good key:
- has high cardinality (many distinct values),
- spreads load evenly (no single hot value),
- matches the
WHEREclause of most queries, and - co-locates data that's read together.
For hash vs range partitioning, hotspots and consistent hashing, see Scaling Writes.
Key takeaways#
- Shard by the access pattern you run most often.
- Keep related data on the same shard so common queries touch one database.
- Cross-shard queries mean scatter-gather. Design to avoid them on hot paths.
- Treat the shard key as a long-term decision.