Designing a system like X (Twitter) involves a comprehensive approach to handle high traffic, scalability, and diverse functionalities. Below is a structured breakdown of the system design:
1. Requirements Gathering
Functional Requirements:
User registration/login, post tweets, follow/unfollow, real-time timelines, search, notifications, media uploads.
Non-Functional Requirements:
High scalability (millions of users), low-latency reads/writes, fault tolerance, security, global accessibility.
2. High-Level Architecture
The system comprises:
Frontend: Web/Mobile clients with React, Angular, or native apps.
API Gateway: Nginx or Envoy for routing requests to microservices.
Microservices:
User Service: Manages profiles and authentication (OAuth/JWT).
Tweet Service: Handles tweet creation, deletion, and media.
Timeline Service: Generates user feeds.
Follow Service: Manages follower relationships.
Search Service: Indexes tweets using Elasticsearch.
Notification Service: Sends alerts via WebSockets or Firebase.
Fan-out on Write: Precompute timelines for high-follow users (e.g., celebrities) by writing tweets to all followers' timelines asynchronously via Kafka.
Fan-out on Read: For less-followed users, fetch tweets from followed users in real-time when the timeline is requested.
Hybrid Approach: Use fan-out on write for top 1% influencers; fan-out on read for others to balance cost and performance.
Search
Index tweets in Elasticsearch by keywords, hashtags, and user handles. Implement auto-suggestions and relevance ranking.
Media Handling
Upload media to object storage (S3) and transcode using FFmpeg workers. Serve via CDN with signed URLs for access control.
Notifications
Real-time updates via WebSockets for web or Firebase Cloud Messaging (FCM) for mobile. Queue notifications in Kafka for reliability.
4. Scalability Strategies
Load Balancing: Distribute traffic using Nginx or AWS ALB across stateless microservices.
Database Sharding:
Shard users by user_id, tweets by tweet_id.
Use consistent hashing for uniform distribution.
Caching:
Cache hot data (e.g., trending tweets, celebrity timelines) in Redis.
Use LRU eviction policy for memory efficiency.
Asynchronous Processing: Offload heavy tasks (e.g., timeline updates, image processing) to Kafka workers.
5. Security Measures
Authentication: OAuth 2.0/JWT for secure user access.
Authorization: Role-based access control (RBAC) for APIs.