Database Sharding
Partition data across databases and examine routing and cross-shard costs.
system design, sharding, partitioningPartition rather than copy
Sharding splits data across independently managed partitions. A shard key and routing rule determine where a record belongs. Unlike replication, sharding primarily divides the data; each shard may itself be replicated for resilience. Choose a key from real query and load patterns, not only record count.
Customer order histories
- Route customer A to shard 1 and customer B to shard 2 using a maintained map.
- A new order for A goes to shard 1, so that customer's history is local there.
- A report across all customers queries both shards and combines results. One extremely active customer can still make shard 1 hot.
See the reasoning
Route and combine
Compare a customer-local lookup with an all-customer report. This is a prepared demonstration, not live code execution.
Route customers
- Shard 1Customer A ordersCurrent focus
- Shard 2Customer B orders
A routing map assigns each customer to a shard.
Time-series records
Records may be partitioned by time range, making retention and time-bounded queries simpler. However, the current time range can receive most writes, creating a hot shard. Combining time with another partitioning key may spread load but makes some queries fan out. Late-arriving records and time-zone or boundary rules also need an explicit policy.
Trade-offs and failure
Cross-shard joins and transactions are harder, and one unavailable shard can make a query partial or fail. Define whether partial results are acceptable. Rebalancing needs a migration protocol, correct routing updates and verification while writes continue. Back up, monitor and recover each shard; do not shard before simpler scaling options no longer meet the workload.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
