Design Twitter

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-06-14

Problem Statement

Design a highly scalable microblogging platform like Twitter, where users can post short messages (tweets), follow other users, and view a feed of recent tweets from people they follow.


The system should support millions of users, real-time feeds, high write/read throughput, and handle features such as likes, retweets, hashtags, and search efficiently.


🎯 Core Requirements


1. User Operations


•Users should be able to:
•Register, log in, and manage profiles.
•Follow or unfollow other users.
•View their list of followers and following users.


2. Tweet Operations


•Post a tweet (up to 280 characters).
•Delete or edit a tweet.
•Like or retweet others’ tweets.
•Attach optional media (images, videos, links).


3. Feed Generation


•Display a home timeline containing:
•Latest tweets from users the person follows.
•Tweets should appear in reverse chronological order or ranked by relevance.
•Support pagination and infinite scroll for feeds.


4. Trending and Search


•Display trending topics (hashtags or keywords) based on recent activity.
•Allow users to search tweets, hashtags, or profiles.


5. Notifications & Engagement


•Notify users when:
•They are followed, liked, or retweeted.
•Someone mentions them in a tweet.
•Maintain read/unread status for notifications.


6. Scalability & Performance


•Handle millions of active users and hundreds of millions of tweets.
•Ensure low latency for feed delivery.
•Support horizontal scaling for write-heavy workloads.
•Use caching and asynchronous processing for performance optimization.


7. Non-Functional Requirements


•Availability: 99.9% uptime.
•Latency: <200 ms for feed generation.
•Durability: Tweets and relationships must persist reliably.
•Consistency: Eventual consistency is acceptable for feeds.
•Security: User authentication, authorization, and spam control.


⚙️ Key Functional Components


ComponentResponsibility


User Service


Manage users, profiles, and follow relationships.


Tweet Service


Create, delete, and store tweets.


Feed Service


Generate personalized user timelines.


Notification Service


Send alerts for mentions, likes, and follows.


Search Service


Index and retrieve tweets and hashtags.


Media Service


Handle storage and retrieval of images/videos.


Analytics/Trends Service


Track trending hashtags and tweet statistics.


Auth Service


Manage login, tokens, and permissions.


🧱 Data Model (Simplified)


User

1 2User { 3 user_id: UUID 4 username: string 5 name: string 6 bio: string 7 followers: list<user_id> 8 following: list<user_id> 9 created_at: timestamp 10}


Tweet

1 2Tweet { 3 tweet_id: UUID 4 user_id: UUID 5 content: string 6 media_url: optional<string> 7 created_at: timestamp 8 like_count: int 9 retweet_count: int 10 hashtags: list<string> 11}


Feed

1 2Feed { 3 user_id: UUID 4 tweets: list<tweet_id> 5 last_updated: timestamp 6}


🧩 High-Level Architecture

1 2 +-------------------+ 3 | API Gateway | 4 +-------------------+ 5 | 6 +-----------+-----------+ 7 | | 8+---------------+ +---------------+ 9| Auth Service | | User Service | 10+---------------+ +---------------+ 11 | | 12+---------------+ +----------------+ 13| Tweet Service |<----->| Feed Service | 14+---------------+ +----------------+ 15 | | 16+---------------+ +----------------+ 17| Media Service | | Notification | 18+---------------+ | Service | 19 | +----------------+ 20 | 21+-----------------------------------+ 22| Storage Layer | 23| (SQL/NoSQL, Blob Store, Cache) | 24+-----------------------------------+ 25 | 26+----------------+ 27| Search & Trends| 28+----------------+


🧠 System Design Considerations


1. Data Storage


•User, Tweets, Relationships: Stored in NoSQL (e.g., Cassandra, DynamoDB) for scalability.
•Media: Stored in Object Storage (e.g., AWS S3, Azure Blob).
•Search Index: Stored in Elasticsearch or OpenSearch.
•Cache: Redis or Memcached for frequently accessed data.


2. Feed Generation Approaches


ApproachDescriptionProsCons


Fan-out on write


Push tweets to all followers’ feeds at post time.


Fast reads.


Expensive writes (for users with many followers).


Fan-out on read


Generate feed dynamically on user read.


Efficient writes.


Slower reads, higher latency.


Hybrid


Precompute feeds for active users, lazy for others.


Balanced approach.


Slight complexity.


3. Scaling & Performance


•Use message queues (Kafka, RabbitMQ) for feed updates and notifications.
•Implement sharding based on user IDs or tweet IDs.
•Use CDNs for media delivery.
•Employ rate limiting to control abuse.


4. Search and Trends


•Hashtags indexed in near-real-time.
•Trending computed via sliding window aggregations (e.g., tweets/minute per hashtag).
•Use distributed systems like Kafka Streams or Spark Streaming for analytics.


5. Fault Tolerance


•Each service is independently deployable (microservices).
•Use replication and auto-recovery for resilience.
•Ensure eventual consistency using background sync jobs.


📈 Example Workflows


Post Tweet


1.User sends tweet to Tweet Service.
2.Tweet stored in DB, added to search index.
3.Feed Service updates followers’ feeds (via Kafka event).
4.Notification sent to mentioned users.


Get User Feed


1.Feed Service retrieves precomputed feed (from Redis).
2.Fallback to on-demand generation if cache miss.
3.Merge and rank tweets by timestamp.
4.Return paginated feed to user.


🚀 Scalability Features


•Horizontal scaling of stateless services.
•Read replicas for heavy read load.
•Asynchronous background workers for updates.
•Distributed caching and sharding.


✅ Goal:


Design a scalable, distributed, and performant microblogging platform like Twitter that supports posting, following, feed generation, and real-time updates at global scale.

Solution

Comments