Sub topic 9
Sharding and scaling the pipeline
Earlier chapters built the feed logic on a single logical store. This chapter splits that store across many machines. It assumes you know the fan-out on write and hybrid designs from the previous chapters, and that you have used a key-value store such as Redis and a relational database. You should also be able to read short Python snippets.
What has to scale
A news feed has four parts that grow at different rates:
- Posts store. It is append-heavy and read by post ID.
- Follow graph. It is read in two directions: "who follows author A" (for fan-out) and "who does user U follow" (for pull reads).
- Timeline cache. One bounded list per user.
- Fan-out pipeline. A queue and workers that turn one publish into many timeline writes.
Each part gets its own shard key. Using one key for everything is the most common early mistake.
Estimating when one machine stops being enough
A rough estimate shows which part breaks first. Assume 200 million daily users, 10 feed reads per user per day, 50 million new posts per day, and an average of 200 followers per author.
| Quantity | Calculation | Result |
|---|---|---|
| Feed reads | 200M × 10 / 86,400 s | about 23,000 per second on average, about 70,000 at 3× peak |
| Timeline writes | 50M × 200 / 86,400 s | about 116,000 per second on average |
| Timeline storage | 200M users × 800 entries × 16 bytes | about 2.6 TB per copy |
Fan-out on write turns 580 publishes per second into 116,000 timeline writes per second. The write rate and the 2.6 TB of memory both exceed a single cache node. The pipeline, not the posts table, is the first thing to shard.
Choosing shard keys
| Data set | Shard key | Why | Cost |
|---|---|---|---|
| Timelines | `user_id` | A feed read touches exactly one shard | A fan-out write touches many shards |
| Posts | `post_id` (or `author_id`) | IDs spread evenly, and hydration is a lookup by ID | Listing one author's posts needs `author_id` to be indexed or co-located |
| Followers of author (`author_id → followers`) | `author_id` | Fan-out workers read one author's list sequentially | A celebrity's list is huge and sits on one shard |
| Following of user (`user_id → followed`) | `user_id` | Pull reads and hybrid merges read one user's list | The same edge is stored twice |
Follow edges are stored twice, once per direction. The two copies are updated by the same follow or unfollow operation. If they can drift apart, treat the follower-side copy used for fan-out as the one to repair, because that is the one that decides who receives posts.
Why not shard posts by author?
Sharding by author_id makes "latest posts from author X" a single-shard query, which the pull path for celebrities needs. It also puts all of a celebrity's traffic on one shard. Sharding by post_id spreads load, but then you need a secondary index or a separate author_posts table keyed by author_id. Many systems keep both: the posts table sharded by post_id and a small (author_id, created_at, post_id) index sharded by author_id. The index only holds references, so hot authors cost little storage.
Mapping keys to shards
Hashing with hash(key) % N is simple, but changing N remaps almost every key. For a cache this means a near-total miss storm when you add a node. Consistent hashing places nodes at many points on a ring, and each key belongs to the next node clockwise. Adding a node moves only about 1/N of the keys.
import bisect
import hashlib
from collections import defaultdict
class HashRing:
"""Consistent hash ring with virtual nodes."""
def __init__(self, nodes, vnodes=100):
points = []
for node in nodes:
for i in range(vnodes):
points.append((self._hash(f"{node}#{i}"), node))
points.sort()
self._points = points
self._hashes = [h for h, _ in points]
@staticmethod
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
def node_for(self, key):
h = self._hash(str(key))
idx = bisect.bisect(self._hashes, h) % len(self._hashes)
return self._points[idx][1]
def group_by_shard(ring, follower_ids):
"""Batch follower IDs by the timeline shard that owns them."""
batches = defaultdict(list)
for follower_id in follower_ids:
batches[ring.node_for(follower_id)].append(follower_id)
return batches
ring = HashRing(["tl-0", "tl-1", "tl-2", "tl-3"])
batches = group_by_shard(ring, range(10_000))
for shard in sorted(batches):
print(shard, len(batches[shard]))Virtual nodes smooth out the distribution. The four counts come out close to 2,500 each but not identical. With one point per node the split can be badly lopsided.
The batching function matters more than the ring. A fan-out worker that sends one network call per follower spends its time on round trips. Grouping follower IDs by destination shard turns 10,000 writes into 4 pipelined batch calls.
Scaling the fan-out pipeline
The publish request should not perform the fan-out. It writes the post, enqueues a small event, and returns. Workers do the rest.
Design choices in this pipeline:
- Partition the queue by
author_id. Posts from one author stay in order, and a retry does not interleave with a newer post. - Split large follower lists into chunks. A worker handles 1,000 followers per task, not one author's whole list. A single chunk failing or running slowly then does not block the rest, and many workers can share one author's fan-out.
- Make each timeline write idempotent. A timeline entry is
(timestamp, post_id). Writing it twice into a sorted set is harmless, so workers can retry freely. At-least-once delivery from the queue is then enough. - Apply backpressure. If workers fall behind, queue depth grows. Alert on the age of the oldest message, not only on depth, because age is what users feel as stale feeds.
Prioritizing work
Not all fan-out is equally urgent. Posts from authors with a small number of followers who are online now should be delivered first. Fan-out to inactive users can run on a low-priority queue, or be skipped entirely. A user who has not opened the app in 30 days can have their timeline rebuilt on their next login using the pull path. This reduces timeline writes and cache memory by the share of dormant accounts, often a large fraction.
Hot spots
Even with good hashing, load is not uniform. Three hot spots show up in feeds.
- Hot author. A celebrity's follower list lives on one graph shard, and every read of it goes there. The hybrid design already avoids pushing their posts. You must still protect the shard that serves their recent posts to millions of readers. Cache the author's last page of posts under a key replicated on several nodes, and add a small random suffix to the key (
author:123:recent:{0..7}) so reads spread across copies. - Hot post. A viral post is hydrated by every reader. Cache post bodies by
post_idin a separate tier with short TTLs for counters such as likes. Read counts from a different path than the body. - Hot reader. A bot polling a feed every second burns a timeline shard. Rate-limit per user at the API gateway.
Replication and read scaling
Timelines are derived data. They can be rebuilt from the posts store and the follow graph. That changes how much durability you buy for them:
- Keep one or two replicas of each timeline shard for availability, not as the source of truth.
- Read from replicas and accept a small replication lag. A feed that is a second behind is normal.
- Replicate the posts store and follow graph with the durability your database normally provides, since those are the sources of truth.
When a timeline shard is lost, the system serves affected users through the pull path and rebuilds their lists in the background. This is slower per request, so the rebuild should be rate-limited to avoid overloading the posts store.
Scatter-gather on the read path
In the hybrid design a feed read has two parts: the user's timeline (one shard) and recent posts from followed celebrities (several shards). The second part is a scatter-gather. The reader gets the list of followed celebrity IDs, fetches each one's recent posts in parallel, and merges them with the timeline.
Keep this cheap:
- Store a per-user list of followed high-follower accounts, which is short, with the timeline or in the following-graph shard.
- Set a timeout on each celebrity fetch. If one is slow, return the feed without it rather than delaying the response.
- Cap the number of celebrities merged per request, for example the 50 most recently active.
- Fetch only the first page worth of entries from each source. A lazy merge needs no more than the page limit from each list.
Adding and removing nodes
Resharding is where many designs fail in production. Safe steps for a timeline cache:
- Add the new node to the ring in a "warming" state. It receives writes for its key range but does not serve reads.
- Let fan-out writes populate it. Since timelines are bounded and constantly updated, active users fill in quickly. For others, a miss falls back to the pull path.
- Switch reads to the new node once its hit rate is acceptable.
- Remove the old copies after a delay, so a rollback is possible.
For the database tiers, use many more logical shards than physical machines, for example 1,024 logical shards on 16 machines. Moving a logical shard to a new machine is a copy and a routing change. Splitting a logical shard in two is far harder, so choose a generous count at the start.
Failure modes
| Failure | Symptom | Mitigation |
|---|---|---|
| Queue partition stalls | Feeds of one author's followers go stale | Alert on oldest message age, and restart or reassign the consumer |
| Timeline shard down | Elevated errors for a slice of users | Fail over to a replica, else serve from the pull path |
| Worker crash mid-batch | Some followers miss a post | Idempotent retries from the queue |
| Cache node added without warming | Miss storm hits posts store and graph | Warm first, and rate-limit rebuilds |
| Graph shard hot | Slow fan-out for large authors | Chunk follower lists, replicate reads |
| Duplicate edge copies drift | Users receive posts after unfollowing, or miss posts | Periodic reconciliation job, repair from the follower-side copy |
A checklist for reviewing a sharding plan
- Does each query path hit one shard, or a small and bounded number?
- Is every shard key high-cardinality and evenly distributed, with a plan for the few keys that are not?
- Can you add a node without remapping most keys?
- Are all fan-out writes idempotent, so retries are safe?
- What happens to feed reads when any one tier is fully down?
Exercise
A team shards timelines by user_id with hash(user_id) % 8 across 8 cache nodes. They add a ninth node and change the formula to % 9. Roughly what fraction of keys now map to a different node, and what would you change?
Show answer
With modulo hashing, a key keeps its node only when hash % 8 equals hash % 9, which holds for roughly 1 in 9 keys. So about 8/9 (around 89%) of keys move, and the cache sees a miss storm that falls back to the pull path and the posts store. Use consistent hashing with virtual nodes, so adding a ninth node moves only about 1/9 of the keys. Also warm the new node before it serves reads.
Exercise
A fan-out worker publishes a post from an author with 500,000 followers by looping over all followers and sending one cache write each. Name two problems and give a fix for each.
Show answer
First, one network round trip per follower makes the task very slow. Group follower IDs by owning timeline shard and send pipelined batch writes. Second, one task holds the whole list, so a crash or slowdown delays or loses everyone after that point. Split the list into chunks of about 1,000 followers per task, and make each timeline write idempotent so a failed chunk can be retried safely.