Design a Scalable Social Networking System like Facebook

Difficulty: EASYCategory: LLDFrequency: 1Asked On 2024-10-10

Problem Statement

Design and implement a simplified version of Facebook focusing on social interactions such as user profiles, friend relationships, posting content, and timeline/news feed generation. The system should be built with clean design principles, appropriate design patterns, and support concurrent operations.

🎯 Functional Requirements

You are required to design the system and implement at least 3 features with production-level code and concurrency support:

Supported Features:

1.createUser(String userId, String name)
•Registers a new user.
2.sendFriendRequest(String fromUserId, String toUserId)
•Sends a friend request from one user to another.
3.acceptFriendRequest(String fromUserId, String toUserId)
•Accepts a pending friend request.
4.postStatus(String userId, String content)
•User posts a status update (text-only).
5.getNewsFeed(String userId)
•Shows the most recent posts from the user and their friends, sorted by timestamp (latest first).

🧱 Suggested Data Models

User

•String userId
•String name
•Set<String> friends
•Set<String> pendingRequests

Post

•String postId
•String userId
•String content
•long timestamp

NewsFeedService

•Aggregates and returns recent posts from the user + friends.

📐 Required Design Patterns

1.Singleton Pattern
•For service managers (e.g., UserService, PostService).
2.Observer Pattern (optional extension)
•To notify friends of new posts or events.
3.Factory Pattern
•For creating Post objects or notification types (if extended).
4.Builder Pattern (optional)
•For constructing complex post structures or user profiles.

🔐 Concurrency Requirements

•Ensure thread-safety for:
•Sending/accepting friend requests
•Posting statuses
•Reading/writing shared structures (friends list, posts, feed)

Suggestions:

•Use ConcurrentHashMap, synchronized, or ReentrantLocks
•Make key data structures concurrent (e.g., post storage, request queues)

🔁 Multithreading Scenarios

•Multiple users sending requests or posting simultaneously
•Two threads modifying the same user’s friend list concurrently
•Concurrent reads (feeds) and writes (posts/friends)

🧪 Sample Workflow

1text 2CopyEdit 3createUser("u1", "Alice") 4createUser("u2", "Bob") 5 6sendFriendRequest("u1", "u2") 7acceptFriendRequest("u1", "u2") 8 9postStatus("u1", "Hello from Alice!") 10postStatus("u2", "Hi! Bob here.") 11 12getNewsFeed("u1") → ["Hi! Bob here.", "Hello from Alice!"]

💾 In-Memory Data Storage (for LLD scope)

•Map<String, User> — user registry
•Map<String, List<Post>> — user’s post history
•List<Post> — shared or sharded feed data

✅ Evaluation Criteria

•✅ Clean code structure and naming
•✅ Proper use of OOP and design patterns
•✅ Concurrency safety using Java constructs
•✅ Functionality correctness with multiple threads
•✅ Easily extensible to add comments, likes, photos


Solution

Comments