Design Twitter Timeline (User + Home)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-07-08

Problem Statement

Design the backend system for a Twitter-like timeline, focusing on user timeline (tweets posted by a user) and home timeline (tweets from followed users). Emphasize OOP design, modularity, and efficient tweet retrieval.


Functional Requirements


1.User Management
•Create, update, and retrieve user information.
•Follow/unfollow other users.
2.Tweet Management
•Users can post tweets (text, optional media).
•Tweets have timestamp, unique ID, and author information.
3.Timelines
•User Timeline → shows tweets posted by the user, in reverse chronological order.
•Home Timeline → shows tweets from followed users, merged and sorted by timestamp.
•Optional: support pagination and infinite scrolling.
4.Interactions
•Like, retweet, and reply to tweets.
•Update timeline dynamically when new tweets arrive.


Non-Functional Requirements


•Performance: Efficient retrieval of user and home timelines.
•Scalability: Support millions of users and tweets.
•Extensibility: Easy to add features like trending tweets, hashtags, or search.


Edge Cases & Constraints


•User with no followers → home timeline only shows their own tweets.
•Large number of followers → efficient merging for home timeline.
•Deleted tweets → remove from timelines.
•Pagination → handle large timelines efficiently.


Design Hints


•Key Classes / Interfaces
•User → stores userId, name, followers, following.
•Tweet → stores tweetId, content, authorId, timestamp, likes, retweets.
•Timeline → interface for fetching and displaying tweets.
•UserTimeline → tweets by a single user.
•HomeTimeline → merged tweets from followed users.
•TwitterApp → main orchestrator for user actions, posting, and timeline retrieval.
•Data Structures
•HashMap → userId → User object, tweetId → Tweet object.
•LinkedList / Deque → store recent tweets for O(1) insertion and removal.
•PriorityQueue / Heap → merge multiple timelines efficiently by timestamp.
•Design Patterns
•Observer Pattern → notify followers when a user posts a tweet (push model).
•Strategy Pattern → optional, for different timeline ranking algorithms.
•Singleton → for central TwitterApp instance managing users and tweets.


Example Flow


1.User posts a tweet → Tweet object created, added to UserTimeline.
2.Followers’ HomeTimeline updated (push or pull model).
3.User requests home timeline → merge latest tweets from followed users, sorted by timestamp.
4.User likes or retweets → update tweet stats and notify relevant users if needed.


Evaluation Areas


•Accurate OOP modeling of users, tweets, and timelines.
•Efficient timeline retrieval and merging of multiple user timelines.
•Extensible design for interactions, notifications, and ranking.
•Scalability considerations for large-scale timelines.


Solution

Comments