Sub topic 9
Sharding and scaling the pipeline
This chapter assumes you know the fan-out models from earlier chapters (read, write, hybrid), the bounded feed cache, and basic ideas of partitioning and message queues. Here we look at how to split the data and the work across machines so the feed keeps up as users and posts grow.
What needs to scale
A feed system has three parts that grow at different rates:
- Storage. Posts, follow edges, and per-user timelines.
- Read traffic. Feed requests, usually the largest load by far.
- Write amplification. One post becomes many timeline writes under fan-out on write.
Each part is sharded on its own key. Picking a single key for everything is the most common early mistake.
Choosing shard keys
A shard key decides which machine owns a row. A good key spreads load evenly and keeps the queries you run most on a single shard.
| Data | Shard key | Why | Cost |
|---|---|---|---|
| Feed cache (timelines) | `user_id` | A feed read touches one shard | Hot users can still skew load |
| Posts | `post_id` (hashed) | Even spread of writes and storage | Fetching an author's posts hits many shards |
| Posts, alternative | `author_id` | One author's posts are co-located | Celebrity authors create hot shards |
| Follow edges | `follower_id` and a mirrored copy by `followee_id` | Supports "who do I follow" and "who follows me" | Two copies to keep in sync |
Timelines hold only (timestamp, post_id) references. A read therefore does two steps: load the timeline from one shard, then fetch the post bodies in a batch from the post store. Batching by shard keeps the number of calls low.
Consistent hashing
If you assign a user to a shard with hash(user_id) % N, changing N moves almost every user. Consistent hashing places shards on a ring, so adding a shard moves only a small fraction of keys.
import bisect
import hashlib
class HashRing:
def __init__(self, nodes, replicas=100):
self.ring = [] # sorted list of (hash, node)
for node in nodes:
for i in range(replicas):
self.ring.append((self._hash(f"{node}#{i}"), node))
self.ring.sort()
self.keys = [h for h, _ in self.ring]
@staticmethod
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
def node_for(self, key):
idx = bisect.bisect(self.keys, self._hash(str(key))) % len(self.ring)
return self.ring[idx][1]
ring = HashRing(["cache-a", "cache-b", "cache-c"])
print(ring.node_for("user:42"))The replicas value creates many virtual points per node. Without them, a few nodes can end up owning much larger arcs of the ring than others.
Scaling the fan-out pipeline
Fan-out on write should never run inside the request that publishes the post. Publishing writes the post, then puts a fan-out job on a queue. Workers read the job, look up followers, and write to the timeline shards.
Several techniques keep this pipeline healthy:
- Batch followers. Split a follower list into chunks of, say, 1,000 and make each chunk its own job. A large author then becomes many small jobs that run in parallel.
- Group writes by shard. Within a chunk, send one batched write per timeline shard, not one per follower.
- Make jobs idempotent. Queues deliver at least once, so a retry must not duplicate an entry. Keying timeline entries by
post_idand ignoring repeats handles this. - Prioritize. Give active users' timelines a faster queue. Updates for users who have been inactive for weeks can wait or be skipped, and rebuilt on their next visit.
- Apply backpressure. If a queue grows past a threshold, slow producers or shed low-priority work instead of letting memory fill.
Scaling reads
Reads are mostly cache hits on a timeline shard plus a batch lookup of posts. These steps help:
- Replicas. Add read replicas for each timeline shard. Feeds tolerate slightly stale data, so replication lag is acceptable.
- A post cache. Popular posts are fetched by thousands of timelines. A separate cache keyed by
post_idabsorbs that load. Hot keys can be copied across several cache nodes. - Regional placement. Keep timelines near the users who read them, and replicate the post store across regions.
Failure modes
- Hot shard. One celebrity's post or a viral post concentrates traffic on a few keys. Mitigate with key replication and local in-process caches.
- Lost timeline shard. Because timelines are derived data, you can rebuild them from the follow graph and posts. Plan for the rebuild load, since many users will fall back to fan-out on read at once.
- Rebalancing storms. Moving data between shards competes with live traffic. Move in small batches with rate limits.
Exercise
Your feed cache is sharded with hash(user_id) % 8. You add a ninth shard and most users suddenly see empty feeds. Why did this happen, and what change prevents it next time?
Show answer
With modulo hashing, changing the shard count from 8 to 9 changes the result for most keys, so most users now map to a shard that does not hold their timeline. Use consistent hashing with virtual nodes, so adding a shard moves only a small share of keys, and warm or rebuild the moved timelines before routing traffic to them.