The Problem#
Open Facebook, X (Twitter), Instagram or LinkedIn and the first screen is a news feed: a scrolling list of recent posts from the people and pages you follow, often re-ordered so the most interesting ones come first. You see your own posts on your profile timeline, the posts of everyone you follow on your home timeline, and you can search all public posts for a word or hashtag.
The product is simple. The engineering is not, because of one ratio. A user writes a post once, but the post must appear in the feeds of everyone who follows them. For most users that is a few hundred feeds. For a celebrity it is a hundred million. Meanwhile every user opens their feed many times a day and expects it in a fraction of a second. So the core question is when to do the work of assembling a feed:
- when a post is written (copy it into every follower's feed in advance: fan-out on write), or
- when a feed is read (collect recent posts from everyone the reader follows at that moment: fan-out on read), or
- a hybrid of the two, chosen per account.
A real-world analogy. Think of a newspaper delivery service in a big city. One way is for every writer to drop a copy of each article into the mailbox of every subscriber the moment it is written. Reading is instant, because your mailbox is already full, but a famous columnist with a million readers has to stuff a million mailboxes for every article. The other way is that nobody gets mail. When you want to read, you walk to every writer you like and pick up their latest articles. Writing is free, but reading means visiting hundreds of desks. Real services do both. Ordinary writers deliver to mailboxes. For the few famous columnists, readers pick up a copy from a shared stand on the way, and the two piles are merged when you sit down to read.
This case study designs that system end to end: posting, following, building and caching feeds, the celebrity problem, ranking, pagination, media, profile timelines and search. It builds on Pattern: Scaling Reads, Pub/Sub and Event Streaming and Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| Follow (one-way) or friend (two-way) relationships? | Follows allow huge follower counts, the root of the celebrity problem | One-way follows, like X or Instagram; friends are a special case |
| Chronological or ranked feed? | Ranking adds candidate generation, features and models | Start chronological, then add ranking as a layer |
| How many users and how active? | Drives fan-out volume and cache size | 2B registered users, 500M daily active |
| How many posts and follows? | Fan-out cost is posts × followers | 500M posts a day, about 200 follows per user on average, some accounts with 100M+ followers |
| How fresh must feeds be? | Freshness budget allows asynchronous fan-out | New posts visible to followers within about a minute; own posts immediately |
| How fast must the feed load? | Sets the read-path design | p99 under 500 ms for the API, first screen quickly on mobile |
| What do posts contain? | Media handling and storage size | Text, links, images and video; media up to a few hundred MB |
| Is search in scope? | Needs a separate real-time inverted index | Yes: keyword and hashtag search over public posts |
| Likes, comments, privacy? | Affect counters, ranking and filtering | Likes and comments exist (for ranking and counts); visibility rules apply at read time |
| Pagination depth? | Deep pagination is costly | Infinite scroll, but almost nobody scrolls past a few hundred posts |
| Consistency? | Availability vs freshness | Availability first, eventual consistency for others' posts |
Requirements#
Functional#
- Users can create posts with text and media.
- Users can follow and unfollow other users.
- Users see a home timeline: posts from people they follow, newest first or ranked.
- Users can scroll the feed infinitely, page by page.
- Users see a profile (user) timeline of any account's posts.
- Users can search public posts by keyword and hashtag.
- Followers can be notified of new posts from accounts they choose (push or email), handled by the notification system.
Non-Functional#
- Read latency: home timeline p99 under 500 ms server-side, p50 under 100 ms.
- Post latency: creating a post returns within about 200–500 ms. Fan-out is asynchronous.
- Freshness: a post appears in followers' feeds within 1 minute for normal accounts, a few minutes at worst. The author sees their own post immediately (read-your-writes).
- Availability: 99.99% for reading feeds. Prefer showing a slightly stale feed over showing an error.
- Scale: 2B users, 500M daily active, follower counts from 0 to over 100M, following counts up to several thousand.
- Durability: posts and follows are never lost. Feed caches can be rebuilt.
- Efficiency: memory for feed caches and the cost of fan-out must stay reasonable per user.
Capacity Estimation#
The numbers below are deliberately rounded. The point is to find which part of the system dominates. (See Back-of-the-Envelope Estimation for the method and Numbers Every Engineer Should Know for the constants.) A handy conversion: a day has about 86,400 seconds, so 1 billion per day is about 11,600 per second, and a month has about 2.5 million seconds, so 1 billion per month is about 400 per second.
Users and activity
- 2B registered users, 500M daily active users (DAU).
- Each DAU opens the feed about 10 times a day and loads about 2 pages each time. That is 10B feed page requests a day, about 116k per second on average. Assume a peak-to-average ratio of 2.5 to 3, so plan for about 300k per second.
- 500M new posts a day is about 5,800 posts per second on average. Plan for 15–20k per second at peak, and much more during a global event such as a World Cup final or New Year's midnight.
- The read-to-write ratio is about 116k : 5.8k, roughly 20 : 1 in requests. In work it is far more lopsided, because one write fans out to many feeds.
Fan-out volume (the number that drives the design)
Every follow edge has two ends, so the average number of followers equals the average number of follows, about 200. If every post were copied to every follower's feed:
- 500M posts × 200 followers = 100B feed inserts a day, about 1.16M inserts per second on average.
- Only feeds of recently active users are worth maintaining. If about half of all follower edges point to users active in the last 30 days, the volume drops to about 50B a day, roughly 580k per second.
- The distribution is extremely skewed. Most users have tens of followers. A few thousand accounts have more than 10M. One post from an account with 100M followers is 100M inserts on its own: as much work as 500,000 average posts. This is the celebrity problem, and it is why pure fan-out on write fails.
Storage
- Post metadata: id 8 B, author id 8 B, text up to about 280 characters (up to about 1 KB in UTF-8), timestamps, flags, media references and counters. That is about 1 KB per post. 500M × 1 KB = 500 GB a day, about 180 TB a year before replication. With three replicas, more than half a petabyte a year: big, but routine for a sharded store.
- Media: suppose 20% of posts carry media averaging 1 MB after compression (images are 100 KB to 2 MB; videos are far larger). 100M × 1 MB = 100 TB a day, more than 36 PB a year, before transcoded renditions. Media is by far the biggest storage item, which is why it goes to object storage and a CDN, never into the posts database.
- Follow graph: 2B users × 200 follows = 400B edges. Store each edge in both directions (followers and followees) at about 50 B per row including overhead: 400B × 2 × 50 B = about 40 TB.
- Precomputed feed cache: store only post ids, not post bodies. One entry is post id 8 B + author id 8 B + a few bytes of timestamp or flags, about 20 B.
- 200 entries per user × 20 B = 4 KB per user. For 1B active users, that is 4 TB.
- 800 entries per user = 16 KB per user, about 16 TB. With Redis per-key overhead and replication, plan for 40–50 TB of RAM.
- At about 100 GB usable per cache node, that is a few hundred nodes: a large but ordinary Redis or Memcached fleet.
Bandwidth
- Feed API responses: a page of 20 hydrated posts as JSON is about 20–40 KB. 116k pages per second × 30 KB ≈ 3.5 GB per second, about 28 Gbps, before compression. That is fine across many API servers.
- Media: each feed page triggers maybe 5 images or video segments of about 200 KB each, about 1 MB per page. 116k × 1 MB ≈ 116 GB per second, about 1 Tbps. Only a CDN can serve this. The origin sees a tiny fraction.
Search
- Index ingest equals the post rate: about 6k documents per second on average and 20k+ at peak, with near-real-time visibility.
- Queries: a few billion a month, so thousands to tens of thousands per second, each fanning out to many index shards.
What these numbers tell us
- Reads dominate requests, but fan-out dominates write work. Its cost depends on follower count, not post count.
- The feed cache must store ids, not posts, or it would be hundreds of times larger.
- Post bodies are read very unevenly. A viral post may be hydrated millions of times a minute, so the post cache needs a hot-key strategy.
- Media goes through object storage and a CDN.
- Only active users deserve a precomputed feed. For everyone else, we build on demand.
Core Entities#
- User: id, handle, display name, avatar URL, follower count, following count, flags (verified, celebrity, private).
- Post: id (time-sortable, e.g. a Snowflake-style 64-bit id), author id, text, media references, created time, edited time, visibility, deleted flag, counters (likes, replies, reposts), reply-to and quote references.
- Follow: follower id, followee id, created time, and optionally a "precomputed" flag or notification setting. This is a directed edge.
- FeedItem: an entry in one user's precomputed home timeline: owner id, post id, author id, sort key (time or score), source (fan-out, injected, ad). It is derived data and can always be rebuilt.
- Media: id, owner, type, original object key, renditions (sizes and bitrates), status (uploading, processing, ready, failed).
- Engagement events: like, reply, repost, view and click events. They feed counters, ranking features and notifications.
The key design decision is already visible. Post, User and Follow are the source of truth. FeedItem is a cache of a query. If every FeedItem were lost, we could rebuild every feed from Follow and Post. That freedom lets us keep FeedItems in memory, trim them aggressively and skip them for inactive users.
API Design#
The API is a small REST surface over HTTPS (see HTTP, HTTP/2, HTTP/3 and HTTPS). Feeds use cursor pagination, never page numbers, because new posts arrive at the top all the time.
POST /v1/media/uploads -> { mediaId, uploadUrl (pre-signed), expiresAt }
POST /v1/posts
{ "text": "Hello", "mediaIds": ["m_91"], "replyTo": null,
"visibility": "public", "clientRequestId": "c-7f3a" }
-> 201 { "postId": "1849...", "createdAt": "2026-12-03T10:00:00Z" }
PATCH /v1/posts/{postId} { "text": "Hello, edited" }
DELETE /v1/posts/{postId}
PUT /v1/users/{userId}/follow -> 204 (idempotent)
DELETE /v1/users/{userId}/follow -> 204
GET /v1/feed?limit=20&cursor=<opaque>
-> { "items": [ { "post": {...}, "author": {...}, "reason": "following" } ],
"nextCursor": "eyJ0IjoxNzM...", "hasMore": true }
GET /v1/feed/new?since=<cursorOfTopItem> -> { "count": 7 }
GET /v1/users/{userId}/posts?limit=20&cursor=<opaque>
GET /v1/search/posts?q=world+cup&limit=20&cursor=<opaque>Design notes:
- The user id comes from the auth token, never from the request body, so nobody can post as someone else or read another user's private feed. See Authentication and Authorization.
clientRequestIdmakes post creation idempotent. If the mobile client retries after a timeout, the server returns the original post instead of creating a duplicate. See Idempotency and Safe Retries.- Follow is a
PUT, which is idempotent by HTTP semantics: following twice is a no-op. Unfollow is aDELETE. - The cursor is opaque. Clients must not parse it. Internally it encodes the position (the last post id or time, or for ranked feeds a session id and offset) and is signed, so the server can change the format without breaking clients.
/feed/newpowers the "7 new posts" pill at the top of the feed. It is cheap to poll every 30–60 seconds, or the server can push it over an existing connection.- Media uploads go straight from the client to object storage through a pre-signed URL, so large bytes never pass through the API servers.
High-Level Design#
We build the design one requirement at a time. We start with the simplest version that works, find where it breaks, and fix only that.
1) Creating a post#
A client calls POST /v1/posts. The API gateway authenticates the request, applies per-user rate limits (a spam bot should not be able to post 1,000 times a minute; see Rate Limiting and Throttling) and routes it to the Post Service. The Post Service:
- Validates the text: length, banned content, links checked by a safety service.
- Checks that every
mediaIdbelongs to this user and is either ready or still processing. - Generates a post id. We use a 64-bit, roughly time-ordered id in the style of Twitter's Snowflake: a millisecond timestamp in the high bits, then a worker id and a per-millisecond sequence. Sorting by id is then sorting by creation time, so feeds, cursors and indexes can all use the id directly.
- Writes the post to the Posts store, keyed by post id, with a secondary index on
(authorId, postId desc)for profile timelines. - Publishes a
PostCreatedevent for everything downstream: fan-out, search indexing, notifications and analytics.
Step 5 hides a classic trap: the dual-write problem. If the service writes the database and then crashes before publishing the event, the post exists but no follower ever sees it. If it publishes first and the database write fails, followers see a post that does not exist. The standard fix is the transactional outbox or change data capture: write the event as part of the same database transaction (or tail the database's change log), and let a relay publish it to Kafka. See Change Data Capture and the Outbox Pattern. The event stream is then guaranteed to contain every committed post, at least once.
Which store for posts? Posts are written once, read by id very often, edited rarely and never joined at feed time. A wide-column or key-value store such as Cassandra, DynamoDB or a sharded MySQL setup like Facebook's TAO-backed MySQL fits well. The access patterns are "get by id" and "list by author, newest first", and both map to a partition key plus a sort key. We discuss this in the data model.
2) Following#
PUT /v1/users/{id}/follow goes to the Graph Service, which owns the follow edges. We need to answer two questions quickly:
- "Whom does user A follow?" This is needed to build A's feed.
- "Who follows user B?" This is needed to fan out B's posts.
So each edge is stored twice. A following table is partitioned by follower id, and a followers table is partitioned by followee id. In DynamoDB this is one table with partition key followerId and sort key followeeId, plus a global secondary index that flips them. In Cassandra it is two tables written together. We do not need a graph database. We only ever look one hop away, and simple adjacency lists partitioned by user do that at enormous scale. (Facebook's TAO is a graph API over sharded MySQL and caches, not a graph database.)
Following someone also triggers a small backfill: insert that account's few most recent posts into the follower's feed so the follow has a visible effect at once. Unfollowing does the reverse, lazily. Either remove the account's items from the cached feed, or filter them out at read time and let them age out.
3) Reading the feed: the naive way (fan-out on read)#
The simplest correct feed is a query at read time:
- Get the list of accounts the user follows from the Graph Service.
- For each of them, get their recent posts from the Posts store using the
(authorId, postId)index. - Merge all those lists by post id (time), take the top 20, and hydrate them.
This works fine for a small product. It is also always fresh and costs nothing at write time. It breaks on three fronts:
- Many follows. A user following 2,000 accounts needs 2,000 partition reads per feed open. Even in parallel, the slowest of 2,000 reads sets the latency: tail-at-scale, where one slow shard makes the whole request slow. With 300k feed requests per second, the Posts store would face hundreds of millions of reads per second.
- Repeated work. The same merge is computed again on every refresh, though almost nothing changed since the last one.
- Deep pages. Page 10 needs the merge to skip 200 posts, which means fetching even more from every followee.
Product limits help, but only a little. Facebook caps friends at 5,000. X limits how many accounts one can follow per day and caps the following count unless an account has enough followers. Even 5,000 is too many partition reads per request.
4) Precomputing feeds (fan-out on write)#
Flip the work: do it once when a post is written, and keep every user's feed ready to read.
- The Fan-out Service consumes
PostCreatedevents. For each event, it asks the Graph Service for the author's followers. It then pushes the post id into each follower's precomputed feed, a list in a fast store, newest first and capped at a few hundred entries. - Reading becomes one key lookup,
feed:{userId}, which returns the latest N post ids in sub-millisecond time from Redis. The ids are then hydrated.
Twitter famously ran this design: home timelines lived in Redis clusters as lists of tweet ids, and a fan-out service wrote into them. Each entry stored little more than the tweet id, the author id and a few flag bits, and each timeline kept only the most recent several hundred tweets.
Fan-out on write must be asynchronous. The post API returns as soon as the post is durably stored. A queue absorbs the fan-out work, and workers drain it in parallel (see Asynchronous Processing and Message Queues). Because the queue gives at-least-once delivery, an insert may happen twice. So feed inserts must be idempotent: adding a post id that is already in the list is a no-op, which is natural if the list is a sorted set keyed by post id.
Large fan-outs are split into chunks. A post from an account with 50,000 followers becomes 50 tasks of 1,000 followers each. Many workers process them in parallel, and a failure retries only one chunk.
5) Celebrities: the hybrid model#
Fan-out on write breaks on the other end of the distribution. An account with 100M followers creates 100M inserts per post. Even at 1M inserts per second across the whole fan-out fleet, that is about 100 seconds of the entire fleet's capacity for a single post. Meanwhile ordinary users' posts wait in the same queue. A handful of famous accounts posting during a big event could delay everyone's feed by many minutes. It is also wasteful: most of those 100M followers will not open the app before the post scrolls out of their cached feed.
The fix is the hybrid (push-pull) model:
- Normal accounts (below a threshold, say 10k–100k followers; the exact value is tuned from data) are fanned out on write as before.
- High-follower accounts are not fanned out. Their posts stay only in their own author timeline, which is cheap to read and heavily cached because it is so popular.
- At read time, the Feed Service takes the user's precomputed feed and fetches recent posts from the few celebrities they follow, then merges the two lists by id.
Because a typical user follows only a handful of such accounts (tens, not thousands), the read-time part stays small. Each celebrity's recent posts are read from a cache shared by millions of readers, so they are almost always cache hits.
Implementation details matter:
- Where is the flag? Store a per-edge or per-account flag saying "this followee is not precomputed". The Feed Service can then load the celebrity list together with the feed instead of scanning the whole follow list. Keeping this list per user ("celebrities I follow", usually a short set) makes the pull cheap.
- Crossing the threshold. When an account grows past the threshold, stop fanning out its new posts. Old ones already pushed stay in place, so nothing is lost. If an account shrinks below the threshold, start fanning out again, with some hysteresis (for example, switch at 100k but switch back only below 80k) so accounts near the line do not flap.
- Per-post decisions. Some systems decide per post instead of per account. They fan out to followers who were active recently and let the rest pull. That gives "fan-out on write for active users, fan-out on read for inactive ones".
6) Hydration: turning ids into posts#
The feed lists hold only ids. Before returning a page, the Feed Service must hydrate about 20 post ids into full posts with their authors, counters, media URLs and the viewer's own state ("did I like this?"). That is a multi-get against:
- the Post cache: a distributed cache of post objects keyed by post id. Posts are immutable apart from edits, deletes and counters, so they cache very well with long TTLs.
- the User cache: author profiles keyed by user id.
- the Engagement services: like, reply and repost counts (often cached separately because they change constantly), plus "viewer has liked" bits.
A page of 20 posts may touch 20 post keys, up to 20 user keys and some counter keys. Issued as a few parallel batched multi-gets, this costs 1–3 ms in a healthy cache. Misses fall back to the Posts store and fill the cache (cache-aside; see Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind).
Hydration is also where visibility is enforced. Deleted posts, posts from accounts the viewer has blocked or muted, posts from accounts that went private, and posts removed by moderation are filtered out here, at read time. Fan-out cannot know these things in advance, and they change after the fact.
7) Media#
Images and videos never go through the Post Service. The client first calls POST /v1/media/uploads and receives a pre-signed URL for object storage (S3, GCS or an in-house blob store). It uploads the bytes directly, in resumable chunks for large videos. The upload triggers a media pipeline that:
- scans the content for malware and policy violations,
- strips location metadata (EXIF GPS) unless the user opted in,
- transcodes images into several sizes and formats (thumbnail, feed size, full size; WebP or AVIF where supported),
- transcodes videos into adaptive bitrate renditions (HLS or DASH segments at 240p to 1080p or 4K),
- marks the media
ready.
The post stores only media ids, and the client fetches renditions from a CDN that caches them near users. See Pattern: Handling Large Files and Blobs, Object Storage and Blob Storage and Content Delivery Networks (CDN).
8) Profile timelines and search#
- Profile (user) timeline: a range query on the Posts store's
(authorId, postId desc)index, plus a small cache for popular profiles. This same read serves the celebrity pull in the hybrid model. - Search: a separate Search Indexer consumes
PostCreated,PostEditedandPostDeletedevents and writes to an inverted index (Elasticsearch or a custom Lucene-based system). Queries scatter to all index shards, and the results are gathered, merged and ranked. Search is eventually consistent, typically within seconds. See Elasticsearch and Search Systems. The search deep dive below goes further.
The full high-level design#
The diagram is split into the write side and the read side so each stays readable.
Write side: posting and fan-out
Read side: serving the feed
Components:
- API gateway: TLS termination, authentication, per-user and per-IP rate limits, routing. See Load Balancing.
- Post Service: validates and stores posts, assigns time-ordered ids and emits events through an outbox.
- Posts store: the source of truth for posts, partitioned by post id with an author index. It is a sharded wide-column or relational store.
- Graph Service and store: follow edges in both directions, cached heavily. It answers followers-of and following-of queries, paginated for huge accounts.
- Kafka: the durable event backbone. Post events are partitioned by author id so one author's events stay ordered. See Apache Kafka in Practice.
- Fan-out Service and workers: turn one post event into many feed inserts, skip celebrities and inactive users, and work in chunks with retries.
- Feed cache: Redis clusters holding a capped, id-only list per active user, replicated and sharded by user id. See Redis in Practice.
- Feed Service: reads the precomputed feed, pulls celebrity posts, merges, optionally ranks, hydrates, filters and paginates.
- Post cache and User cache: large Memcached or Redis fleets with hot-key protection.
- Media pipeline, object storage and CDN: handle all bytes outside the request path.
- Search Indexer and search cluster: a near-real-time inverted index over public posts.
- Notification Service: sends push notifications to followers who turned them on for an account. It is the notification system case study, reused.
Key Flows#
Flow 1: Creating a post and fanning it out#
- The client sends the post with a
clientRequestId. A retry after a network timeout returns the samepostIdinstead of creating a duplicate. - The Post Service validates the post, assigns a time-ordered id and writes the post and an outbox row in one transaction. Either both exist or neither does.
- The API responds as soon as the post is durable, typically in 50–200 ms. The author's client immediately inserts the new post at the top of their own feed (optimistic UI), and the server also gives read-your-writes for the author (see deep dive 5).
- A relay (or CDC on the database log) publishes
PostCreatedto Kafka, partitioned by author id so one author's create, edit and delete events stay in order. - Fan-out workers read the event. They page through the author's follower list in chunks of about 1,000 and drop followers who are inactive (no visit in 30 days) or have muted the author. If the author is above the celebrity threshold, they skip the fan-out entirely.
- For each follower, the worker adds the post id to
feed:{followerId}with the post id as its score (ZADDin Redis), then trims the set to its cap. Writes are pipelined: one round trip per batch of followers on the same shard, not one per follower. - Offsets are committed only after the work is done. A crash means some inserts are repeated, which is harmless because
ZADDof an existing member is idempotent.
For a typical author with 200 followers, the whole fan-out finishes in well under a second. For an author with 50k followers it is 50 chunks processed in parallel, which takes seconds. That is comfortably inside the one-minute freshness target.
Flow 2: Reading the home feed#
- The Feed Service reads the top candidate ids from the precomputed feed, one O(log n + k) sorted-set range read.
- In parallel, it reads the short list of high-follower accounts this user follows, then their recent post ids from the author timeline cache. These keys are shared by millions of readers and are almost always hot.
- It merges the two id lists. Post ids are time-ordered, so a chronological merge is a simple comparison of ids. It removes duplicates (a post that was both pushed and pulled) and filters out muted or blocked authors.
- For a ranked feed, the ranker scores the candidates (deep dive 7). For a chronological feed this step is skipped.
- It hydrates the top 20 with batched multi-gets, drops anything deleted, made private or removed since it was fanned out, and tops up from the next candidates if filtering removed too many.
- It returns the page with an opaque cursor that encodes where to continue.
Typical latency budget: feed cache read 1–2 ms, celebrity pull 2–5 ms, ranking 10–50 ms when used, hydration 3–10 ms, plus network and serialisation. That is about 30–100 ms at p50, leaving plenty of headroom under a 500 ms p99.
Flow 3: A feed miss (inactive user returns)#
When a user who has not opened the app for months comes back, there is no feed:{userId} key, because we stopped maintaining it (deep dive 3). The Feed Service then:
- Detects the miss and returns a feed built on read. It gets the user's followees, fetches each one's recent posts (bounded: for example, only the last 7 days and at most 20 per followee), merges them and serves the first page. This may take 200–800 ms, which is acceptable once.
- Asynchronously rebuilds the precomputed list from that merge and marks the user active again, so fan-out resumes and the next open is fast.
- To avoid a thundering herd when many dormant users return at once (for example after a marketing email), rebuilds go through a rate-limited queue, and a per-user lock ensures only one rebuild runs per user.
Flow 4: Following and unfollowing#
- The client calls
PUT /v1/users/B/follow. The Graph Service writes the edge(A follows B)to thefollowingtable synchronously, so A's client can show "Following" at once and a retry is a harmless no-op. - The reverse edge
(B is followed by A)is written in the same transaction where the store supports it, or via an event otherwise. B's follower counter is incremented through a sharded counter, so a celebrity gaining thousands of followers a minute does not create one hot row. - A
FollowCreatedevent triggers a backfill for A. If B is a normal account, the worker reads B's most recent posts (say the last 10 from the last 3 days) fromauthor_tl:Band adds their ids tofeed:A. Because ids are time-ordered, they slot into the right positions, not on top. If B is above the celebrity threshold, the worker instead adds B tocelebs_followed:A, and B's posts appear through the read-time pull from then on. - A's next feed request shows B's posts. If the backfill has not finished, the follow still takes effect on the following refresh, well inside the freshness target.
- On unfollow, the Graph Service deletes both edges and removes B from
celebs_followed:Aif present. Entries from B already infeed:Aare not deleted one by one. The Feed Service filters out authors A no longer follows during merge (it has A's following set cached), and those entries age out of the capped list. This keeps unfollow O(1) instead of a scan of A's feed. - A block works like an unfollow in both directions, plus a hard visibility rule. The Feed Service and the search broker drop the blocked user's posts during hydration, so a block takes effect on the very next page even though stale ids may still sit in caches.
The pattern is the same as everywhere else in this design: make the source-of-truth write small and synchronous, do the derived work asynchronously, and let read-time filtering cover the gap between the two.
Data Model#
Choosing stores. Each entity has a different access pattern, so each gets a fitting store. See Choosing a Database: A Decision Guide.
| Data | Access pattern | Store | Why |
|---|---|---|---|
| Posts | get by id; list by author, newest first | Cassandra, DynamoDB or sharded MySQL | Huge, append-mostly, simple keys, horizontal scale |
| Follow edges | list following of X; list followers of Y, paged | Same store, two tables or table plus GSI | One-hop adjacency lists; no graph traversal needed |
| Precomputed feeds | read top N; insert; trim | Redis sorted sets or lists | Sub-ms reads, tiny entries, rebuildable |
| Post and user cache | multi-get by id | Memcached or Redis | Read-heavy, hot keys |
| Counters | increment; read approximate | Sharded counters in Redis plus a durable store | Very write-hot |
| Media bytes | put once, read via CDN | Object storage | Cheap, durable, CDN-friendly |
| Search index | term to posts, time-sorted | Elasticsearch or a custom Lucene system | Inverted index |
Keys and indexes
posts: partition keypost_id. A second table or indexposts_by_authorhas partition keyauthor_idand clustering keypost_id DESC. In Cassandra, very prolific authors' partitions are bucketed by month ((author_id, yyyymm)) so no partition grows without bound.following: partition keyfollower_id, clustering keyfollowee_id.followers: partition keyfollowee_id, clustering keyfollower_id. Both are written in one logged batch (Cassandra) or a single-table transaction (DynamoDB). A reconciliation job fixes rare divergence.- For celebrity accounts the
followerspartition has 100M rows. It is paged by the fan-out and notification jobs and never read in one go. Some designs split it into sub-partitions ((followee_id, bucket)) so it spreads across nodes. feed:{user_id}: a Redis sorted set with member = post id (with the author id packed into the member or kept in a parallel hash) and score = post id (time) for chronological feeds. Capped at about 800 entries.celebs_followed:{user_id}: a small Redis set of high-follower accounts this user follows, used for the read-time pull.author_tl:{author_id}: a cached list of each author's most recent post ids (say 100), used for profiles and the celebrity pull.
Retention
- Posts: kept forever unless deleted. Deletes are soft first (tombstone, hidden at once), then hard-deleted after a grace period, including derived copies in caches, search and backups within the legal deadline.
- Feed cache: only for users active in the last ~30 days. Entries older than the cap are trimmed, and deeper scrolling falls back to fan-out on read.
- Engagement events: raw events go to the data lake for ranking training with a limited retention (for example 90 days to 2 years, depending on privacy policy). Aggregates live longer.
- Media: kept while the post exists. Renditions that are rarely viewed may move to cheaper storage tiers.
Deep Dives#
1) Fan-out on write or fan-out on read: how do we choose?#
This is the central decision, so it is worth being precise about costs.
Basic: Pure fan-out on read. Every feed request queries every followee's recent posts and merges them. It needs no extra storage and is always fresh, but read cost grows with the number of follows. Its latency is set by the slowest of hundreds of partition reads. It suits a small product, an enterprise tool where everyone follows a few dozen accounts, or a cold-start feed.
Better: Pure fan-out on write. Each post is pushed into every follower's precomputed feed, and a read is one key lookup. Read cost is constant. Write cost is proportional to follower count, and it fails for celebrities and wastes work on inactive users.
Best: A hybrid that chooses per author (and sometimes per reader):
- Push for normal authors to active followers.
- Pull for high-follower authors, and for inactive readers when they return.
- Bound everything with caps: feed length, followees fetched on read and posts per followee.
A cost model. Let P be posts per second, F the average active followers per post, R feed reads per second and K the average number of followees whose posts must be fetched on read.
- Fan-out on write costs about
P × Fcache inserts per second plusRsingle-key reads. - Fan-out on read costs about
R × Kpartition reads per second.
With P = 6k, F = 100 (active only), R = 116k and K = 200, push costs 600k cheap inserts per second, while pull costs 23M partition reads per second. Push wins by a wide margin. But one author with F = 100M posting once a minute adds about 1.7M inserts per second by themselves. For that author, pull costs nothing at write time and only one shared, hot cache read per follower read. The hybrid takes the cheaper side for each author. Whether an author is "big" follows from this arithmetic, not from a fixed rule.
Why the threshold is tunable. Lower the threshold and more authors are pulled. That reduces write load and cache memory, but adds merge work on reads. Raise it and reads are simpler, but write bursts are larger. Teams measure the p99 read latency and the fan-out lag, then move the threshold until both are within target. Some designs even make it dynamic: when fan-out lag grows during an event, temporarily treat more authors as "pull" until the backlog drains.
When not to fan out at all. Some feeds are not built from follows: "For You" or explore feeds come mainly from recommendation candidates, not from a follow graph. They are computed at read time from candidate sources (deep dive 7). Fan-out still matters for the "Following" tab.
2) How do we handle accounts with millions of followers (the celebrity problem)?#
A post from an account with 100M followers is the single most dangerous write in the system.
Basic: Fan out normally. A 100M-follower post becomes 100M inserts. At 1M inserts per second for the whole fleet, that is 100 seconds of total capacity for one post. Queues behind it stall, and ordinary posts arrive minutes late. Primer-style designs call out the related race condition: replies to the celebrity's post may reach some followers' feeds before the original post, so the serving layer must re-order by id.
Better: Fan out asynchronously with priority and chunking. Split a big post into tasks of 1,000–10,000 followers, process many in parallel, and put chunks for ordinary authors in a separate higher-priority queue so they never wait behind a celebrity. This keeps ordinary users fresh, but still spends the full write cost and still fills 100M feed lists, most of which belong to people who will not read them.
Best: Do not fan out for high-follower accounts. Merge their posts at read time:
on read(user):
pushed = FEEDCACHE.zrevrange("feed:"+user, 0, 199) # ids
celebs = CACHE.smembers("celebs_followed:"+user) # small set
pulled = []
for a in celebs: pulled += CACHE.lrange("author_tl:"+a, 0, 19) # hot keys
cands = merge_by_id_desc(pushed, pulled) # k-way merge, dedupe
return rank_or_take(cands, 20)Details that make this robust:
- Keep the celebrity list short and local. Store
celebs_followed:{user}, maintained when the user follows or unfollows a high-follower account, and updated when an account crosses the threshold. Without it, the Feed Service would scan the whole follow list on every read. - Cache author timelines aggressively and redundantly. The celebrity's
author_tlkey is read by millions of users per minute, which makes it a hot key. Replicate it (deep dive 4), and serve it from an in-process cache on every Feed Service host with a 1–5 second TTL. A single host may serve thousands of reads per second for the same key, so even a 1-second local cache turns them into one remote read per host per second. - Bound the merge. If someone follows 300 high-follower accounts (some power users do), cap the pull at the most recently active 50–100 and accept that the rest appear a little later via other paths. Alternatively, raise the threshold for that reader.
- Followers who want notifications ("bell" subscribers) get them through the notification system, which fans out only to the subset who opted in, often a few percent of followers.
Edge cases.
- Mid-tier accounts (100k to 1M followers) can be handled either way. Many systems push to the followers who were active recently and let everyone else pull on next open.
- A celebrity replying to a normal user's post: the reply belongs to the celebrity, so it is pulled, but the conversation ranking may need the parent post. Hydration fetches it.
- Retweets or reposts of a celebrity's post by normal users are fanned out normally. The repost is a small item that references the original.
3) How do we store and cache the precomputed feeds?#
Basic: Store feeds as rows in a database table, feed_items(owner_id, post_id), written by fan-out and read with a range query. It is durable, but tens of billions of writes a day to a disk-based store are expensive, and they are not needed: the feed is derived data.
Better: Keep feeds in Redis, one key per user, holding only ids. Use a list (LPUSH + LTRIM) for strictly chronological feeds, or a sorted set (ZADD + ZREMRANGEBYRANK) when we need idempotent inserts and ordering by id or score. Shard by user id across a cluster and replicate each shard. A read is one key, one shard and one round trip.
Best: Treat the feed cache as a bounded, rebuildable index:
- Cap each feed. Keep 500–800 entries. Almost nobody scrolls further, and deeper pages are served by fan-out on read (deep dive 6).
- Store tiny entries. Each entry holds the post id, the author id and a few flag bits (is it a reply, is it a repost, does it have media), so the Feed Service can filter without hydration. At about 20 B per entry and 800 entries, that is 16 KB per user.
- Only active users. Maintain feeds only for users seen in the last N days (for example 30). Fan-out workers check a compact "active users" set first, such as a bitmap or a Bloom filter (see Probabilistic Data Structures for Big Data), and skip the rest. When a dormant user returns, rebuild on read (Flow 3). With 500M DAU out of 2B users, this alone cuts fan-out volume and memory in half or more.
- Compact encodings. Redis stores small sorted sets and lists in a compact listpack encoding that uses far less memory than the general structure. Keep feeds below the encoding threshold, or build a custom store. At very large scale, operators do: Twitter ran its timelines on its own fork of Redis with memory-efficient list structures, and Facebook's feed backend (Multifeed) keeps recent activity in memory on many leaf servers and assembles feeds at read time, which is fan-out on read done with purpose-built in-memory indexes.
- Replication and failure. Replicate each shard (primary plus replicas). If a whole shard is lost, affected users fall back to fan-out on read while the shard is rebuilt from the Posts store and the Graph. No data is lost, because the feed is derived.
- Persistence is optional. Redis snapshots (RDB) or append-only files speed up restarts. Without them, a restart means a rebuild storm, which must be rate-limited.
Why not store full posts in the feed? At 1 KB per post, 800 entries per user would be 800 KB per user, and 800 TB for 1B users. Worse, every edit, delete or counter change would need updating in millions of copies. Ids plus a shared post cache store each post exactly once in memory, and edits update one key.
Sizing example. 1B active feeds × 800 entries × 20 B = 16 TB of payload. With about 2× overhead for encoding and keys, that is 32 TB. With one replica, 64 TB. At 100 GB usable per node, that is about 640 nodes, which could be cut by half with a 400-entry cap. Each node handles about 100k operations per second, so 640 nodes give about 64M operations per second: plenty for 600k inserts and 300k reads per second, even with pipelining inefficiencies.
4) How do we handle millions of concurrent reads of the same post?#
The feed lists are spread evenly across users, but post bodies are not. A viral post, or any post by a celebrity, is hydrated by every one of millions of feeds that contain it. One key in the post cache receives a large share of all traffic.
Basic: A distributed post cache in front of the Posts store, keyed by post id, with a long TTL (posts rarely change) and LRU eviction, invalidated on edit or delete. Hit rates above 99% are normal, so the Posts store barely sees reads. But a cache key lives on one shard. A single Redis or Memcached node serves perhaps 100k–1M simple reads per second, which is enough for most keys but not for a post being read 2M times a second during a global event. The shard holding it melts, and so do all the other posts on that shard. This is a classic hot key. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
Better: Replicate hot keys. Run N copies of the post cache (or N replicas per shard), and spread reads randomly across them. A key now gets N times the throughput. The cost is N cache misses instead of one when the key is first loaded or after invalidation, and N copies to invalidate on edit. Since edits are rare and reads massive, that trade is usually worth it for the whole post cache, not only hot keys. Another variant is to suffix hot keys (post:123#0 to post:123#7). Readers pick a random suffix, so each copy hashes to a different shard. This is applied only to keys that a detector flags as hot.
Best: Layer the defences:
- In-process (near) cache on each Feed Service host: a small LRU of the hottest few thousand posts with a 1–5 second TTL. A host serving 5k feed requests per second that all contain the same viral post makes one remote read per TTL instead of 5k. With 2,000 hosts and a 2-second TTL, the remote cache sees only about 1,000 reads per second for that key.
- Hot-key detection: sample keys in the cache client or proxy (for example with a count-min sketch or a top-k sketch), and promote keys above a threshold to the near cache and to replicated copies automatically.
- Request coalescing (single-flight): when many requests on one host miss the same key at the same moment, only one goes to the backend. The others wait for its answer. This prevents a stampede when a hot key expires.
- Split mutable counters from the post body. The like count of a viral post changes thousands of times a second. If it were part of the cached post object, every like would invalidate the object. Keep counters in a separate, approximately consistent counter service (sharded counters summed on read, or a periodically flushed in-memory aggregate) and cache the immutable body for a long time.
This is the same playbook as in Pattern: Scaling Reads: cache, replicate the hottest data, push copies close to the reader, and never let many identical requests reach the same backend at once.
5) How do we make edits, deletes and new posts visible quickly enough?#
Most of the feed tolerates a minute of staleness. Some things do not:
- the author must see their own new post immediately (read-your-writes),
- a deleted post must disappear everywhere quickly, especially if it was posted by mistake or is harmful,
- an edit should show the new text, and blocking someone must hide their posts at once.
Basic: Rely on TTL expiry. Caches eventually serve the new version. That is too slow for deletes and confusing for the author ("where is my post?").
Better: Invalidate on write. Edits and deletes go to the Posts store, then a PostEdited or PostDeleted event deletes or overwrites the post's cache key (and its replicas and suffixes). Hydration always checks the post's state, so a deleted post that is still in millions of feed lists is simply skipped when read. There is no need to remove it from every list. Near caches still hold stale copies for their few-second TTL, which is usually acceptable.
Best: Combine several mechanisms, each for the case it fits:
- Read-your-writes for the author. Right after posting, the client adds the post to the top of its own feed (optimistic UI). On the server, the Feed Service merges the author's own most recent posts from
author_tl:{self}(or a short-lived "recent writes" key) into the feed for the next few minutes. Fan-out lag never hides the author's own post. Routing the author's next reads to the primary region (or to the leader replica) avoids replica-lag surprises. See Database Replication. - Versioned cache entries. Store a version (or the
edited_attime) with each cached post. Invalidation messages carry the new version, and a cache only accepts a set if the version is newer. This prevents a delayed old write from overwriting a newer value, which is a classic race in cache-aside. - Broadcast invalidation for near caches. Publish delete and edit events on a pub/sub channel that every Feed Service host subscribes to, so in-process copies are dropped within a second instead of waiting for their TTL.
- Tombstones. A delete writes a tombstone (deleted flag) into the post cache instead of removing the key. Readers see "deleted" as a cache hit and skip the post, without a miss stampede on the store.
- Visibility checks at read time. Blocks, mutes and privacy changes are evaluated during hydration against the viewer's current relationship data, cached per viewer with short TTLs. Correctness then never depends on cleaning up millions of feed lists.
The trade-off is deliberate. We do not try to keep all feed lists strongly consistent. Lists are allowed to contain stale or dead ids, and read-time filtering turns them into a correct page. See Cache Eviction and Invalidation.
6) How do we paginate an infinite feed correctly?#
New posts land at the top of the feed all the time, and ranked feeds re-order. Page numbers break immediately: if 5 new posts arrive between page 1 and page 2, OFFSET 20 repeats 5 posts the user already saw.
Basic: Offset pagination (?page=2). It is simple, but it shows duplicates and gaps whenever items are inserted, and deep offsets are expensive in most stores.
Better: Cursor (keyset) pagination on the time-ordered id. The cursor says "posts older than id X". The next page is ZREVRANGEBYSCORE feed:{u} (X -inf LIMIT 0 20 in Redis, or WHERE post_id < X ORDER BY post_id DESC LIMIT 20 in a store. Insertions at the top never shift the next page, so it is stable and cheap at any depth. Fetching newer posts uses the id of the top item: post_id > top. This powers "N new posts" and pull-to-refresh.
Best: Handle the cases that keyset alone does not:
- Deep pages beyond the cache cap. When the cursor goes below the oldest id in
feed:{u}(about 800 entries deep), switch to fan-out on read for older content, bounded by a time window. This is the core idea of the whole design: precompute the common case and compute the rare case on demand. - Ranked feeds. Scores change between requests, so "score < X" is not stable. Instead, when the session starts, rank a candidate set (say 500 items), store the ordered list under a short-lived session key (
feedsession:{u}:{sid}with a 30-minute TTL), and let the cursor be(sid, offset). All pages come from one frozen ranking, so there are no repeats or gaps. If the session expires, rank again and skip already-seen ids, which are tracked in a small seen-set (or Bloom filter) per session. - Merging pushed and pulled sources. The cursor must remember the position in both sources. With time-ordered ids, one boundary id works for both. For ranked mixes, the frozen session list solves it.
- Filtering removes items. If 3 of 20 hydrated posts are deleted, fetch more candidates before returning, so pages are not mysteriously short. Use
hasMorerather than "fewer than 20" to signal the end. - Signed opaque cursors. Encode the cursor as base64 JSON with an HMAC, so clients cannot forge one (for example to read past a privacy boundary) and the format can evolve.
cursor (chronological) = sign({ v:1, before: 1849302837461245952 })
cursor (ranked) = sign({ v:2, sid: "s_9f2", off: 40 })7) How do we rank the feed instead of showing it chronologically?#
A chronological feed is simple, predictable and easy to reason about, and many users want it. Most large products also offer a ranked feed, because when a user follows hundreds of accounts, the most interesting posts are often not the newest ones. Facebook's News Feed has been ranked for over a decade, and Instagram moved from chronological to ranked in 2016. X offers both a ranked "For You" tab and a chronological "Following" tab.
Basic: A hand-written score, for example:
score = w1 * affinity(viewer, author) # how often viewer engages with author
+ w2 * log(1 + likes + 2*replies + 3*reposts)
+ w3 * has_media
- w4 * hours_since_posted # time decayIt is cheap and explainable, but the weights are guesses and it cannot learn what each user likes.
Better: A two-stage pipeline:
- Candidate generation: gather a few hundred to a few thousand candidates. They come from the pushed feed, the celebrity pull and possibly out-of-network sources (posts liked by people you follow, topic-based recommendations, embeddings-based nearest neighbours; see Vector Databases and Similarity Search).
- Ranking: score each candidate with a trained model that predicts the probability of engagement events (like, reply, repost, dwell over 10 seconds, hide or report). Combine the predictions into one value score with business weights.
Best: A full multi-stage ranking system, as used in large feeds:
- Light ranker: a small model (logistic regression or a small tree ensemble) over cheap features, cutting thousands of candidates to hundreds in a few milliseconds.
- Feature hydration: fetch features from an online feature store. These include the viewer's affinity to the author, the author's recent engagement rate, the post's age and early engagement velocity, the viewer's device and time of day. See ML System Design and Feature Stores.
- Heavy ranker: a neural network that predicts several outcomes at once (multi-task). The final score is a weighted sum, with negative weights for "hide", "report" and "unfollow". X's open-sourced recommendation algorithm (2023) described exactly this structure: candidate sources, a light ranker and a neural heavy ranker that predicts many engagement probabilities, followed by heuristic filters. The accompanying engineering post said the pipeline gathers about 1,500 candidates per request, runs about 5 billion times a day and completes in under 1.5 seconds on average.
- Re-ranking heuristics: cap posts per author in a page, mix media types, enforce freshness, insert ads at fixed slots, and remove near-duplicates.
- Feedback loop: impressions and actions stream back through Kafka to update features in near real time (for example a post's engagement velocity) and to train models daily. See Batch vs Stream Processing.
Trade-offs and pitfalls.
- Latency: ranking is often the largest piece of the read budget. Bound it by candidate count and model size, cache scores per session and degrade to chronological order if the ranker times out.
- Feedback loops and fairness: ranking optimised purely for clicks can amplify outrage or clickbait. Production teams measure long-term metrics (retention, survey-reported value) and apply integrity demotions.
- Explainability and user control: offer a chronological option and "why am I seeing this" explanations. In some jurisdictions, such as the EU's Digital Services Act for very large platforms, a non-profiled option is required.
- Position bias: users click items at the top more, so training data is biased. Corrections include randomised exploration slots and inverse-propensity weighting.
8) How are photos and videos handled?#
Media is most of the bytes and most of the user-visible latency, so it gets its own pipeline.
Basic: Upload media to the API server, which stores it on its disk or in the database and serves it back. This fails at once: API servers fill up, large uploads tie up request threads, and there is no caching near users.
Better: Direct-to-object-storage uploads with pre-signed URLs, then serve through a CDN. The API only issues the URL and records the media id. For large videos, use multipart, resumable uploads (for example S3 multipart or a tus-style protocol) so a dropped mobile connection does not restart a 300 MB upload.
Best: An asynchronous media pipeline with states:
- Post before media is ready. The user may publish while a video is still processing. The post is stored at once, fan-out proceeds, and the client shows a "processing" placeholder until
Ready. Alternatively the post is held back from fan-out until media is ready, which is simpler for readers but slower for authors. - Renditions. Images are resized to a few widths (for example 150, 640 and 1080 px) and encoded as WebP or AVIF with a JPEG fallback. Videos are transcoded to adaptive streaming (HLS or DASH) at several bitrates, plus a poster frame. Clients pick the size that fits the screen, which saves bandwidth.
- Content-addressed storage. Name objects by a hash of their content, so identical uploads (a meme shared by thousands) are stored once, and CDN caching is perfect because the object never changes at that URL.
- CDN behaviour. Media URLs are immutable, so they get
Cache-Control: max-ageof a year. Popular media is served from edge caches with hit rates above 95%. Private-account media uses signed, short-lived URLs. - Feed impact. The feed API returns media metadata (dimensions, a blurhash or tiny placeholder, rendition URLs) but never bytes. The client lazy-loads media as items scroll into view and prefetches the next few.
9) How do profile timelines and post search work?#
Profile timeline. This is the simplest read in the system: "posts by author A, newest first". It is a range query on posts_by_author with a cursor (post_id < X). Popular profiles are cached as author_tl:{author} (the latest ~100 ids), and that cache key doubles as the source for the celebrity pull. The one wrinkle is very prolific accounts (bots, news wires), whose partitions grow huge. Bucketing by time ((author_id, month)) keeps partitions bounded, and the cursor walks buckets backwards.
Search answers "posts containing world cup, newest or most relevant first", over billions of posts, with new posts searchable within seconds.
Basic: SELECT … WHERE text LIKE '%world cup%'. This is a full scan, hopeless beyond a few million rows.
Better: An inverted index: for each term, a posting list of the post ids that contain it. A query intersects posting lists. Posts flow from Kafka into an indexer that does the text processing:
- tokenise (split into words, treating hashtags, mentions and URLs as special tokens),
- strip markup,
- normalise case and Unicode,
- optionally stem and remove stop words,
- handle languages that do not use spaces (CJK segmentation).
Elasticsearch or OpenSearch with time-based indices (one index per day, so old indices can be merged, frozen or dropped) is the common off-the-shelf choice.
Best: A search tier designed for recency:
- Partition by time first. Most queries want recent posts. Recent shards (the last day or week) live in memory on many replicas. Older shards live on SSD with fewer replicas, and the oldest form an archive tier. A query searches the newest partitions first and stops early once it has enough good results.
- Scatter-gather within a partition. Each time partition is split into shards by post id. A query goes to all shards of the relevant partitions. Each shard returns its top-k, and a broker merges them, ranks them and returns one page. Tail latency is controlled with replicas and hedged requests. See Elasticsearch and Search Systems.
- Near-real-time ingest. New posts go into an in-memory segment that is searchable within seconds. Twitter described its real-time search engine, Earlybird (Busch et al., "Earlybird: Real-Time Search at Twitter", ICDE 2012), as an inverted index optimised for exactly this: posting lists appended in time order in memory, with concurrent readers and a single writer per segment.
- Ranking search results: mix text relevance (BM25), recency, author quality and engagement. Popular queries (trending topics) are cached for a few seconds.
- Deletes and visibility. A delete event marks the id as deleted in each shard (a deletion bitmap). Visibility filtering (blocks, private accounts) runs on the broker during hydration, just like the feed.
- Query processing: the same normalisation as indexing, plus spelling correction and boolean operators (
AND,OR,-word,from:user).
Search load is modest in requests (thousands per second) but heavy per request, because every query touches many shards. So the search cluster is sized by shard fan-out × QPS, not by QPS alone.
10) How do we store and serve the follow graph at this scale?#
Basic: One relational table follows(follower_id, followee_id) with indexes on both columns. It is fine for millions of edges, but 400B edges do not fit one database, and the index on followee_id gets hot for celebrities.
Better: Shard two adjacency tables by their partition key: following by follower id, followers by followee id. Both are written on every follow. Each query is a single-partition range read. Cache the following lists of active users (a few hundred ids each, read on every feed miss and by the ranker) in the same cache tier.
Best: A dedicated graph service with:
- Write path: follow writes go to
followingsynchronously (the user must see "Following" at once) and tofollowersvia an event, either asynchronously or in the same transaction where the store supports it. Counters (follower_count) are updated through sharded counters, because a celebrity gaining 50k followers a minute would make a single counter row very hot. - Huge partitions: the 100M-row followers list of a celebrity is split into buckets across nodes. Fan-out and notification jobs scan it in pages with a cursor, in parallel per bucket.
- Read caching: "whom does A follow" is cached per active user, invalidated on follow and unfollow. "Does A follow B?" (needed for privacy checks) is answered by a membership lookup, optionally with a Bloom filter in front.
- Consistency: a follow followed quickly by an unfollow must not leave a ghost edge in one direction. Use per-edge versions (last write wins on the timestamp), and run a periodic reconciliation job that compares both directions.
- Mutual and second-degree queries ("followed by people you know") are answered offline by batch jobs, or by intersecting cached lists. A general graph database is rarely needed. Facebook's TAO (Bronson et al., "TAO: Facebook's Distributed Data Store for the Social Graph", USENIX ATC 2013) shows how far a cache over sharded MySQL with objects and associations goes. The social graph case study covers this in depth.
Product rules cap graph extremes on the following side: a 5,000-friend limit at Facebook, and follow-rate limits at X. These keep fan-out on read bounded for every user. There is no such cap on followers, which is why the celebrity strategy exists.
11) How do users learn about new posts in real time?#
Users expect a "12 new posts" pill while they scroll, and a push notification for accounts they care about.
Basic: Pull-to-refresh only. The user sees new posts only when they ask. It is cheap and simple, but feels stale.
Better: Poll a cheap endpoint every 30–60 seconds while the app is in the foreground: GET /feed/new?since=<topId>. The server counts ids greater than topId in feed:{u} (ZCOUNT, one O(log n) call) plus any newer celebrity posts, and returns a number. At 100M concurrent foreground sessions polling once a minute, that is about 1.7M small requests per second. They are cheap, but not free. Adaptive intervals (slower when the user is idle, faster during live events) and HTTP/2 connection reuse keep it manageable.
Best: Push over a persistent connection the app already has (WebSocket, SSE or the realtime channel used for chat and notifications). When a fan-out worker inserts into feed:{u} and the user is online, it publishes a small "new items" event to the user's connection gateway, which forwards it. The client shows the pill and fetches the actual items only when tapped. See Pattern: Pushing Realtime Updates and Polling, Long Polling, SSE, WebSockets and Webhooks.
- Batch and debounce pushes. Send at most one "new items" signal every few seconds per user. Never stream every insert.
- Celebrity posts are not fanned out, so they produce no per-follower insert. Their followers learn about them on the next poll or fetch, or through the notification system for subscribers.
- Push notifications (phone notifications) are a separate path.
PostCreatedgoes to the notification system, which looks up followers who enabled notifications for this author, applies rate limits and quiet hours, and sends through APNs or FCM. This is a much smaller fan-out, because few followers opt in. The notification system case study covers it. - Do not auto-insert items above what the user is reading. Shifting content under someone's thumb causes mis-taps. Prepend only when the user taps the pill or scrolls to the top.
12) How do we survive spikes, multiple regions and dormant users?#
Spikes. A goal in a World Cup final or the stroke of midnight on New Year's Eve can multiply the post rate several times within seconds, and the read rate with it. Twitter publicly reported a record of about 143,000 tweets per second in August 2013, during a TV broadcast in Japan, against an average of about 5,700 at the time.
Basic: Scale for the peak permanently. It is expensive, and peaks still surprise you.
Better: Let queues absorb write spikes. Posting stays fast because the API only writes the post and the event. Fan-out lag grows for a few minutes and then drains. Monitor fan-out lag (time from post to last feed insert) and consumer lag in Kafka, and autoscale workers on them. See Capacity Planning and Load Testing.
Best: Add explicit degradation modes:
- Temporarily lower the celebrity threshold, so more authors are pulled instead of pushed.
- Shrink fan-out to only followers active in the last few hours. Everyone else catches up when they open the app.
- Serve slightly stale feeds from cache without re-ranking, falling back to chronological order when the ranker is overloaded.
- Shed non-essential work (view counters, analytics, "who to follow" widgets) before feed reads.
- Pre-warm caches and add capacity ahead of known events (finals, elections, product launches).
See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
Multiple regions. Users everywhere need fast reads, and the service must survive a region loss.
- Run full read stacks (Feed Service, caches, Posts store replicas) in several regions. Route users to the nearest region with GeoDNS or anycast (see DNS: The Domain Name System).
- Posts are written in the author's home region and replicated asynchronously to the others, typically within a second. Fan-out runs in each region from the replicated event stream, so each region builds the feeds of the users it serves.
- Alternatively, fan-out runs once in the author's region and ships feed inserts to the reader's home region. This costs cross-region traffic but avoids duplicated work.
- Accept eventual consistency across regions. A follower in another region may see a post a second or two later. The author's read-your-writes is handled by pinning their reads to the home region for a short time after they post.
- If a region fails, users are routed to another. Their feed caches there may be cold or missing, so the fallback is fan-out on read, with rate-limited rebuilds. See Multi-Region and Global Data and Disaster Recovery and Backups.
Dormant users. Maintaining feeds for people who never come back wastes most of the fan-out budget.
- Keep an "active in the last 30 days" set, and skip fan-out to everyone else.
- Evict their
feed:{u}keys (a TTL of 30 days, refreshed on each read, does this automatically). - On return, build on read (Flow 3) and resume fan-out.
The cost is one slower first load, a few hundred milliseconds, for a returning user. The benefit is that memory and write volume scale with active users instead of registered users. For a product with 2B registered and 500M daily active users, that is the difference between paying for all four and paying for one.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Celebrity post fanned out to 100M feeds | Fan-out backlog; everyone's feed minutes late | Hybrid: no push above threshold, pull at read; separate priority queues for normal authors |
| Viral post hot key in post cache | One cache shard overloaded; neighbouring keys fail too | Near cache with short TTL, replicated or suffixed hot keys, single-flight, split counters from body |
| Fan-out workers lag during an event | Feeds stale beyond the 1-minute target | Autoscale on consumer lag, lower celebrity threshold, fan out only to recently active users |
| Feed cache shard lost | Affected users have no precomputed feed | Replicas with failover; fall back to fan-out on read; rate-limited rebuild from Posts and Graph |
| Mass return of dormant users | Rebuild storm on Posts store | Rebuild queue with rate limit, per-user lock, bounded on-read merge (time window, per-followee cap) |
| Dual write: post saved but event lost | Post never reaches followers | Transactional outbox or CDC; at-least-once events with idempotent feed inserts |
| Duplicate events or retries | Same post twice in a feed | Sorted-set inserts keyed by post id (idempotent); dedupe on merge by id |
| Deleted or blocked content still in feed lists | Harmful or unwanted posts shown | Read-time visibility filter, tombstones in post cache, broadcast invalidation to near caches |
| Ranker slow or down | Feed latency SLO missed | Strict timeout, fall back to chronological merge, cache session rankings |
| Huge followers partition for a celebrity | Hot partition in Graph store | Bucketed partitions, paged scans in parallel, sharded follower counters |
| Search shard slow | Search tail latency spikes | Replicas and hedged requests, time-partitioned shards, early termination on recent partitions |
| Region outage | Users lose feed access | Multi-region read stacks, GeoDNS failover, on-read fallback while caches warm, async post replication |
What Interviewers Expect#
Mid-level#
- Clarify requirements: follow vs friend, chronological feed, scale and freshness. Draw a correct basic design with a Post Service, a Graph (follow) store, a Feed Service and a cache.
- Explain fan-out on read vs fan-out on write and their costs, and choose precomputed feeds for read speed.
- Use time-ordered ids and cursor pagination instead of offsets.
- Put media in object storage behind a CDN.
Senior#
- Quantify fan-out (posts × followers), and explain why it is fine on average but terrible for celebrities. Propose the hybrid with a tunable threshold and a read-time merge.
- Store ids in the feed cache, not posts. Size it (entries × bytes × active users), cap it, and limit it to active users with on-read rebuilds.
- Make fan-out asynchronous with a durable queue, at-least-once delivery, idempotent inserts and chunking for big accounts. Solve the dual-write problem with an outbox or CDC.
- Handle hot posts with replicated caches, near caches and request coalescing.
- Handle deletes, edits and blocks with read-time filtering and invalidation. Give the author read-your-writes.
Staff+#
- Lead with the trade-off economics: push vs pull cost per author, cache memory per user, and how the threshold and active-user window move both. Propose dynamic degradation during spikes.
- Design ranking as a pipeline (candidates, light ranker, features, heavy ranker, re-rank), with latency budgets, fallbacks, frozen session rankings for stable pagination and feedback loops.
- Cover multi-region: where fan-out runs, replication lag, read-your-writes across regions and cold-cache failover.
- Discuss operations: fan-out lag and feed freshness SLOs, hot-key detection, rebuild storms, testing with production-like follower distributions, and integrity concerns (spam fan-out, ranking harms, user control such as a chronological option).
- Know where real systems differ. Twitter's precomputed Redis timelines are push-heavy. Facebook's Multifeed aggregates at read time from in-memory indexes. Explain why both can be right.
Deep Dive: The maths of feeds (fan-out, tail latency, caches and backlogs)Show
1. A second set of numbers (a Twitter-like product). A classic sizing exercise uses 100M active users, 500M posts a day, 250B timeline reads a month, 10B searches a month and an average fan-out of 10 deliveries per post, counting only active followers who are online-relevant. That gives:
- posts: 500M / 86,400 ≈ 6k per second,
- fan-out deliveries: 5B a day ≈ 60k inserts per second,
- timeline reads: 250B / 2.5M seconds ≈ 100k per second,
- searches: 10B / 2.5M ≈ 4k per second.
At about 10 KB per post (8 B id, 32 B user id, 140 B text and about 10 KB of media on average), new content is 500M × 10 KB ≈ 5 TB a day, about 150 TB a month and about 5.4 PB in three years. With a 16–20 B cache entry per delivery and several hundred entries per active user, the home-timeline cache is a few TB.
Notice how much the average fan-out assumption matters: 10 here versus 100–200 in our main estimate. Fan-out volume is linear in it, so it is the first number to pin down with the interviewer. Counting only active followers is the single biggest lever.
2. Why fan-out on read has terrible tail latency. Suppose each partition read has a 1% chance of being slower than its p99, say 50 ms. A feed request that reads N partitions in parallel is slow if any of them is slow. The chance that all N are fast is 0.99^N:
| N (followees read) | P(all fast) | P(at least one slow) |
|---|---|---|
| 10 | 0.904 | 9.6% |
| 100 | 0.366 | 63% |
| 300 | 0.049 | 95% |
| 1,000 | 0.00004 | ≈100% |
With 300 followees, 95% of requests are as slow as the slowest shard's p99. This is the "tail at scale" effect described by Dean and Barroso ("The Tail at Scale", Communications of the ACM, 2013). Their remedies are hedged requests and tied requests, and they help. But the real fix is to read one key instead of hundreds, which is exactly what a precomputed feed does.
3. Follower counts are heavy-tailed. Follower distributions on social networks are roughly power-law: most accounts have few followers and a tiny fraction have enormous counts. Kwak et al. ("What is Twitter, a Social Network or a News Media?", WWW 2010) measured this on the 2009 Twitter graph and found a follower distribution that is power-law-like over a wide range, with deviations for the very largest accounts. The consequence for fan-out: total fan-out work is dominated by a small number of authors. Suppose the top 0.01% of accounts by followers hold, say, 20% of all follower edges, and post as often as anyone else. Then excluding them from push removes about 20% of push volume, and much more of the burstiness, since each of their posts is a giant spike. Measure this on your own graph. It tells you where to set the threshold.
4. Draining a celebrity backlog (Little's law). If fan-out capacity is μ inserts per second, normal load is λ, and a burst of B extra inserts arrives (one celebrity post), the backlog drains in about B / (μ − λ). With μ = 1.5M/s, λ = 1M/s and B = 100M, the drain takes 100M / 0.5M = 200 seconds, during which every new post waits behind the backlog unless queues are separated. Little's law (L = λW) also gives the queue length at a given lag: at 1M inserts per second and 30 s of lag, about 30M inserts are queued. That is useful when sizing Kafka retention and worker memory.
5. Near-cache effectiveness. With H Feed Service hosts, each with a near-cache TTL of T seconds, the remote cache sees at most H / T reads per second for any single hot key, however many users read it. With H = 2,000 and T = 2 s, that is 1,000 reads per second, against perhaps millions of hydrations per second of the post. The cost is staleness: an edit may take up to T seconds to show (or less with broadcast invalidation).
6. Feed cache memory. Memory = active users × entries × bytes per entry × (1 + overhead) × replicas.
- 1B × 800 × 20 B × 2 × 2 = 64 TB.
- Halving entries to 400 halves it. So does restricting to 500M users active within 7 days.
- Each lever trades a slightly worse experience for rare cases (deep scrollers, returning users) for big cost savings. A useful habit is to compute the cost per user per month of the feed cache. For example, 64 TB of RAM at roughly $2–10 per GB per month (self-managed hardware at the low end, a managed cache service at the high end) is about $130k–640k a month, or well under a tenth of a cent per active user. Then compare it with what an extra 100 ms of latency would cost in engagement.
7. Write amplification of storing full posts in feeds. Storing a 1 KB post body in each of F feeds costs F KB per post instead of F × 20 B: a 50× increase. Every edit then touches F copies instead of one. With an average F of 100, that turns 500 GB a day of post data into 50 TB a day of feed writes. This is why every large design stores ids in feeds and hydrates from one shared copy.
Deep Dive: How real feed systems are builtShow
Only facts that the companies have published are summarised here. Details change over time, so treat this as the shape of the designs, not their current internals.
Twitter (X) home timelines. For years Twitter's home timeline was the textbook fan-out-on-write design. Engineering talks around 2012–2013 (Raffi Krikorian's "Timelines at Scale") described it:
- a post goes through a write API into a fan-out service,
- the service looks up followers in a social-graph service (FlockDB at the time),
- it inserts the tweet id into each follower's home timeline, kept in Redis clusters and replicated several times,
- each timeline holds only the last several hundred entries,
- timelines are maintained only for users active in the recent past, and rebuilt from the graph and the posts store for others.
High-follower accounts were not fanned out. Their tweets were merged in at read time, which is the hybrid described above. Search was a separate real-time system (Earlybird), fed from the same ingest. The 2023 open-source release of the "For You" recommendation pipeline shows the later evolution: candidate sources from in-network (people you follow) and out-of-network, a light ranker, a neural heavy ranker and filtering stages. That is fan-out on write for candidate supply plus heavy ranking at read time.
Facebook News Feed. Facebook's feed has been ranked since early on and assembles feeds largely at read time. Its Multifeed backend, as described in Facebook engineering talks, keeps each user's recent actions in memory on "leaf" servers. An "aggregator" queries the leaves for the actions of the viewer's friends and pages, ranks them and returns the feed. This is fan-out on read done at extreme efficiency: the data is in RAM, laid out for exactly this query, so hundreds of followee reads become a few parallel calls to leaves that each scan in memory. The social graph underneath is served by TAO, a graph-shaped cache over sharded MySQL (Bronson et al., USENIX ATC 2013). The lesson is that fan-out on read is not inherently slow. It is slow when every followee read is a disk-based database query.
Instagram. Instagram began with a chronological feed built on PostgreSQL, Redis and Django, and switched to a ranked feed in 2016. Its engineers have written about sharding PostgreSQL by user id with id generation inside the database (an id format with time bits, a shard id and a sequence, similar in spirit to Snowflake), and later about moving to Cassandra for parts of the feed and inbox data. The general shape is: precomputed or cached feed candidates, then ranking.
LinkedIn. LinkedIn's feed is ranked, and it mixes posts from connections, followed companies and creators, and recommended content. LinkedIn has published work on its follow feed infrastructure and on near-real-time ranking features. Its streaming stack (Kafka was created at LinkedIn) carries engagement events back to ranking.
What to take from this.
- Every large system is hybrid. The question is where the cut is: per author, per reader, per data tier or per stage.
- Ids in feeds, bodies in a shared cache is universal.
- Ranking moved from optional to central, but a chronological mode remains, both because users ask for it and because of regulation.
- The infrastructure you have shapes the choice. With fast in-memory per-user indexes (Multifeed), pull is cheap. With a general-purpose database, push wins for most authors.
Deep Dive: Evolving the design step by stepShow
A good way to present this design (and to build it) is as a sequence of bottlenecks found by measurement: benchmark, profile, fix the biggest bottleneck, repeat.
Stage 1: one database (thousands of users). A posts table, a follows table and a query that joins them, ordered by time, with LIMIT 20. Add indexes on (author_id, created_at) and follows(follower_id). This is simple and fully consistent, and correct for a startup. See Scaling from Zero to Millions of Users.
Stage 2: read replicas and caches (millions of users). Feed queries move to read replicas. Post and user objects are cached in Memcached or Redis. Media moves to object storage and a CDN. The feed query is still fan-out on read, but each piece is cached.
Stage 3: precomputed feeds (tens of millions). The join is now the bottleneck, with p99 dominated by users who follow many accounts. Introduce the event stream, the fan-out workers and per-user feed lists in Redis. Reads become one key plus hydration. Fan-out on read remains for deep pages and cold users.
Stage 4: the hybrid (hundreds of millions, with celebrities). Fan-out lag spikes whenever a big account posts. Add the celebrity threshold and the read-time merge. Separate queues by priority. Restrict fan-out to active users.
Stage 5: sharding everything. Posts, follows and feeds are each sharded by their natural key (post id, user id, owner id). Counters become sharded counters. Hot-key defences go into the cache client. The data layer uses the standard toolkit: replicas, federation (splitting by function, such as posts and users), sharding, denormalisation, query tuning, and moving the hottest access patterns to NoSQL stores. See Partitioning and Sharding and Pattern: Scaling Writes.
Stage 6: ranking and multi-region. Add candidate generation, feature stores and ranking models. Replicate posts across regions and fan out per region. Add degradation modes for global events.
At each stage, the trigger should be a measured problem (p99 latency, fan-out lag, cache memory, cost), not a guess. Interviewers like hearing what metric would push you to the next stage.
Deep Dive: Variants (news aggregator, groups, stories and enterprise feeds)Show
The same building blocks recombine for different feed products. Knowing how they change is what lets you handle "now design X" follow-ups.
A news aggregator (Google News style). Here the "authors" are a few thousand to a hundred thousand publishers, not hundreds of millions of users, and nobody "follows" in the social sense. The feed is a query over a shared pool of recent articles. The google-news case study covers this in full. The key differences:
- Ingest instead of posting. Crawlers and publisher feeds (RSS or Atom, sitemaps, publisher APIs) bring in new articles. The requirement is usually freshness within about 30 minutes of publication, so a crawl scheduler polls each source at a rate tuned to how often it publishes: big outlets every minute or two, small blogs every hour.
- Deduplication and clustering. The same story appears from hundreds of outlets. Near-duplicate detection (for example MinHash or SimHash signatures over article text) groups articles into story clusters, and the feed shows one cluster with several sources.
- Category and regional feeds (World, Business, Sports, per country) are shared by millions of readers. So they are precomputed and cached per category and region, refreshed every minute or so, and served from a CDN or an edge cache. This is fan-out on write to a few shared lists instead of to every user.
- Personalised feeds come from a ranking layer on top: candidate clusters from the user's interests and locality, scored by freshness, source quality, topical relevance and diversity.
- Infinite scroll with pagination consistency. Because the pool changes every minute, use a session snapshot: rank once, store the ordered list for the session, and page through it with a cursor (deep dive 6). This avoids duplicates as new stories arrive.
- Click-through. Articles open on the publisher's site. The aggregator records the click through a redirect endpoint (or a beacon) for ranking signals. It must be fast (a few milliseconds) and must not become an open redirect: only redirect to known article URLs.
- Breaking-news spikes. Traffic can jump many times within minutes. Shared category feeds cached at the edge with short TTLs (10–60 s) and request coalescing at the origin absorb this easily. Personalised feeds degrade to the cached category feed if the ranker is overloaded.
- Latency targets are often tighter (under 200 ms) because the pages are simple and highly cacheable.
- Media: thumbnails are fetched from publisher pages, resized and served from the aggregator's own CDN, which avoids hot-linking and gives control over size and format.
Groups, pages and communities (Facebook Groups, Reddit, Discord forums). Posts go to a container that members subscribe to.
- A community with 10M members is like a celebrity, so pull from the community's timeline at read time.
- Small private groups are fanned out to members.
- Reddit-style front pages are mostly ranked queries over communities (hot, new, top), cached per community and sort order. The reddit case study goes deeper.
Stories (ephemeral content). Content expires after 24 hours, the "tray" shows which followed accounts have new stories rather than every item, and the seen state matters.
- Store a per-viewer "tray" of authors with unseen stories, updated by fan-out (or pulled from a short author-to-latest-story-time map).
- Expire content with TTLs.
- Track "seen" per viewer in a compact structure (a set or bitmap of story ids seen in the last day).
Enterprise or small-network feeds (an internal company feed, or a team activity feed). Users follow tens of sources, so fan-out on read is perfectly adequate and simpler: no precomputed feeds, no celebrity logic, strong consistency for free. Naming this in an interview shows you pick designs by numbers rather than by habit.
Activity feeds (GitHub, Strava, "your friend liked X"). Events are aggregated before display ("Alice and 12 others liked your post"). Fan-out still applies, but entries are aggregation keys (post id + action type) whose counts update in place, plus rules for when to group and when to show items separately.
Chronological "Following" plus ranked "For You." Many products run both. The Following tab uses the pushed feed in id order and needs no ranker. The For You tab adds out-of-network candidates and the heavy ranker. Both share the same post cache, hydration, visibility filter and pagination machinery, so the second tab is mostly an extra candidate source and scoring stage.
Deep Dive: Operating, testing and securing the feedShow
Key metrics (SLOs). See Observability: Logs, Metrics and Traces.
- Feed read latency: p50 and p99 per region and per stage (feed cache, pull, ranking, hydration). Alert when p99 exceeds 500 ms for 5 minutes.
- Fan-out lag: time from post commit to the last feed insert, measured on a sample of posts by follower-count bucket. The target is p99 under 60 s for authors under the threshold. Publish synthetic "canary" posts from test accounts and measure when they appear in test followers' feeds. This end-to-end probe catches problems that per-component metrics miss.
- Feed freshness for readers: the age of the newest item served relative to the newest eligible item. This detects silently broken fan-out.
- Cache metrics: hit rate by tier (near, post cache, feed cache), evictions, memory per shard, and hot keys detected.
- Consumer lag in Kafka per partition, and dead-letter queue sizes.
- Product health: empty-feed rate (users served zero items), refresh rate, scroll depth and errors per screen.
Testing.
- Load tests with a realistic follower distribution. A uniform random graph hides the celebrity problem entirely. Generate graphs with heavy-tailed follower counts, and replay recorded production traffic shapes, including event spikes.
- Chaos and failure drills: kill a feed cache shard, delay the ranker, partition a region. Verify fallbacks (on-read feed, chronological order, cold-cache rebuild rate limits) actually engage.
- Consistency checks: a background job samples users, rebuilds their feed from the source of truth and compares it with the cached feed. Differences point to lost fan-out events or bad filtering.
- Shadow traffic and A/B tests for ranking changes, with guardrail metrics (latency, hides and reports) and long-term holdouts. See CI/CD and Deployment Strategies.
Security, abuse and privacy. See Security Fundamentals for System Design.
- Authorisation on every read: private accounts are visible only to approved followers. Check at hydration, not only at fan-out, because approvals and blocks change.
- Spam and fan-out abuse: bots that follow millions of accounts or post rapidly. Rate-limit posting and following per account and per device, detect follow-spam patterns, and quarantine fan-out for new or suspicious accounts until they are cleared by integrity systems.
- Content moderation: posts can be removed after fan-out. Read-time filtering and tombstones make removal take effect everywhere within seconds. Keep an audit trail.
- Deletion and data rights: a user deleting their account must have posts removed from feeds (filtered at once, purged from caches and indexes), search, backups and analytics within legal deadlines (for example GDPR's "without undue delay").
- Privacy in ranking: limit which signals are used, honour opt-outs, and avoid leaking private information through recommendations (for example, "people you may know" revealing a private contact).
Deep Dive: Inside the fan-out workersShow
The fan-out tier does the most write work in the system, so its internals decide both cost and freshness.
Task structure. A PostCreated event becomes a fan-out job. The job reads the author's follower list in pages of about 1,000 ids, and each page becomes a task. Tasks go to a work queue (a Kafka topic partitioned by a hash of the task, or SQS-style queues), so many workers share one big job. A small job (200 followers) is a single task, processed inline by the worker that read the event.
Grouping by shard. A task's 1,000 followers are spread across feed-cache shards. The worker groups them by the shard that owns each feed:{user} key and sends one pipelined batch per shard: ZADD plus ZREMRANGEBYRANK for each user, many commands in one round trip. With 200 cache shards, a 1,000-follower task becomes about 200 small pipelines, each taking a fraction of a millisecond on the server. Throughput is then bounded by the network and the cache CPU, not by round-trip latency. A Lua script (or a Redis function) can do "add then trim" atomically per key in one call.
Filters before writing. For each follower, the worker checks:
- Active? A bitmap or Bloom filter of users active in the last 30 days. Skip the rest.
- Muted the author, or muted a keyword in the post? These are small per-user sets, often cached. Skipping here saves memory, but the read-time filter remains the safety net.
- Feed key exists? If the user's feed was evicted, do not recreate a feed containing a single post. Let the next read rebuild it properly.
Ordering and races. Events from one author are ordered within their Kafka partition, so a delete never overtakes the matching create for the same author. But replies from other authors to a celebrity's post can reach a follower's feed before the original post does, because they travel through different partitions and different (push versus pull) paths. Time-ordered ids solve display order: the merge sorts by id. Hydration can also attach the parent post to a reply, so a reply never appears without context.
Back-pressure. If the feed cache is slow, workers must slow down instead of piling up retries. Use bounded in-flight requests per shard, circuit breakers per shard, and a retry topic with exponential backoff. Kafka retains the backlog durably, so slowing down loses nothing; it only adds lag. Lag is then a metric to alert on, not a failure.
Priorities. Separate topics (or weighted consumers) handle:
- interactive fan-out: normal authors, small jobs,
- bulk fan-out: big jobs from mid-tier accounts,
- repair work: rebuilds and backfills after a follow.
Interactive work is never starved by bulk work.
Exactly-once is not needed. The combination of at-least-once delivery and idempotent sorted-set inserts gives an effectively exactly-once result. A crashed worker's task is retried, and re-adding the same post ids changes nothing. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
Undo paths. Deletes and unfollows do not have to "un-fan-out". A delete is enforced at read time. An unfollow is filtered at read time and cleaned lazily: the next time the user's feed is rewritten or trimmed, entries from unfollowed authors are dropped. A full un-fan-out would cost as much as the original fan-out, for no visible benefit.
Rough worker sizing. At 600k inserts per second and about 50k pipelined inserts per second per worker core (including follower-list reads and filtering), that is about 12 cores in steady state. Add headroom for 5–10× spikes and for retries, and the fan-out fleet is a few hundred cores. That is small compared with the read tier, and it shows that the real cost of push is cache memory and shard throughput, not worker CPU.
Deep Dive: An alternative design with in-memory pullShow
Push-based feeds are the interview default, but a pull-based design can also meet the requirements if the "read the followees' recent posts" step is made extremely cheap. This is roughly the idea behind Facebook's Multifeed, and it is worth being able to sketch.
Idea. Instead of keeping one precomputed list per reader, keep one compact list of recent activity per author, in memory, on a fleet of index servers ("leaves"). Every leaf holds the recent posts of a subset of authors, for example the last few days. A feed request goes to an aggregator, which:
- loads the reader's followee list (from a graph cache),
- sends the followee ids to every leaf in parallel (or only to the leaves that own them),
- receives each leaf's matching recent post ids and their light features,
- merges and ranks them, then hydrates the top results.
Why it can be fast. Each leaf answers "recent posts for these 300 author ids" with in-memory lookups in microseconds. The cost is one parallel round trip to tens or hundreds of leaves, not hundreds of separate database queries. Tail latency is controlled with replicas of each leaf partition and hedged requests to the slowest.
Advantages.
- No write amplification. A post is written once per replica, whatever the follower count. There is no celebrity problem on the write side.
- Memory scales with posts, not with followers. Storing a week of posts once is smaller than storing hundreds of copies of each id in readers' lists.
- Changes take effect at once. A new follow, an unfollow or a ranking change applies on the very next request, with no backfill.
- Rich ranking is natural, because the aggregator sees all candidates with their features.
Disadvantages.
- Read cost is high per request. Every refresh does the full merge and ranking, so read-side compute and fan-in network traffic dominate. Caching the ranked result per session helps.
- Every request depends on many leaves, so availability engineering (replicas, partial results) is essential. Returning a feed missing one leaf's authors is usually better than an error.
- It is specialised infrastructure, harder to build than "Redis lists and workers".
When to choose it. When ranking quality is central and the feed is recomputed on every visit anyway, when follower counts are extreme, or when an organisation can invest in a custom in-memory index service. For most designs, and in most interviews, the hybrid push-pull design is the expected answer. Mentioning this alternative, and why a company might choose it, is a strong staff-level signal.
Production reference. Hashnode precomputes feeds only for active users with EventBridge, Lambda and Redis; see More Company Architectures. Meta's multi-pass feed ranking is in Meta's engineering lessons.
Key Takeaways#
- The feed is a cache of a query. Posts, users and follows are the source of truth. Precomputed feeds are derived, bounded and rebuildable, so they can live in memory and be trimmed freely. See Caching Fundamentals.
- Fan-out on write makes reads cheap but costs follower-count work per post. Fan-out on read is the reverse. Use the hybrid: push for normal authors to active followers, pull for celebrities (and for returning dormant users), merged at read time by time-ordered ids.
- Store ids, not posts, in feeds. Hydrate from a shared post cache with near caches, replicated hot keys and request coalescing for viral posts. See Distributed Caching with Redis and Memcached.
- Make fan-out asynchronous and idempotent. Use an outbox or CDC for reliable events, Kafka for the backbone, chunked tasks, priority queues and at-least-once delivery with idempotent inserts. See Pub/Sub and Event Streaming.
- Enforce correctness at read time. Deletes, edits, blocks, privacy and moderation are filtered during hydration. Read-your-writes is given to the author explicitly.
- Paginate with cursors. Use keyset cursors on time-ordered ids for chronological feeds and frozen session rankings for ranked feeds. Fall back to fan-out on read beyond the cache cap.
- Ranking is a pipeline: candidates, a light ranker, features, a heavy ranker and re-ranking, with strict latency budgets and a chronological fallback. See ML System Design and Feature Stores.
- Media and search are side pipelines. Media goes through pre-signed uploads, transcoding and a CDN. Search is a time-partitioned, near-real-time inverted index fed from the same event stream.
- Plan for spikes, regions and dormant users with queue-absorbed bursts, dynamic thresholds, per-region fan-out, on-read fallbacks and active-user-only feeds. See Pattern: Scaling Reads and Consistent Hashing.