logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramlinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Atomic CASGlobal Lock OrderingRead Write SynchronizationReadWriteLock vs synchronized vs ReentrantLock60-Day LLD & Machine Coding Mastery Roadmap
The Four Pillars of OOPComposition, Asociation & AggregationDatabase locking / atomic updates
Don't Repeat Yourself (DRY) PrincipleKeep it Simple, Stupid (KISS) PrincipleYou Aren't Gonna Need It (YAGNI) Principle
Design a Library Management System (LMS)Design a News FeedDesign a Parking LotDesign Thread-Safe Dropbox File Storage SystemDesign Tic Tac ToeDesing a Vending Machine
D : Dependency InversionI : The Interface Segregation PrincipleL : The Liskov Substitution PrincipleO : The Open/Closed PrincipleS : The Single Responsibility Principle
UML Activity Diagrams: Modeling Process and WorkflowUML Class Diagrams: Static Structure ModelingUML Sequence Diagrams: Modeling Dynamic InteractionsUse Case Diagrams: Functional Requirement Modeling
Low Level Design/problems

Design a News Feed

9 min read
On this pageCore requirements — must implement
Core requirements — must implementExtended requirements — discuss if time permitsNon-functional requirementsAssumptionSolutionEntitiesServicesAPIWorkflowsFan-out serviceFeed ranking and retrieval strategyPost publicationPersistence RepositoryFan-out on write vs fan-out on read vs hybridTransactional outbox

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

AreaAssumption
Social GraphOne user can follow many users.
Content CreationOne user can publish many posts.
EngagementA post can receive likes from many users.
Feed IntegrityUsers should not see duplicate feed entries.
Feed OrderingFeed ordering is chronological initially, with ranking extensible.
Fan-out StrategyAsynchronous fan-out is acceptable.
Initial ArchitectureA single-process implementation is the initial target.
Scope & RoadmapProduction 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.
  • 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:

  1. Add Bob to Alice's followers.
  2. 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
  followeeId

Then 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
 
unlock

an 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:

PolicyBehaviorTrade-off
Block producerWait for queue capacityPublisher latency increases
Reject submissionReturn failureCaller needs retry/fallback
Persist to durable brokerStore work for laterAdditional infrastructure
Batch submissionsReduce queue overheadLarger 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:

delay=min⁡(maxDelay, baseDelay×2attempt)delay = \min(maxDelay,\ baseDelay \times 2^{attempt})delay=min(maxDelay, baseDelay×2attempt)

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.
    • 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:

  1. Save the post in the database.
  2. Application crashes before publishing the fan-out event.
  3. 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.

←PreviousDesign a Library Management System (LMS)Next→Design a Parking Lot

On this page

Core requirements — must implementExtended requirements — discuss if time permitsNon-functional requirementsAssumptionSolutionEntitiesServicesAPIWorkflowsFan-out serviceFeed ranking and retrieval strategyPost publicationPersistence RepositoryFan-out on write vs fan-out on read vs hybridTransactional outbox