AlgoViz

Partitioning strategies

medium 25 min

Range, 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

Our systemClientkey 42Routercompare boundsShard 00 to 999Shard 11000 to 1999Shard 22000 and up

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

Our systemClienttenantsRouterhash of tenantShard 0many tenantsShard 1many tenantsShard 2many tenants
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

    major

    Two partitions that both include the bound give one key two homes.

    Wrong
    0 <= k <= 1000   -> shard 01000 <= k <= 2000 -> shard 1
    Right
    0 <= k < 1000    -> shard 01000 <= k < 2000 -> shard 1
  • A negative remainder

    critical

    In Java a hash may be negative, and abs of the smallest int is still negative.

    Wrong
    Math.abs(key.hashCode()) % n
    Right
    Math.floorMod(key.hashCode(), n)
  • Hash for interval questions

    major

    Each report over an interval asks every shard.

    Wrong
    shard = hash(event_id) % n# then: WHERE time BETWEEN a AND b
    Right
    shard = hash(device_id) % n# rows sorted by time inside
  • Asking the directory every time

    major

    It becomes the slowest and most fragile part of every request.

    Wrong
    shard = directory.get(region)  # network
    Right
    shard = 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.