Implementing Database Sharding

1. Understanding Sharding Concepts

TermDefinition
ShardIndependent partition of data on its own node
Shard keyColumn(s) used to route rows
Routing layerMaps key → shard (app, proxy, or built-in)
ReshardingMoving data to add/remove shards
Co-locationRelated rows on same shard for local joins

2. Designing Shard Keys

CriteriaDetail
High cardinalityMany distinct values for even spread
Even accessAvoid hotspots
Used in most queriesAvoid scatter-gather
ImmutableChanging key requires data move
Examplesuser_id, tenant_id, account_id

3. Implementing Range-Based Sharding

ProCon
Efficient range queriesHotspots on recent ranges
Easy split/mergeSequential keys cluster on one shard
Used inHBase, MongoDB, CockroachDB (default)

4. Implementing Hash-Based Sharding

ProCon
Even distributionNo range queries on shard key
Random spreadAdding shards re-hashes everything (use consistent hashing)
Used inCassandra, DynamoDB, Citus

5. Implementing Directory-Based Sharding

AspectDetail
MechanismLookup table maps key → shard
FlexiblePer-tenant placement, custom rules
CostExtra lookup per request; cache aggressively
SPoF riskReplicate the directory

6. Managing Cross-Shard Queries

PatternDetail
Scatter-gatherQuery all shards, merge results
CostLatency = slowest shard; CPU n× higher
MitigationsCo-locate joined data, denormalize, async aggregation
Distributed JOINHash redistribute (broadcast small tables)

7. Handling Shard Rebalancing

MethodDetail
Pre-splitCreate many empty shards up front
Online moveStream changes during data copy
Consistent hashingAdd/remove only moves a fraction
Dual-write windowWrite to old + new during transition

8. Implementing Consistent Hashing

        N1
       /  \
   key3    key1
     |      |
    N3 --- N2
     |      |
   key4    key2

Adding N4 redistributes only the keys
between N3 and the new node — not all keys.
        
ConceptDetail
Hash ringNodes + keys placed on ring; key → next clockwise node
Virtual nodesMany points per physical node — even distribution
Used inCassandra, DynamoDB, Riak, Memcached clients

9. Managing Shard Failover

StrategyDetail
Replicas per shardSync or async; promote on failure
Health checksDetect node loss quickly
Quorum reads/writesTolerate node loss without ack delay
BackpressureReroute traffic away from degraded shard

10. Designing for Shard Scalability

PrincipleDetail
Plan for 10× growthPre-split to avoid emergency re-shard
Tenant per shard (multi-tenant)Isolate noisy neighbors
Idempotent writesResharding tolerates retries
Avoid cross-shard txsUse sagas or design for local-only writes