Home   dsa  

Design a system like Facebook - System design interview

Designing a system like Facebook involves creating a scalable and robust architecture to handle user profiles, social interactions, media sharing, real-time updates, and more. Here's a comprehensive system design using Prisma for database modeling, Express.js for API routes, and a recommended tech stack:

Tech Stack

System Components

  1. Client Applications (Web, Mobile, Desktop):

    • Various clients for accessing Facebook features such as news feed, messaging, groups, etc.
  2. Express.js Backend

    • Prisma Models:

      // schema.prisma
      
      datasource db {
        provider = "postgresql"
        url      = env("DATABASE_URL")
      }
      
      generator client {
        provider = "prisma-client-js"
      }
      
      model User {
        id       Int      @id @default(autoincrement())
        username String   @unique
        email    String?  @unique
        password String
        posts    Post[]
        comments Comment[]
        friends  User[]    @relation("Friends", references: [id])
        groups   Group[]   @relation("MemberOf", references: [id])
      }
      
      model Post {
        id        Int       @id @default(autoincrement())
        content   String
        authorId  Int
        author    User      @relation(fields: [authorId], references: [id])
        comments  Comment[]
        createdAt DateTime  @default(now())
      }
      
      model Comment {
        id        Int       @id @default(autoincrement())
        content   String
        postId    Int
        post      Post      @relation(fields: [postId], references: [id])
        authorId  Int
        author    User      @relation(fields: [authorId], references: [id])
        createdAt DateTime  @default(now())
      }
      
      model Group {
        id          Int      @id @default(autoincrement())
        name        String
        description String?
        members     User[]   @relation("MemberOf", references: [id])
      }
      
    • Express API Routes:

      // server.js
      
      const express = require('express');
      const { PrismaClient } = require('@prisma/client');
      const prisma = new PrismaClient();
      
      const app = express();
      app.use(express.json());
      
      // Endpoint for creating a new post
      app.post('/posts', async (req, res) => {
        const { content, authorId } = req.body;
        try {
          const post = await prisma.post.create({
            data: {
              content,
              authorId: parseInt(authorId),
            },
          });
          res.json(post);
        } catch (error) {
          console.error(error);
          res.status(500).json({ error: 'Failed to create post' });
        }
      });
      
      // Endpoint for adding a comment to a post
      app.post('/posts/:postId/comments', async (req, res) => {
        const { postId } = req.params;
        const { content, authorId } = req.body;
        try {
          const comment = await prisma.comment.create({
            data: {
              content,
              postId: parseInt(postId),
              authorId: parseInt(authorId),
            },
          });
          res.json(comment);
        } catch (error) {
          console.error(error);
          res.status(500).json({ error: 'Failed to add comment' });
        }
      });
      
      const PORT = process.env.PORT || 3000;
      app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
      });
      
  3. Database Layer

    • PostgreSQL for user data (profiles, posts, comments)
    • MongoDB for media storage (photos, videos) and flexible data (messages, notifications)
  4. Real-time Communication

    • WebSockets (Socket.io): Facilitates real-time updates for notifications, chat messages, and live feed updates.
  5. Caching

    • Redis: Caches frequently accessed data like user profiles, posts, and comments to improve performance.
  6. Media Storage

    • Amazon S3: Stores photos and videos securely with high availability and durability.
  7. Authentication

    • OAuth: Used for user authentication and authorization to access Facebook services securely.
  8. Monitoring and Analytics

    • Prometheus and Grafana: Monitor system health, performance metrics, and usage statistics to optimize performance and troubleshoot issues.

Scalability and Fault Tolerance

Security

Published on: Jul 10, 2024, 01:08 AM  
 

Comments

Add your comment