19 min read
Designing Facebook News Feed
In this article, we design the News Feed for Facebook.
On this page
Requirements#
Functional#
- Create post
- Follow people
- View posts, latest first
- Infinite scrolling of feed
Non-functional#
- Like most social media apps, we shall prioritize availability over consistency.
- Latency should be low. Posting and fetching feed should be fast, with feed loads under a 500ms latency budget.
- Highly scalable system. Billions of users with unlimited followers and unlimited follows.
Core entities#
- User
- Post
- Follow, a many-to-many relation between two users
APIs#
POST /poststo create a new post.PUT /users/{userId}/followto follow the user with iduserId.DELETE /users/{userId}/followto unfollow the user with iduserId.
GET /feed?cursor={cursor}&pageSize={pageSize}cursoris an opaque value that marks where the previous page ended.- For example,
cursorcan be theb64encoding ofcreatedAt:lastPostId. - Every response returns the next
cursorvalue, which the client sends with the next request.
Architecture#
Creating posts#
To handle POST /posts, we start with a simple write path.
- API Gateway & Load Balancer: Routes incoming post requests to our backend service.
- Stateless Post Service: Horizontally scaled hosts that receive the request and write directly to the database. Because each host is stateless (and we aren’t handling reads or caching yet), we can scale up just by adding more servers.
- Cassandra (Posts table): A wide-column store, used here as a simple key-value store, chosen for its simplicity and high write throughput, as long as write load is spread evenly across its partitions.
Because a pure key-value store treats the value as an opaque blob, it has no way to index or filter by fields like location or #hashtag without scanning every single record. Since our News Feed requirements only need us to store and fetch posts by ID, we don’t need that extra overhead.
Sharding#
To spread data across multiple servers (we certainly can’t hold all the posts in a single server), the database needs a rule to decide which server stores which row. It does this using a Partition Key.
- You pick a field as the Partition Key (for example,
postId). - The database runs that key through a hash function (conceptually like
hash(postId) % totalServers). - The output tells the database the exact server (partition/shard) where that row lives.
We can minimize the remapping of data when we add or remove shards by using consistent hashing.
We will be using postId as the sharding key.
We shall have a similar problem with postId as the shard key: we can’t fetch the posts for a user by userId. We shall see what to do about this while reading posts.
flowchart LR
Client["Client"] -->|"POST /posts"| LB["API Gateway &<br/>Load Balancer"]
LB --> PS["Post Service<br/>(Stateless Hosts)"]
PS -->|"Write by postId"| DB[("Posts Table<br/>(Key-Value Store)<br/>PK: postId")]
Attachments#
If a user uploads a 50 MB video, routing that raw file through our API Gateway and Post Service ties up server connections and bandwidth. How can we let the client upload the file directly to S3 safely, without exposing public write access to our bucket, before calling POST /posts?
Pre-signed URLs solve this cleanly. By issuing a temporary, cryptographically signed URL scoped to a single object key, the client can upload directly to S3 without routing heavy binary traffic through our API servers.
- Request URL: The client asks the Post Service for an upload URL and receives a time-limited S3 pre-signed URL (e.g., valid for 5 minutes).
- Direct Upload: The client uploads the raw image or video directly to S3 via HTTP PUT.
- Create Post: Once the upload succeeds, the client calls
POST /postswith the post text and the S3 object key. - CDN Delivery: When followers load their feed, the client fetches the media directly from the CDN backed by S3.
Follow people#
To handle PUT /users/{userId}/follow (and DELETE for unfollows), we add a dedicated path alongside our Post Service:
- API Gateway & Load Balancer: Routes incoming follow/unfollow requests to the right service.
- Stateless Follow Service: Horizontally scaled hosts that process the request and write the edge to the database.
- Follow Table (Cassandra / DynamoDB): Stores each unidirectional relationship as a pair of
(followerId, followeeId).- Partition Key (
followerId): Tells the database which server/shard stores the data. - Sort Key (
followeeId): Uniquely identifies the exact record inside that partition and keeps rows sorted. Together, the pair forms the full primary key (which also naturally prevents duplicate follows).
- Partition Key (
Just like with the Posts table, how we choose our keys determines what queries are fast and what queries force a full table scan. For the Follow table, our system will eventually need to answer two different questions:
- Outbound: “Who are all the people a given user follows?”
- Inbound: “Who are all the followers of a given user?”
With followerId as the Partition Key, outbound queries (“Who does a given user follow?”) are fast because all of a user’s followees sit together on the same partition.
With followerId as our Partition Key, the database has no way to hash and route the request to a specific shard to answer the second question, “Who are all the followers of a given user?”. So looking up by followeeId alone would force a full scan across every shard.
Maintaining a reversed (followeeId, followerId) mapping is the pattern used in production.
Denormalized Table / Materialized View: In Cassandra, we typically create a second table (e.g., FollowersByUser) keyed by (followeeId, followerId) and write to both tables on every follow/unfollow.
From here on, we’ll call this reversed view the Follow GSI, whichever of the two implementations we use.
The tradeoff is extra storage and write amplification (every follow now updates two places). Because the secondary index or second table updates asynchronously, a newly added follower might take a brief moment to appear, which works cleanly with our eventual consistency requirement.
flowchart LR
Client["Client"] --> LB["API Gateway &<br/>Load Balancer"]
LB -->|"POST /posts"| PS["Post Service<br/>(Stateless Hosts)"]
PS -->|"Write by postId"| PostsDB[("Posts Table<br/>PK: postId")]
LB -->|"PUT /users/{userId}/follow"| FS["Follow Service<br/>(Stateless Hosts)"]
FS -->|"Write edge"| FollowDB[("Follow Table<br/>PK: followerId<br/>SK: followeeId")]
FollowDB -.->|"Async replication"| FollowGSI[("Follow GSI / View<br/>PK: followeeId<br/>SK: followerId")]
Reading feed#
To handle GET /feed using only the tables we have built so far, we introduce a stateless Feed Service.
When a user opens their feed, the Feed Service executes three steps in order:
- Fetch Followed Accounts: Query the
Followtable usingfollowerId(the Partition Key) to get the list of everyone the user follows. - Fetch Their Posts: Query the
Poststable to retrieve recent posts authored by each of those followed accounts.- Earlier, we partitioned the
Poststable strictly bypostIdso writes would distribute evenly and single-post lookups would be fast.
- Earlier, we partitioned the
- Merge, Sort, and Paginate: Combine all retrieved posts in memory, sort them in reverse-chronological order (
createdAtdescending, withpostIdas tie-breaker), slice the page using our cursor, and return the response.
Since postId is the Partition Key of the Posts table, querying for all recent posts by a specific author (sorted by createdAt) runs into trouble. Adding a Global Secondary Index (GSI) or materialized view partitioned by authorId solves that exact lookup problem.
To avoid fetching every post a user has ever written over the years, we also make createdAt#postId the Sort Key (PK: authorId, SK: createdAt#postId). Appending postId keeps two posts with the same timestamp from colliding. Because rows inside each authorId partition stay sorted by createdAt, the Feed Service can efficiently read only the most recent posts from each followed account.
But still, the above approach for fetching the feed breaks down into two specific bottlenecks on every single GET /feed request:
- Database Read Amplification (Fan-out on read): If a user follows 10,000 accounts, fetching those 10,000
followeeIdsis a single partition lookup, but theFeed Servicemust then issue 10,000 separate queries against thePosts GSIto gather their recent posts. - Application Compute & Memory Overhead: The
Feed Servicepulls all those candidate posts over the network into memory just to merge, sort, and slice the top 20 items, discarding 99% of what it fetched, only to repeat the entire process when the user scrolls to page two.
flowchart LR
Client["Client"] --> LB["API Gateway &<br/>Load Balancer"]
LB -->|"POST /posts"| PS["Post Service<br/>(Stateless Hosts)"]
PS -->|"Write by postId"| PostsDB[("Posts Table<br/>PK: postId")]
PostsDB -.->|"Async replication"| PostsGSI[("Posts GSI / View<br/>PK: authorId<br/>SK: createdAt#postId")]
LB -->|"PUT /users/{userId}/follow"| FS["Follow Service<br/>(Stateless Hosts)"]
FS -->|"Write edge"| FollowDB[("Follow Table<br/>PK: followerId<br/>SK: followeeId")]
FollowDB -.->|"Async replication"| FollowGSI[("Follow GSI / View<br/>PK: followeeId<br/>SK: followerId")]
LB -->|"GET /feed"| FeedS["Feed Service<br/>(Stateless Hosts)"]
FeedS -->|"1. Get followees"| FollowDB
FeedS -->|"2. Query recent posts"| PostsGSI
Precomputing feeds#
Since reading feeds happens far more frequently than creating posts (a read-heavy system), doing the merge-and-sort work on every read does not scale under our 500ms latency budget.
To tackle the issue, we can pre-compute the user’s feed.
We shall create a new Feed table to store each user’s feed. userId (the feed owner) is our Partition Key, and on every new post, we look up the author’s followers using the Follow GSI (followeeId -> followerId) and push the post out to them.
Instead of storing the user’s entire feed in a single value (which hits item size limits and causes write contention), each post is its own row. With userId as the Partition Key and createdAt#postId as the Sort Key, every post is stored pre-sorted inside that user’s partition, making cursor pagination immediate.
The rows will not hold the full post, just the postId reference, to avoid duplicating heavy data, and we simply insert that single new row rather than rebuilding each follower’s entire feed from scratch. On GET /feed, the Feed Service reads the top postIds from the Feed table and hydrates their full details from the Posts table.
flowchart LR
Client["Client"] --> LB["API Gateway &<br/>Load Balancer"]
LB -->|"POST /posts"| PS["Post Service<br/>(Stateless Hosts)"]
PS -->|"1. Write post"| PostsDB[("Posts Table<br/>PK: postId")]
PostsDB -.->|"Async replication"| PostsGSI[("Posts GSI / View<br/>PK: authorId<br/>SK: createdAt#postId")]
PS -->|"2. Get followers"| FollowGSI[("Follow GSI / View<br/>PK: followeeId<br/>SK: followerId")]
PS -->|"3. Fan-out postId"| FeedDB[("Feed Table<br/>PK: userId<br/>SK: createdAt#postId")]
LB -->|"PUT /users/{userId}/follow"| FS["Follow Service<br/>(Stateless Hosts)"]
FS -->|"Write edge"| FollowDB[("Follow Table<br/>PK: followerId<br/>SK: followeeId")]
FollowDB -.->|"Async replication"| FollowGSI
LB -->|"GET /feed"| FeedS["Feed Service<br/>(Stateless Hosts)"]
FeedS -->|"1. Read postIds"| FeedDB
FeedS -->|"2. Hydrate posts"| PostsDB
Publishing posts for authors with many followers#
Suppose an author has 50,000 followers and the Post Service writes to all 50,000 follower feeds synchronously before returning a response.
There are various failures that happen when we do this synchronously:
- Timeouts & Partial Failures: Writing 50,000 rows over the network easily exceeds standard HTTP timeout limits. If a network blip interrupts the loop at follower #25,000, half the followers get the post and half don’t, leaving no clean way to retry without duplicating work.
- Thread & Resource Starvation: Each incoming post ties up a
Post Serviceworker thread and database connections for seconds at a time, starving the service of capacity to handle other users’POST /postsrequests. - Database Write Spikes: If several popular accounts post at the same time, synchronous bursts of hundreds of thousands of writes can throttle or overwhelm the
Feeddatabase.
To solve this, we want the Post Service to save the post to the Posts table and immediately return 200 OK to the user, while another set of workers handles the 50,000 feed writes in the background.
Using async workers#
Introducing a Message Queue (like Kafka or SQS) with asynchronous Feed Workers is the exact architectural fix here.
- The
Post Servicewrites to thePoststable, drops a lightweight{postId, authorId, createdAt}event onto the queue, and immediately returns200 OK. Feed Workersconsume events at a steady rate so theFeeddatabase isn’t overwhelmed, automatically retrying failed writes (or routing them to aDead Letter Queue).
So, we choose when to fan out on write (writing to all followers) and when to skip it and fan out on read instead:
- When someone publishes a post, the
Post Servicechecks whether the author crosses a follower threshold (for example, 100,000+ followers):- Regular Users (Fan-out on write): We publish an event to the Message Queue, and
Feed Workerswrite thepostIdinto every follower’s pre-computedFeedtable as before. - Celebrities (Skip fan-out): We save the post to the
Poststable (and itsPK: authorId, SK: createdAt#postIdview) and stop there: no queue event, and no 100-million-row fan-out.
- Regular Users (Fan-out on write): We publish an event to the Message Queue, and
- When a user opens their feed, the
Feed Servicecombines two lightweight reads:- Pre-computed Feed: Fetch the user’s pre-computed
postIdsfrom theFeedtable (covering all the regular accounts they follow). - Celebrity Pull (Fan-out on read): Identify which celebrities the user follows, fetch those celebrities’ recent posts from the
Posts GSI(PK: authorId, SK: createdAt#postId), and merge them with the pre-computed posts in memory.
- Pre-computed Feed: Fetch the user’s pre-computed
Because any individual user only follows a handful of celebrities, pulling those few feeds on read is fast, and we completely avoid 100-million-row write storms.
Look closely at that celebrity pull on the read path: if 50 million fans open their app around the same time, all 50 million requests will query the Posts GSI for that same celebrity’s authorId partition.
What component could we introduce to prevent that single database shard from getting overwhelmed by identical reads?
Caching posts#
A distributed in-memory cache like Redis sits right in front of the database to absorb that read spike.
Here is how it protects that single shard when a celebrity posts:
- Cache Celebrity Feeds (
celeb_posts:{authorId}): Instead of 50 million requests hitting thePosts GSIfor that celebrity’sauthorId, theFeed Servicereads their recent posts directly from Redis in sub-millisecond time. - Cache Individual Posts (
post:{postId}): We can also cache individual post objects bypostIdso hydrating full post details onGET /feedrarely touches thePoststable at all.
Edge case for caching#
Prepending the new post to celeb_posts:{authorId} on write (for example, using Redis LPUSH paired with LTRIM to cap the list at the latest ~200 posts) keeps the cache warm and prevents millions of simultaneous requests from hammering the database at once.
There is one subtle edge case with updating the cache directly on write:
- Expired Cache Key: Suppose a celebrity hasn’t posted in months, so their
celeb_posts:{authorId}entry expired (via TTL) and was evicted from Redis. - Incomplete List: If the
Post Serviceblindly pushes just the 1 brand-new post into that missing Redis key, Redis now contains a list with only a single post.
On write, the Post Service could check whether the list in Redis is empty. If it is, it loads the latest 200 posts; otherwise, it only prepends the new one.
In production with Redis, engineers refine this exact idea with two small patterns:
- Atomic Check-and-Push (
LPUSHX): Instead of checking if the list is empty in application code and then pushing (which can hit a race condition if the key expires in between), Redis has anLPUSHXcommand that prepends the new post only if the key already exists. - Lazy Loading (Cache-Aside): If
LPUSHXreports that the key doesn’t exist (because the TTL expired), thePost Servicecan skip querying the 200 posts altogether.- The next
GET /feedrequest will see a cache miss, and theFeed Servicefetches the latest 200 posts from thePosts GSIand populates Redis on demand, keeping writes fast.
- The next
flowchart LR
Client["Client"] --> LB["API Gateway &<br/>Load Balancer"]
%% Write Path
LB -->|"POST /posts"| PS["Post Service"]
PS -->|"1. Save post"| PostsDB[("Posts Table<br/>PK: postId")]
PostsDB -.->|"Async view"| PostsGSI[("Posts GSI / View<br/>PK: authorId, SK: createdAt#postId")]
PS -->|"2a. Regular user"| MQ(["Message Queue"])
MQ --> FW["Feed Workers"]
FW -->|"Get followers"| FollowGSI[("Follow GSI / View<br/>PK: followeeId, SK: followerId")]
FW -->|"Fan-out postId"| FeedDB[("Feed Table<br/>PK: userId, SK: createdAt#postId")]
PS -->|"2b. Celebrity (LPUSHX)"| Cache[("Redis Cache<br/>celeb_posts:{authorId}<br/>post:{postId}")]
%% Follow Path
LB -->|"PUT /users/{userId}/follow"| FS["Follow Service"]
FS -->|"Write edge"| FollowDB[("Follow Table<br/>PK: followerId, SK: followeeId")]
FollowDB -.->|"Async view"| FollowGSI
%% Read Path
LB -->|"GET /feed"| FeedS["Feed Service"]
FeedS -->|"1. Read precomputed feed"| FeedDB
FeedS -->|"2. Check followed celebs"| FollowDB
FeedS -->|"3. Fetch celeb & post data"| Cache
FeedS -.->|"Cache miss: celeb posts"| PostsGSI
FeedS -.->|"Cache miss: post details"| PostsDB
Handling follow and unfollow#
What happens to that precomputed Feed table when the social graph changes? Suppose User A newly follows regular user User B (PUT /users/B/follow), or later unfollows them. Since User B’s past posts were created before the follow happened, they aren’t in User A’s Feed table. On an unfollow, old posts remain there.
Here is how we can use a background worker to handle the Follow event (PUT /users/B/follow):
- Regular User Followed: The worker queries the
Posts GSI(PK: authorId, SK: createdAt#postId) forUser B’s latest ~20–50 posts and writes thosepostIdsintoUser A’sFeedpartition. - Celebrity Followed: The worker skips the
Feedtable completely.User A’s nextGET /feedrequest will automatically pullUser B’s cached posts from Redis on read.
Now let’s look at the Unfollow event (DELETE /users/B/follow). Remember that our Feed table is structured with PK: userId (User A) and SK: createdAt#postId, storing postId references.
We can tackle this with either of the options below:
- Store
authorIdin theFeedtable: By saving{postId, authorId}in each row, a background worker can scanUser A’s recent feed partition and delete only rows matchingauthorId == Bwithout querying thePoststable. - Filter at read time: When
GET /feedhydrates posts from thePoststable (or cache), it already has the full post object andUser A’s active follow list, so it can immediately drop any post from an unfollowed user before returning the page.
Prevent large feed tables#
If an active user follows 500 people, their Feed partition (PK: userId, SK: createdAt#postId) will accumulate tens of thousands of rows over a few years, even though users rarely scroll past the top few hundred posts. How can we prevent each user’s Feed partition from growing infinitely?
We prevent unbounded partition growth in the Feed table using two mechanisms:
- TTL (Time-To-Live): Set an automatic expiration (e.g., 30 days) on every row in the
Feedtable. Both Cassandra and DynamoDB support per-row TTL and purge expired rows in the background with zero application-level delete overhead. - Size Capping + Read Fallback: Cap each user’s active feed partition to the latest ~500 posts (trimming older entries asynchronously or holding the hot window in a Redis Sorted Set). In the rare case a user scrolls past 500 posts,
GET /feedfalls back to a fan-out on read query against thePosts GSI.
Final diagram#
flowchart LR
Client["Client"] --> LB["API Gateway &<br/>Load Balancer"]
Client -->|"Direct media upload<br/>(Pre-signed URL)"| S3[("Object Storage<br/>(S3)")]
Client -->|"Fetch media"| CDN["CDN"]
CDN -.->|"Cache miss"| S3
%% Media Processing
S3 -->|"Object event"| MediaQ(["Media Events Queue"])
MediaQ --> TW["Transcoding<br/>Workers"]
TW -->|"Save variants"| S3
TW -->|"Set READY"| PostsDB[("Posts Table<br/>PK: postId")]
TW -->|"Fan-out event<br/>(media posts)"| FeedQ(["Feed Events Queue"])
%% Post & Follow Write Paths
LB -->|"POST /posts"| PS["Post Service"]
PS -->|"Save post"| PostsDB
PostsDB -.->|"Async view"| PostsGSI[("Posts GSI<br/>PK: authorId, SK: createdAt#postId")]
PS -->|"Regular user<br/>(text-only posts)"| FeedQ
PS -->|"Celebrity (LPUSHX)"| Cache[("Redis Cache<br/>celeb_posts / post")]
LB -->|"Follow / Unfollow"| FS["Follow Service"]
FS -->|"Update edge"| FollowDB[("Follow Table<br/>PK: followerId, SK: followeeId")]
FollowDB -.->|"Async view"| FollowGSI[("Follow GSI<br/>PK: followeeId, SK: followerId")]
FS -->|"Graph event"| FeedQ
%% Async Fan-out Workers
FeedQ --> FW["Feed Workers"]
FW -->|"Lookup followers"| FollowGSI
FW -->|"Backfill on follow"| PostsGSI
FW -->|"Write / Trim (TTL)"| FeedDB[("Feed Table<br/>PK: userId, SK: createdAt#postId")]
%% Read Path
LB -->|"GET /feed"| FeedS["Feed Service"]
FeedS -->|"1. Cursor read"| FeedDB
FeedS -->|"2. Check celebs & filter"| FollowDB
FeedS -->|"3. Hydrate & merge"| Cache
FeedS -.->|"Cache miss"| PostsGSI
FeedS -.->|"Cache miss"| PostsDB