Introduction to data partitioning
easy 25 minData partitioning splits one large set of data into smaller parts by a rule, so that each part is easier to store, search and maintain.
See it run
Split one big table by a rule, then watch which questions get cheaper and which do not.
Operations
Split one database
From one busy database to three shards, with user_id as the key.
Step 1 of 5
Single database
- Database load
- 40%
Simple but limited
12 rows in one database. Simple, and good enough for a long time.
Step 1: Single database
def shard_for(key, shards): if isinstance(key, str): key = stable_hash(key) return shards[key % len(shards)]def insert(row): shard_for(row["user_id"], shards).add(row)def count_all(): return sum(s.count() for s in shards)- Parts touched
- 1 of 3
- Needs the key
- Yes
- One database
- everything in one place
Say the rule out loud: key, remainder, shard. If you cannot say it in one breath, it is too complicated.
In the real world
The same introduction to data partitioning doing real jobs. Pick one and step through it.
Shards by country work until one country grows.
Step 1 of 4
Launch
- Shard 0
- 30%
- Shard 1
- 32%
- Shard 2
- 28%
Even
Three countries of similar size, one per shard.
Step 1: Launch
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Sharding too early
majorA slow query without an index is slow on every shard. You now have the old problem and several new ones.
Wrongshards = split(db, 8) # 200 GBRightadd_index(slow_query)# shard when one machine is fullRange key on a timestamp
criticalEvery new row has the newest time, so one shard takes all writes.
Wrongshard = shard_by_month(created_at)Rightshard = shards[user_id % n]# keep created_at as the sort orderA hash that changes
criticalPython text hashes differ between processes by default. Two servers would look for one user on two shards.
Wrongshard = hash(email) % nRightdigest = sha256(email.encode()).digest()shard = int.from_bytes(digest[:8], "big") % nTreating key 0 as missing
minorZero is a valid id, but many languages treat it as empty.
Wrongif not key: raise ValueError("missing")Rightif key is None: raise ValueError("missing")
Interview tips
How to explain it
- Split by a rule, each row in one part.
- Queries with the key touch one part.
- Queries without it touch all parts.
Memory trick: SHARD
- Split the data, Horizontal by rows.
- Across servers, Route by key.
- Distribute the load.
Do
- Pick a key with many values.
- Keep related rows together.
- Plan rebalancing and pools per shard.
Avoid
- Timestamps as a range shard key.
- Joins over shards.
- Skipping a rebalancing test.