Common Problems
Design Facebook Live Comments
Understanding the Problem
Functional Requirements
Core Requirements
- Viewers can post comments on a Live video feed.
- Viewers can see all comments in near real-time as they are posted.
- Viewers can see comments made before they joined the live feed.
Below the line (out of scope):
- Viewers can reply to comments
- Viewers can react to comments
Non-Functional Requirements
Core Requirements
- The system should scale to support millions of concurrent viewers and thousands of comments per second.
- The system should prioritize availability over consistency, eventual consistency is fine.
- The system should have low latency, broadcasting comments to viewers in near-real time
Below the line (out of scope):
- The system should be secure, ensuring that only authorized users can post comments.
- The system should enforce integrity constraints, ensuring that comments are appropriate (ie. not spam, hate speech, etc.)
Here's how your requirements section might look on your whiteboard:
The Set Up
Planning the Approach
Before you move on to designing the system, it's important to start by taking a moment to plan your strategy. Fortunately, for these common product style system design questions, the plan should be straightforward: build your design up sequentially, going one by one through your functional requirements. This will help you stay focused and ensure you don't get lost in the weeds as you go. Once you've satisfied the functional requirements, you'll rely on your non-functional requirements to guide you through the deep dives.
Defining the Core Entities
I like to begin with a broad overview of the primary entities. Initially, establishing these key entities will guide our thought process and lay a solid foundation as we progress towards defining the API.
For this particular problem, we only have three core entities:
- User: A user can be a viewer or a broadcaster.
- Live Video: The video that is being broadcasted by a user (this is owned and managed by a different team, but is relevant as we will need to integrate with it).
- Comment: The message posted by a user on a live video.
In your interview, this can be as simple as a bulleted list like:
Now, let's carry on to outline the API, tackling each functional requirement in sequence. This step-by-step approach will help us maintain focus and manage scope effectively.
The API
We'll need a simple POST endpoint to create a comment.
POST /comment/create Header: JWT | SessionToken { "liveVideoId": "123", "message": "Cool video!" }
We also need to be able to fetch past comments for a given live video.
GET /comments/:liveVideoId
Pagination will be important for this endpoint. More on that later when we get deeper into the design.
High-Level Design
To get started with our high-level design, let's begin by addressing the first functional requirement.
1) Viewers can post comments on a Live video feed
Fist things first, we need to make sure that users are able to post a comment.
This should be rather simple. Users will initiate a POST request to the POST /comment/create endpoint with the live video id and the comment message. The server will then validate the request and store the comment in the database.
- Commenter Client: The commenter client is a web or mobile application that allows users to post comments on a live video feed. It is responsible for authenticating the user and sending the comment to the Comment Management Service.
- Load Balancer: Its primary purpose is to distribute incoming application traffic across multiple targets, such as the Comment Management Service, in this case. This increases the availability and fault tolerance of the application.
- Comment Management Service: The comment management service is responsible for creating and querying comments. It receives comments from the commenter client and stores them in the comments database. It will also be responsible for retrieving comments from the comments database and sending them to the viewer client -- more on that later.
- Comments Database: The comments database is a NoSQL database like DynamoDB or MongoDB that stores the simple comment document. It is a document database, which means that it stores data in JSON-like documents. This is a good fit for our use case because we are storing simple comments that don't require complex relationships or transactions.
Let's walk through exactly what happens when a user posts a new comment.
- The users drafts a comment from their device (commentor client)
- The commenter client sends the comment to the comment management service via the POST /comment/create API endpoint which is exposed by the load balancer.
- The comment management service receives the request and stores the comment in the comments database.
Ok that was easy, but things get a little more complicated when we start to consider how users will view comments.
2) Viewers can see all comments in near real-time as they are posted
When a user posts a comment, we need to figure out how to broadcast that comment to all viewers in near real-time. Let's dive into some of our options:
Bad Solution: Polling
Good Solution: Websockets
Great Solution: Server Sent Events (SSE)
Here is our updated flow:
- User posts a comment and it is persisted to the database (as explained above)
- In order for all viewers to see the comment, the Comment Management Service will send the comment over SSE to all connected clients that are subscribed to that live video.
- The Commenter Client will receive the comment and add it to the comment feed for the viewer to see.
3) Viewers can see comments made before they joined the live feed
When a user joins a live video the expectation is that, while they immediately see the new comments being added in real-time, they also see the comments that were posted before they joined the live feed. Additionally, if they want to scroll up in the comment feed, they should be able to continue to load older comments. This is a common pattern in chat style applications and is known as "infinite scrolling".
We can easily fetch the most recent N comments by directly querying the database with our GET /comments/:liveVideoId endpoint. However, this endpoint will not allow us to fetch older comments. To do that, we will need to introduce pagination. Pagination is a common technique used to break up a large set of results into smaller chunks. It is typically used in conjunction with infinite scrolling to allow users to load more results as they scroll down the page.
Here are our options when it comes to implementing pagination:
Bad Solution: Offset Pagination
Good Solution: Cursor Pagination
Great Solution: Cursor Pagination with Prefetching and Caching
Having applied the "Great Solution", your whiteboard might look something like this. Note that this satisfies all of our functional requirements, but does not yet satisfy our non-functional requirements. That's okay, we'll get to that in the next section.
Potential Deep Dives
1) How will the system scale to support millions of concurrent viewers?
We already landed on Server Sent Events (SSE) being the appropriate technology. Now we need to figure out how to scale it. With SSE, we need to maintain an open connection for each viewer which means that each connection will occupy a port. The maximum number of ports available on a given server is 65,535 so we can support a maximum of ~65k concurrent viewers per server. If we want to support millions of concurrent viewers, we will need to scale horizontally by adding more servers. The question then becomes how do we distribute the load across multiple servers and how does each server know which comments to send to which viewers?
Bad Solution: Horizontal Scaling with Load Balancer and Pub/Sub
Good Solution: Pub/Sub Partitioning into Topics per Live Video
Great Solution: Partitioned Pub/Sub with Layer 7 Load Balancer
Great Solution: Scalable Dispatcher Instead of Pub/Sub
What is Expected at Each Level?
Ok, that was a lot. You may be thinking, “how much of that is actually required from me in an interview?” Let’s break it down.
Mid-level
Breadth vs. Depth: A mid-level candidate will be mostly focused on breadth (80% vs 20%). You should be able to craft a high-level design that meets the functional requirements you've defined, but many of the components will be abstractions with which you only have surface-level familiarity.
Probing the Basics: Your interviewer will spend some time probing the basics to confirm that you know what each component in your system does. For example, if you add an API Gateway, expect that they may ask you what it does and how it works (at a high level). In short, the interviewer is not taking anything for granted with respect to your knowledge.
Mixture of Driving and Taking the Backseat: You should drive the early stages of the interview in particular, but the interviewer doesn’t expect that you are able to proactively recognize problems in your design with high precision. Because of this, it’s reasonable that they will take over and drive the later stages of the interview while probing your design.
The Bar for FB Live Comments: For this question, I expect that candidates proactively realize the limitations with a polling approach and start to reason around a push based model. With only minor hints they should be able to come up with the pub/sub solution and should be able to scale it with some help from the interviewer.
Senior
Depth of Expertise: As a senior candidate, expectations shift towards more in-depth knowledge — about 60% breadth and 40% depth. This means you should be able to go into technical details in areas where you have hands-on experience. It's crucial that you demonstrate a deep understanding of key concepts and technologies relevant to the task at hand.
Advanced System Design: You should be familiar with advanced system design principles. For example, knowing how to use a search-optimized data store like Elasticsearch for event searching is essential. You’re also expected to understand the use of a distributed cache for locking tickets and to discuss detailed scaling strategies (it’s ok if this took some probing/hints from the interviewer), including sharding and replication. Your ability to navigate these advanced topics with confidence and clarity is key.
Articulating Architectural Decisions: You should be able to clearly articulate the pros and cons of different architectural choices, especially how they impact scalability, performance, and maintainability. You justify your decisions and explain the trade-offs involved in your design choices.
Problem-Solving and Proactivity: You should demonstrate strong problem-solving skills and a proactive approach. This includes anticipating potential challenges in your designs and suggesting improvements. You need to be adept at identifying and addressing bottlenecks, optimizing performance, and ensuring system reliability.
The Bar for Fb Live Comments: For this question, E5 candidates are expected to speed through the initial high level design so you can spend time discussing, in detail, how to scale the system. You should be able to reason through the limitations of the initial design and come up with a pub/sub solution with minimal hints. You should proactively lead the scaling discussion and be able to reason through the trade-offs of different solutions.
Staff+
Emphasis on Depth: As a staff+ candidate, the expectation is a deep dive into the nuances of system design — I'm looking for about 40% breadth and 60% depth in your understanding. This level is all about demonstrating that, while you may not have solved this particular problem before, you have solved enough problems in the real world to be able to confidently design a solution backed by your experience.
You should know which technologies to use, not just in theory but in practice, and be able to draw from your past experiences to explain how they’d be applied to solve specific problems effectively. The interviewer knows you know the small stuff (REST API, data normalization, etc) so you can breeze through that at a high level so you have time to get into what is interesting.
High Degree of Proactivity: At this level, an exceptional degree of proactivity is expected. You should be able to identify and solve issues independently, demonstrating a strong ability to recognize and address the core challenges in system design. This involves not just responding to problems as they arise but anticipating them and implementing preemptive solutions. Your interviewer should intervene only to focus, not to steer.
Practical Application of Technology: You should be well-versed in the practical application of various technologies. Your experience should guide the conversation, showing a clear understanding of how different tools and systems can be configured in real-world scenarios to meet specific requirements.
Complex Problem-Solving and Decision-Making: Your problem-solving skills should be top-notch. This means not only being able to tackle complex technical challenges but also making informed decisions that consider various factors such as scalability, performance, reliability, and maintenance.
Advanced System Design and Scalability: Your approach to system design should be advanced, focusing on scalability and reliability, especially under high load conditions. This includes a thorough understanding of distributed systems, load balancing, caching strategies, and other advanced concepts necessary for building robust, scalable systems.
The Bar for FB Live Comments: For a staff+ candidate, expectations are high regarding depth and quality of solutions, particularly when it comes to scaling the broadcasting of comments. I expect staff+ candidates to not only identify the pub/sub solution but proactively call out the limitations around reliability or scalability and suggest solutions. They likely have a good understanding of the exact technology they would use and can discuss the trade-offs of different solutions in detail.
Loading comments...