Partitioning strategies
medium 25 minRange, hash and list partitioning are three rules for placing rows.
See it run
Send the same keys through three rules and see which questions stay cheap.
Operations
Range
Each shard owns an interval.
Step 1 of 4
Key 42
42 is in 0 to 999
42 is below 1000, so it belongs to shard 0.
Step 1: Key 42
bounds = [1000, 2000]def range_shard(key): return bisect_right(bounds, key)def shards_for(low, high): return range(range_shard(low), range_shard(high) + 1)- One key
- 1 shard
- A range
- Few
- Search among 1,024 ranges
- 10 comparisons
Include the lower bound and exclude the upper. Then no key is lost and none has two homes.
In the real world
The same partitioning strategies doing real jobs. Pick one and step through it.
A business service hashes tenants to three shards.
Step 1 of 4
Even at first
- Shard 0
- 33%
- Shard 1
- 34%
- Shard 2
- 33%
Even
Hundreds of small tenants, spread by hash.
Step 1: Even at first
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Bounds that overlap
majorTwo partitions that both include the bound give one key two homes.
Wrong0 <= k <= 1000 -> shard 01000 <= k <= 2000 -> shard 1Right0 <= k < 1000 -> shard 01000 <= k < 2000 -> shard 1A negative remainder
criticalIn Java a hash may be negative, and abs of the smallest int is still negative.
WrongMath.abs(key.hashCode()) % nRightMath.floorMod(key.hashCode(), n)Hash for interval questions
majorEach report over an interval asks every shard.
Wrongshard = hash(event_id) % n# then: WHERE time BETWEEN a AND bRightshard = hash(device_id) % n# rows sorted by time insideAsking the directory every time
majorIt becomes the slowest and most fragile part of every request.
Wrongshard = directory.get(region) # networkRightshard = cached_map[region]# reload when the version changes
Interview tips
How to explain it
- Range: neighbours stay together.
- Hash: neighbours are scattered.
- List: you decide.
Memory trick: RHL
- Range queries: Range.
- Even spread: Hash.
- Location or tenant: List.
Often the answer
- Hash the owner.
- Sort by time inside.
- Fixed slots, not modulo machines.
Watch out for
- Keys that only grow.
- One key with most traffic.
- Second questions on another field.