Design a social-media news feed.
Core requirements — must implement
- Create accounts.
- Follow and unfollow other users.
- Publish posts.
- Read their personalized news feed.
- Like and unlike posts.
- Retrieve post details and like counts.
Extended requirements — discuss if time permits
- Pagination to return posts in manageable pages
- Remove or hide a post according to policy
Non-functional requirements
- Thread safety : Concurrent requests must not corrupt shared state
- Correctness : No duplicate likes, invalid relationships or inconsistent feed entries
- Low latency : Publishing and feed reads should be responsive
- Scalability : Large follower counts should not block publishers
- Availability : Background failures should not unnecessarily take down feed reads
- Reliability : Failed fan-out work should be retried or recovered
- Extensibility : New ranking policies and delivery strategies should be easy to add
Assumption
| Area | Assumption |
|---|---|
| Social Graph | One user can follow many users. |
| Content Creation | One user can publish many posts. |
| Engagement | A post can receive likes from many users. |
| Feed Integrity | Users should not see duplicate feed entries. |
| Feed Ordering | Feed ordering is chronological initially, with ranking extensible. |
| Fan-out Strategy | Asynchronous fan-out is acceptable. |
| Initial Architecture | A single-process implementation is the initial target. |
| Scope & Roadmap | Production extensions will be discussed separately. |
Solution
Entities
-
User
- Represents an account.
-
Post
- Represents content created by a user.
- Posts should be immutable after publication wherever possible. Immutability makes concurrent sharing easier
-
Feed
- Represents the posts delivered or made available to a user.
- Prefer storing post IDs or lightweight feed entries rather than duplicating full post objects.
-
Like
- A like is a relationship between a user and a post.
(postId, userId)pair must be unique.
-
Follow relationship
- A follow relationship is
(followerId, followeeId) - A user should not follow themselves, and repeated follow requests should not create duplicate relationships.
- A follow relationship is
-
Fan-out task
- A fan-out task represents pending delivery work.
Services
The component that owns mutable state should also own the synchronization protecting that state. This avoids a service having to understand the internal locking rules of every object.
API
Idempotency means repeating the same logical operation does not create additional unintended effects.
- Like should be idempotent.
- Unlike should be idempotent.
- Follow should be idempotent.
- Publish should support request idempotency if retries are possible.
Workflows
Follow and unfollow
Suppose Bob follows Alice, the logical changes are:
- Add Bob to Alice's followers.
- Add Alice to Bob's following.
In a simple in-memory design, the operation needs to protect both relationship collections.
- Two requests simultaneously ask Bob to follow Alice both could check that the relationship doesn't exist and then attempt insertion.
- Use set insertion under appropriate synchronization, or enforce uniqueness at the database level.
- A safe strategy is to acquire the two user locks in a consistent global order, such as ascending user ID. With a global lock order, both threads acquire locks in the same order, preventing this circular wait.
info
A cleaner design for larger systems is to maintain one canonical relationship record
FollowRelationship
followerId
followeeIdThen enforce uniqueness on (followerId, followeeId).
Publish a post
The publisher should not hold the user's relationship lock while scheduling or executing fan-out. The snapshot gives a stable view of the followers at the moment it was captured. The lock is acquired only while copying the collection.
Scaling
For large follower counts, enqueue a single event
PostPublished {
postId,
authorId,
followerSnapshotVersion
}A background fan-out coordinator can then fetch followers in pages, split recipients into batches, submit batch tasks to workers and retry failed batches.
Fan-out worker processing
A worker consumes a task and adds a post to the target user's feed.
Idempotent feed insertion to avoid duplicate feed. The check and insert must themselves be protected against concurrent workers. A thread-safe set or one per-feed exclusive lock can provide this in the in-memory version.
If chronological ordering matters, sort feed entries by a stable ordering key, such as
(createdAt,postId)do not rely on worker completion order to determine feed order.
Like and unlike
Use a mutex as the operation consists of multiple steps that must behave atomically.
lock post's like mutex
if user already exists in likedBy:
return unchanged
insert user into likedBy
increment likeCount
unlockan atomic counter alone cannot protect the set.
Fan-out service
Bounded queues and backpressure
An unbounded queue can grow indefinitely if publishers submit work faster than workers can process it. So a bounded queue has a maximum capacity. When full, the system must choose a policy:
| Policy | Behavior | Trade-off |
|---|---|---|
| Block producer | Wait for queue capacity | Publisher latency increases |
| Reject submission | Return failure | Caller needs retry/fallback |
| Persist to durable broker | Store work for later | Additional infrastructure |
| Batch submissions | Reduce queue overhead | Larger individual tasks |
For a production design, a durable broker or event stream is generally preferable to an unbounded in-memory queue.
Failure and retry
A common policy is exponential backoff:
Add jitter (random variation) so many workers do not retry simultaneously. Permanent failures should not retry indefinitely. Record them for investigation or dead-letter handling.
At-least-once delivery vs exactly-once delivery
A background system often provides at-least-once task delivery:
- A task may be processed more than once.
- The system retries if it cannot confirm success. Exactly-once execution across independent systems is difficult to guarantee.
Instead, design the operation to be idempotent.
Feed ranking and retrieval strategy
The Strategy pattern is useful as the feed service depends on the interface, not a specific ranking algorithm.
Post publication
To notify downstream consumers when a post is created use Observer pattern.
Persistence Repository
Use repository for isolating User/Post/Feed persistence implementation
Fan-out on write vs fan-out on read vs hybrid
- Fan-out on write
-
When Alice publishes a post, distribute it to her followers' feeds.
- Advantages:
- Feed retrieval is fast.
- Feed entries are already prepared.
- Good for users who publish to a moderate follower base.
- Disadvantages:
- Publishing creates significant background work.
- High-follower accounts can create enormous fan-out.
- Feed storage duplicates post references.
- Delivery may be delayed by queue backlogs.
- Advantages:
-
Fan-out on read
- When Bob opens his feed, fetch recent posts from the accounts Bob follows and merge them.
- The actual cost depends on how many candidates are fetched and how many are returned.
- Advantages:
- Publishing is cheap.
- Celebrity posts do not need to be copied into millions of feeds.
- Less duplicated feed storage.
- Disadvantages:
- Feed reads become more expensive.
- More accounts need to be queried.
- Ranking and merging are required at read time.
-
Hybrid
-
For normal users, distribute posts during publishing.
-
For celebrities, avoid writing to every follower's feed. Retrieve their recent posts when followers read their feeds.
-
-
Transactional outbox
Consider this failure:
- Save the post in the database.
- Application crashes before publishing the fan-out event.
- The post exists, but followers never receive it. A transactional outbox addresses this:
The post and event are committed together. A background publisher subsequently sends the event to the broker.
Consumers still need idempotency because an event may be delivered more than once.