Reading preferences
Concept

Database Sharding

Partition data across databases and examine routing and cross-shard costs.

system design, sharding, partitioning

Partition 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

  1. Route customer A to shard 1 and customer B to shard 2 using a maintained map.
  2. A new order for A goes to shard 1, so that customer's history is local there.
  3. 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

Two illustrative shards
  1. Shard 1Customer A ordersCurrent focus
  2. 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.

1. What determines the shard for an order in this example?
2. Can hashing a customer ID eliminate every hotspot?
3. What makes an all-customer report harder?
4. What needs planning during resharding?

References and further reading