Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 30 min · revision 1

Sharding a social graph table and planning a rebalance

Work through a full shard-key proposal for a follows table: choose keys from the requests, add a second copy keyed by followee, split the largest accounts into buckets, and plan the move from 8 to 12 shards with seeded scripts and a copy-time estimate.

Contentsand lesson path

What you will learn

  • Choose a shard key and strategy (range, hash, directory) that avoids hot partitions and serves the main queries.
  • Plan rebalancing and resharding, and serve cross-shard queries with index tables or materialized views while estimating the cost of cross-shard joins and transactions.

01. The problem

A social app stores who follows whom in one table. It has outgrown a single server, and you must write the sharding proposal: which keys, how to handle the largest accounts, and how to add shards later without downtime. Here is the table:

SQL · the table before sharding
CREATE TABLE follows (
  follower_id bigint      NOT NULL,  -- the account that follows
  followee_id bigint      NOT NULL,  -- the account being followed
  created_at  timestamptz NOT NULL,
  PRIMARY KEY (follower_id, followee_id)
);

It must serve four kinds of request. The rates are assumptions for this exercise, not figures from a real company:

Requests and assumed peak rates
R1  does account A follow account B?        60,000/s  profile views, posts
R2  accounts that A follows, 200 per page   20,000/s  building A's home feed
R3  accounts that follow B, 200 per page     4,000/s  follower lists, notifications
W1  follow or unfollow                       3,000/s  writes

First, the size. Assume 150 million accounts that follow 170 others on average: 150 × 10⁶ × 170 ≈ 2.6 × 10¹⁰ edges. Assume each edge costs about 100 bytes for the row, its primary-key index and storage overhead, and allow 70 to 150 bytes. One copy of the table is then about 2.6 TB, somewhere between 1.8 and 3.8 TB, before replicas. That is too much to restore quickly on one server, and the request rates are high, so the team shards.

02. Step 1: Choose the key from the requests

R1 names both accounts, so it can be served from either account's shard. R2, the busiest request that names only one account, starts from the follower. If rows are placed by a hash of follower_id, all of A's edges live on one shard: R1 is a primary-key lookup there, and R2 a short index scan. R3 starts from the followee, so with this key alone it must ask every shard: 4,000 requests per second on 8 shards is 32,000 shard queries per second, and it grows with every shard you add.

The rejected options show why the requests decide. Keying by followee_id would keep R1 on one shard, on B's, but R2, five times as frequent as R3, would ask every shard: 20,000 × 8 = 160,000 shard queries per second. A range of follower IDs would put the newest accounts, often the most active, on the last shard. Hashing the pair (follower_id, followee_id) spreads rows evenly but scatters both R2 and R3 over every shard.

The layout: partition = hash(follower_id) mod 4096, fixed forever, plus a partition map that assigns the 4,096 logical partitions to physical shards, 512 each on 8 shards today. Each shard is a leader with replicas, as in lesson 01. Call this table follows_out.

03. Step 2: Add a second copy keyed by followee

To make R3 a single-shard request, keep an index table, follows_in, partitioned the same way but by hash(followee_id), with the same three columns. Every follow now writes two rows, so W1 becomes 6,000 row writes per second, and storage doubles to about 5.2 TB before replicas.

The two rows usually live on different shards, so no local transaction covers both. Two-phase commit would keep them exact, but every follow would then wait for two shards and hold locks across them. The usual choice is to treat follows_out as the source of truth, written in one local transaction, and to apply each change to follows_in asynchronously from the change stream or an outbox table. The apply step must be idempotent (insert-or-ignore, delete-if-present), and a periodic job compares the two copies partition by partition and repairs differences.

Facebook's TAO, described in a 2013 paper, made the same trade: an edge is stored on the shard of its first ID and its inverse edge on the shard of the second, the two writes are not atomic, and an asynchronous job repairs edges left without their inverse. The consequence for this design is that R3 can briefly miss a new follower. That is acceptable for a follower list, and R1, which decides what a user sees, reads the source of truth.

04. Step 3: Size the partitions of the biggest accounts

Partitions of follows_out stay even, because each one mixes about 37,000 accounts and apps usually cap how many accounts one user can follow. follows_in is different: followers per account follow a power law, and one account can have tens of millions. The script models 300,000 accounts sharing 30 million edges and measures the largest follows_in partition against the median, first with one key per account, then with the largest accounts split into 16 buckets.

Python 3.12 · celebrity_split.py
"""Partition sizes of follows_in (keyed by followee), before and after splitting
the largest accounts into buckets. Python 3.12, standard library only."""

import hashlib
import random
import statistics
from collections import Counter

PARTITIONS, USERS, EDGES, BUCKETS = 4096, 300_000, 30_000_000, 16
rng = random.Random(11)


def h(key: object) -> int:
    return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest())


# Followers per account follow a power law: a few accounts have huge audiences.
weights = [rng.paretovariate(1.5) for _ in range(USERS)]
total = sum(weights)
followers = [EDGES * w / total for w in weights]
LIMIT = EDGES / PARTITIONS  # split accounts bigger than an average partition


def sizes(split: bool) -> Counter:
    size = Counter()
    for user, count in enumerate(followers):
        if split and count > LIMIT:  # key becomes (followee_id, bucket)
            for bucket in range(BUCKETS):
                size[h((user, bucket)) % PARTITIONS] += count / BUCKETS
        else:  # key is followee_id
            size[h(user) % PARTITIONS] += count
    return size


top = max(followers)
print(f'largest account: {top:,.0f} followers, {top / EDGES:.2%} of all edges')
print(f'accounts above the split limit: {sum(c > LIMIT for c in followers)}')
for split in (False, True):
    size = sizes(split)
    ratio = max(size.values()) / statistics.median(size.values())
    label = 'with buckets' if split else 'one key per account'
    print(f'{label:<20} largest partition = {ratio:.1f} x median')
Expected output (python3 celebrity_split.py)
largest account: 140,240 followers, 0.47% of all edges
accounts above the split limit: 102
one key per account  largest partition = 22.4 x median
with buckets         largest partition = 3.4 x median

One account holds 0.47% of all edges, so its partition is 22 times the median, and every notification fan-out for that account's posts reads the same partition. For the 102 accounts above the limit, the proposal stores follows_in rows under (followee_id, bucket), with bucket = hash(follower_id) mod 16, which brings the largest partition down to 3.4 times the median.

The split has costs. Listing a big account's followers reads 16 partitions and merges them. R3 must know which accounts are split, so a small directory of big accounts is checked on every request and cached. When an account crosses the limit, its rows must be moved into buckets, a small reshard of its own. The very largest accounts may need more buckets than 16.

05. Step 4: Plan the move from 8 to 12 shards

Growth will fill the 8 shards. The script compares two ways of adding 4 more: rehashing every follower with mod 12 instead of mod 8, and keeping the 4,096 partitions while moving whole partitions, smallest first, from the fullest shard to the emptiest until no single move would narrow the gap.

Python 3.12 · rebalance_plan.py
"""Plan the move of follows_out from 8 to 12 shards. Python 3.12, standard library."""

import hashlib
import random
from collections import Counter

PARTITIONS, OLD, NEW, USERS = 4096, 8, 12, 300_000
rng = random.Random(7)


def h(key: int) -> int:
    return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest())


# Edges per follower: most accounts follow tens or hundreds, a few follow thousands.
out_degree = [min(int(rng.lognormvariate(4.4, 1.0)), 7_500) for _ in range(USERS)]
edges = sum(out_degree)
size = Counter()  # edges stored in each logical partition
for user, degree in enumerate(out_degree):
    size[h(user) % PARTITIONS] += degree

# Option A: no partitions, shard = hash(follower_id) mod number of shards.
moved = sum(d for u, d in enumerate(out_degree) if h(u) % OLD != h(u) % NEW)
print(f'mod-N rehash, 8 -> 12 shards: {moved / edges:.1%} of edges change shard')

# Option B: fixed partitions in a map; move whole partitions to the new shards.
owner = {p: p % OLD for p in range(PARTITIONS)}
load = Counter()
for p, shard in owner.items():
    load[shard] += size[p]
plan = []
while True:
    donor = max(range(NEW), key=lambda s: load[s])
    taker = min(range(NEW), key=lambda s: load[s])
    p = min((p for p in owner if owner[p] == donor), key=lambda p: size[p])
    if load[donor] - load[taker] <= size[p]:
        break  # moving one more partition would not reduce the gap
    owner[p] = taker
    load[donor] -= size[p]
    load[taker] += size[p]
    plan.append((p, donor, taker))
moved = sum(size[p] for p, _, _ in plan)
print(f'partition map: {len(plan)} of {PARTITIONS} partitions move,'
      f' {moved / edges:.1%} of edges')
largest = max(load.values()) / (edges / NEW)
print(f'largest shard after the move: {largest:.3f} x average')
print('first moves:', ', '.join(f'p{p} {a}->{b}' for p, a, b in plan[:3]))
Expected output (python3 rebalance_plan.py)
mod-N rehash, 8 -> 12 shards: 66.6% of edges change shard
partition map: 1665 of 4096 partitions move, 33.3% of edges
largest shard after the move: 1.001 x average
first moves: p2896 0->8, p2712 0->9, p1120 0->10

Rehashing moves two thirds of all edges, almost the whole table. The partition map moves one third, the minimum needed to fill the four new shards, and leaves them balanced to within 0.1%. Consistent hashing is another way to keep moves small.

Now estimate the time. A third of both copies, 5.2 TB, is about 1.7 TB, so each new shard receives about 430 GB. The copy must be throttled so that the source shards keep serving users. At 200 MB/s per new shard the copy takes 430,000 MB ÷ 200 MB/s ≈ 2,150 s, about 36 minutes; at 100 MB/s about 72 minutes; at 50 MB/s about 2.4 hours. Catch-up, checks and cutovers come on top.

Each partition then moves in five stages, the same shape as the Vitess Reshard workflow:

  1. Copy the partition's rows to the target while the source keeps serving.
  2. Catch up by applying the source's changes since the copy began, read from its log.
  3. Verify row counts and checksums; Vitess has a tool for this, VDiff.
  4. Cut over: stop writes to that partition on the source, wait until the target has applied everything up to the source's final log position, switch the map entry to a new version, and resume writes on the target. Vitess makes the source read-only for this window, so writes pause or fail briefly. A router that still has the old map must be refused by the source, then refresh the map and retry.
  5. Keep a way back: stream changes from the target to the source for a while, so that you can switch back, then delete the old copy.

06. Check your understanding

Practice check · 3 questions

Social graph and rebalancing

Three questions on fan-out, cutover and copy time.

Q1. `follows_out` is sharded by `follower_id` only, and there is no second copy. Which request must ask every shard?
Q2. Partition 1730 is moving from shard 3 to shard 9. The bulk copy is done, and shard 9 applies shard 3's change stream about 2 s behind. What is a safe way to switch partition 1730 to shard 9?
Q3. A rebalance moves 300 partitions of about 4 GB each onto one new shard, and the copy into that shard is throttled to 100 MB/s to protect live traffic. Roughly how long does the bulk copy take, before catch-up?
Practice only: not graded, not saved, not evidence.

07. Apply it

Finish the skill's practice task with a shard-key proposal for a 5 TB table of your choice, using the four steps above:

  1. Requests and rates, the size estimate with its assumptions, and the chosen key and layout.
  2. Index tables or materialized views for the requests the key does not serve, with how they are kept in step.
  3. Hot-key analysis: change celebrity_split.py to your own distribution and decide the split limit and bucket count.
  4. A resharding plan: change rebalance_plan.py to your shard counts, estimate the copy time with best, expected and worst rates, and write the cutover and rollback steps.

08. Review prompt

Without looking back, explain: why follower_id was the right key for follows_out; what the follows_in copy costs and how it is kept in step; why the largest accounts were split into buckets and what that costs on reads; how much data mod-N rehashing and a partition map each move when going from 8 to 12 shards; and the five stages of moving one partition safely.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check