Skip to main content

Design a Social Media Platform like Facebook

Problem Statement

Design a social media platform where users can create accounts, make posts, follow other users, like and comment on posts, and view a personalized feed. The system should handle basic social interactions and generate a feed based on user connections.


Functional Requirements

  • Users should be able to register and login
  • Users should be able to create posts
  • Users should be able to follow/unfollow other users
  • Users should be able to like and comment on posts
  • Users should be able to view a feed of posts from followed users
  • Feed should show latest posts first

Objects Required

  • User
  • Post
  • Comment
  • SocialGraph (Follow system)
  • FeedService

User Class


import java.util.*;

public class User {

    private String userId;
    private String name;

    private Set following = new HashSet<>();
    private List posts = new ArrayList<>();

    public User(String userId, String name) {
        this.userId = userId;
        this.name = name;
    }

    public void follow(User user) {
        following.add(user);
    }

    public void unfollow(User user) {
        following.remove(user);
    }

    public void createPost(Post post) {
        posts.add(post);
    }

    public Set getFollowing() {
        return following;
    }

    public List getPosts() {
        return posts;
    }

    public String getName() {
        return name;
    }
}

The constructor initializes a user with a unique id and name.

The follow() method adds another user to the following list, enabling their posts to appear in the feed.

The unfollow() method removes a user from the following list, stopping their posts from appearing in the feed.

The createPost() method allows a user to publish a new post and store it in their personal post list.


Post Class


import java.time.LocalDateTime;
import java.util.*;

public class Post {

    private String postId;
    private User author;
    private String content;
    private LocalDateTime timestamp;

    private Set likes = new HashSet<>();
    private List comments = new ArrayList<>();

    public Post(String postId, User author, String content) {
        this.postId = postId;
        this.author = author;
        this.content = content;
        this.timestamp = LocalDateTime.now();
    }

    public void like(User user) {
        likes.add(user);
    }

    public void addComment(Comment comment) {
        comments.add(comment);
    }

    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    public User getAuthor() {
        return author;
    }

    public String getContent() {
        return content;
    }
}

The constructor creates a post with author, content, and automatically assigns timestamp.

The like() method adds a user to the like set, ensuring a user can like a post only once.

The addComment() method attaches a comment to the post for discussion.


Comment Class


import java.time.LocalDateTime;

public class Comment {

    private String commentId;
    private User user;
    private String message;
    private LocalDateTime timestamp;

    public Comment(String commentId, User user, String message) {
        this.commentId = commentId;
        this.user = user;
        this.message = message;
        this.timestamp = LocalDateTime.now();
    }
}

The constructor initializes a comment with user, message, and timestamp.

The class represents user-generated responses on posts.


FeedService Class


import java.util.*;

public class FeedService {

    public List getFeed(User user) {

        List feed = new ArrayList<>();

        for (User u : user.getFollowing()) {
            feed.addAll(u.getPosts());
        }

        feed.sort((a, b) ->
                b.getTimestamp().compareTo(a.getTimestamp())
        );

        return feed;
    }
}

The getFeed() method builds a timeline for a user by collecting posts from all followed users.

It sorts posts in reverse chronological order so that the newest content appears first.


SocialMediaPlatform Class


import java.util.*;

public class SocialMediaPlatform {

    private List users = new ArrayList<>();

    public User registerUser(String userId, String name) {
        User user = new User(userId, name);
        users.add(user);
        return user;
    }

    public Post createPost(User user, String postId, String content) {
        Post post = new Post(postId, user, content);
        user.createPost(post);
        return post;
    }
}

The platform class manages user registration and post creation.

The registerUser() method creates and stores a new user in the system.

The createPost() method allows a user to publish a post and links it to their account.


Main Class


public class Main {

    public static void main(String[] args) {

        SocialMediaPlatform platform = new SocialMediaPlatform();

        User u1 = platform.registerUser("U1", "Alice");
        User u2 = platform.registerUser("U2", "Bob");

        u1.follow(u2);

        platform.createPost(u2, "P1", "Hello from Bob!");

        FeedService feedService = new FeedService();

        System.out.println("Feed for Alice:");
        for (Post post : feedService.getFeed(u1)) {
            System.out.println(post.getContent());
        }
    }
}

The main method demonstrates a simple flow where users register, follow each other, create posts, and generate a feed.


Class Diagram

UseruserId : Stringname : Stringfollowing : Set<User>posts : List<Post>follow(User) : voidunfollow(User) : voidcreatePost(Post) : voidPostpostId : Stringauthor : Usercontent : Stringtimestamp : LocalDateTimelikes : Set<User>comments : List<Comment>like(User) : voidaddComment(Comment) : voidCommentcommentId : Stringuser : Usermessage : Stringtimestamp : LocalDateTimeFeedServicegetFeed(User) : List<Post>SocialMediaPlatformregisterUser(String, String) : UsercreatePost(User, String, String) : Postfollows

Also See

Comments

Popular posts from this blog

Designing a Parking Lot - Low Level Design

Problem Statement Design a parking lot that can handle vehicles entering and leaving while managing parking across multiple floors. Each vehicle should be assigned a suitable parking spot based on its type, and the spot should be freed once the vehicle exits. The design should also support generating a ticket at entry and optionally calculating the parking fee based on the duration of stay. Asked In Companies Amazon Google Microsoft Uber Walmart Flipkart Meta PayPal Oracle Salesforce Adobe Apple Intuit LinkedIn Atlassian Functional Requirements The design should support multiple vehicle types such as bikes, cars, and trucks A vehicle must be assigned a parking spot compatible with its type A parking spot cannot be assigned to more than one vehicle at a time The parking lot should support multiple levels (floors) The design should search and allocate an availa...

Most Frequently Asked Low Level Design(LLD) Interview Questions

Below are the curated list of most commonly asked Low Level Design (LLD) interview problems. Each problem includes a short description and a link to the complete solution with code and class diagrams. Design Parking Lot System The system should handle parking for different vehicle types such as bikes, cars, and trucks. It should manage slot allocation, availability tracking, and entry/exit flow. The design also ensures efficient usage of parking space under varying load conditions. View Solution Design Elevator / Lift System The system should support multiple elevators operating across floors with request handling logic. It focuses on scheduling algorithms to minimize wait time and optimize movement. It also manages direction control and concurrent floor requests. View Solution Design Movie Ticket Booking System The system should allow users to browse movies, select shows, and book seats. It handles seat ...

Software Design Patterns for LLD Interviews: A Complete Guide

Software Design Patterns for LLD Interviews: A Complete Guide In Software Development Engineer (SDE) interviews—especially for mid-level and senior roles—low-level design (LLD) rounds assess your ability to write clean, reusable, maintainable, and extensible code. The foundation of resolving these architectural challenges lies in the standard Gang of Four (GoF) Design Patterns. Rather than memorizing theoretical definitions, interviewers expect you to apply these patterns to real-world scenarios, identifying the trade-offs of each. Below is a comprehensive guide to the 12 most frequently asked design patterns in LLD interviews, categorized by their classification (Creational, Structural, and Behavioral). Each pattern contains a concrete, real-world Java implementation and a detailed breakdown of design decisions. Creational Design Patterns Creational design patterns deal with object creation mechanisms. They abstract the instantiation process, making a system independent of how...