Data Partitioning (Sharding)

When a dataset is too big for a single machine, we split it up.

This is called Partitioning (or Sharding).

The goal is to distribute the data so that every node handles just a small piece of the total load.


1. Hash-Based Partitioning

We use a hash function on a key (like user_id) to determine which node gets the data.

How it works

Pros

Cons


2. Range-Based Partitioning

We split data based on sorted ranges of keys (like letters A-Z or IDs 1-1000).

How it works

Pros

Cons


Comparison Summary

Feature Hash-Based Range-Based
Data Balance Excellent (Random) Risk of Hotspots
Query Type Point Lookups (ID=1) Range Scans (ID > 10)
Complexity Simple Requires indexing/metadata
Example Cassandra, DynamoDB HBase, MongoDB

Visual Concept

graph TD
    subgraph "Hash Based"
        H[Hash Mapper] --> N1[Node 1: id=1, 4]
        H --> N2[Node 2: id=2, 5]
        H --> N3[Node 3: id=3, 6]
    end

    subgraph "Range Based"
        R[Range Mapper] --> NR1[Node A: 1-100]
        R --> NR2[Node B: 101-200]
        R --> NR3[Node C: 201-300]
    end

Key Takeaways

Always pick a Shard Key that is permanent and used in almost every query. A bad shard key is the #1 cause of slow databases at scale.