❓
물음표살인마 블로그
  • README
  • ALGORITHM
    • Sieve of Eratosthenes
    • Round Up
    • Binary Search
    • Union Find
    • Sorting Array
    • Lcm, Gcd
  • TechTalk Review
    • Template
  • Books
    • CS Note for Interview
      • Ch1. Design Pattern & Programming paradigm
        • 1.1.1 Singleton Pattern
        • 1.1.2 Factory Pattern
        • 1.1.4 Observer Pattern
        • 1.1.5 Proxty Pattern & Proxy Server
        • 1.1.8 Model-View-Controller Pattern
        • 1.2.1 Declarative and Functional Programming
        • 1.2.2 Object Oriented Programming
      • Ch2. Network
        • 2.2.1 TCP/IP Four-Layer Model
        • 2.2.1-1 TCP 3, 4 way handshake
        • 2.3 Network Devices L4, L7
        • 2.4.1 ARP, RARP
        • 2.4.2 Hop By Hop Communication
        • 2.4.3 IP Addressing Scheme
      • Ch3. Operating System
        • 3.1.1 Roles and Structure of Operating Systems
        • 3.2.1 Memory Hierarchy
        • 3.2.2 Memory Management
        • 3.3.1 Processes and Compilation Process
        • 3.3.3 Memory Structure of a Process
        • 3.3.4 Process Control Block (PCB)
        • 3.3.5 Multiprocessing
        • 3.3.6 Threads and Multithreading
        • 3.3.7 Shared Resources and Critical Sections
        • 3.3.8 Deadlock
        • 3.4 CPU Scheduling Algorithm
      • Ch4. Database
        • 4.1 Database Basic
        • 4.2 Normalization
        • 4.3 Transaction and Integrity
        • 4.4 Types of Databases
        • 4.5 Indexes
        • 4.6 Types of Joins
        • 4.7 Principles of Joins
      • Ch5. Data Structure
    • Learning the Basics of Large-Scale System Design through Virtual Interview Cases
      • 1. Scalability based on user counts(1/2)
      • 1. Scalability based on user counts(2/2)
      • 2.Back-of-the-envelope estimation
      • 3. Strategies for System Design Interviews
      • 4. Rate Limiter
      • 5. Consistent Hashing
      • 6. Key-Value System Design
      • 7. Designing a Unique ID Generator for Distributed Systems
      • 8. Designing a URL Shortener
      • 9. Designing a Web Crawler
      • 10. Notification System Design
      • 11. Designing a News Feed System
      • 12. Chat System Design
      • 13. AutoComplete
      • 14. Design YouTube
      • 15. Design Google Drive
      • Loadbalancer Algorithms
      • Cache tier
      • CDN, Content Delivery Network
      • Stateless Web tier
    • Computer System A programmer's perspective
    • Effective Java
      • Item 1. Consider Static Factory Methods Instead of Constructors
      • Item 2. Consider a Builder When Faced with Many Constructor Parameters
      • Item 3. Ensure Singleton with Private Constructor or Enum Type
      • Item 4. Enforce Noninstantiability with a Private Constructor
      • Item 5. Prefer Dependency Injection to Hardwiring Resources
      • Item 6. Avoid Creating Unnecessary Objects
      • Item 7. Eliminate Obsolete Object References
      • Item 8. Avoid Finalizers and Cleaners
      • Item 9.Prefer try-with-resources to try-finally
      • Item10. Adhering to General Rules When Overriding equals
        • Handling Transitivity Issues
        • Ensuring Consistency
      • Item11. Override hashCode When You Override equals
      • Item12. Always Override toString
        • Always Override toString
      • Item13. Override Clone Judiciously
      • Item14. Consider Implementing Comparable
      • Item15. Minimize the Accessibility of Classes and Members
      • Item16. Accessor Methods Over Public Fields
      • Item17. Minimize Mutability
      • Item18. Composition over inherentance
      • Item19. Design and Document for Inheritance, or Else Prohibit It
      • Item20. Prefer Interfaces to Abstract Classes
      • Item21. Design Interfaces with Implementations in Mind
      • Item22. Use Interfaces Only to define Types
      • Item23. Prefer Class Hierarchies to Tagged Classes
      • Item24. Favor Static Member Classes Over Non-Static
      • Item28. Use Lists Instead of Arrays
      • Item29. Prefer Generic Types
      • Item30. Favor Generic Methods
    • Head First Design Patterns
      • Ch1. Strategy Pattern
      • Ch2. Observer Pattern
        • Ver1. Ch2. Observer Pattern
      • Ch3. Decorator Pattern
        • Ch3. Decorator Pattern
      • Ch4. Factory Pattern
      • Ch5. Singleton Pattern
      • Ch6. Command Pattern
      • Ch7. Adapter and Facade Pattern
      • Ch8. Template Method Pattern
    • Digging Deep into JVM
      • Chapter 2. Java Memory Area & Memory Overflow
      • Chapter 3. Garbage Collector & Memory Allocation Strategy (1/2)
      • Chapter 3. Garbage Collector & Memory Allocation Strategy (2/2)
      • Chapter 5. Optimization Practice
      • Chapter 6. Class file structure
      • Chapter 8. Bytecode Executor Engine (1/2)
  • Interview Practices
    • Restful API Practices
      • Url Shortener API
      • Event Ticket Reservation API
      • Course Management API
      • Search posts by tags API
      • Online Code platform API
      • Simple Task Management API
      • Event Participation API
      • Review System API
      • Car management API
      • Online Library
    • Tech Review
      • if(kakao)
        • Kakao Account Cache Migration / if(kakao)2022
        • Improving the Anomaly Detection System for KakaoTalk Messaging Metrics / if(kakao) 2022
        • Standardizing API Case Handling Without Redeployment / if(kakaoAI)2024
        • JVM warm up / if(kakao)2022
    • Naver Computer Science
      • Process & Thread
      • TCP & UDP
      • Spring & Servlet
      • Filter & Interceptor & AOP
      • Equals() & ==
      • Dependency Injection
      • Object Oriented Programming
  • F-Lab
    • Week1
      • Client & Server
      • HTTP
      • TCP/UDP
      • REST API
      • Questions
        • Object Oriented Programming
        • HTTP
        • Process & Thread
        • Data Structure
    • Week2
      • OSI 7 layer
      • Web vs WAS
    • Week3
      • RDB vs NoSQL
      • RDB Index
      • Cache
      • Redis
      • Messaging Queue
    • Week4
      • Project - Ecommerce
    • Week5
      • ERD - 1
    • Week6
      • Ecommerce - 2
      • Role
      • pw hashing && Salt
      • CreatedAt, ModifiedAt
      • JWT
      • Copy of ERD - 1
    • Week7
      • Vault (HashiCorp Vault)
    • Week 8
      • Api Endpoints
    • Week10
      • Product Create Workflow
  • TOY Project
    • CodeMentor
      • Implementation of Kafka
      • Project Improvement (Architectural Enhancements)
      • Communication between servers in msa
  • JAVA
    • MESI protocol in CAS
    • CAS (Compare and Set)
    • BlockingQueue
    • Producer & Consumer
    • Synchronized && ReentrantLock
    • Memory Visibility
    • Checked vs Unchecked Exception
    • Thread
    • Batch delete instead of Cascade
    • Java Questions
      • Week 1(1/2) - Basic Java
      • Week 1(2/2) - OOP
      • Week 2(1/2) - String, Exception, Generic
      • Week2(2/2) Lambda, Stream, Annotation, Reflection
      • Week3(1/2) Collections
      • Week3(2/2) Threads
      • Week4 Java Concurrency Programming
      • Week5 JVM & GC
    • Java 101
      • JVM Structure
      • Java Compiles and Execution Method
      • Override, Overload
      • Interface vs Abstract Class
      • Primitive vs Object Type
      • Identity and equality
      • String, StringBuilder, StringBuffer
      • Checked Exceptions and Unchecked Exceptions
      • Java 8 methods
      • Try-with-reources
      • Strong Coupling and Loose Coupling
      • Serialization and Deserialization
      • Concurrency Programming in Java
      • Mutable vs Immutable
      • JDK vs JRE
  • SPRING
    • DIP. Dependency Inversion Principal
    • Ioc container, di practice
    • @Transactional
    • Proxy Pattern
    • Strategy Pattern
    • Template Method Pattern
    • using profile name as variable
    • Spring Questions
      • Spring Framework
      • Spring MVC & Web Request
      • AOP (Aspect-Oriented Programming)
      • Spring Boot
      • ORM & Data Access
      • Security
      • ETC
  • DATABASE
    • Enhancing Query Performance & Stability - User list
    • Ensuring Data Consistency, Atomicity and UX Optimization (feat.Firebase)
    • Redis: Remote Dictionary Server
    • Database Questions
      • Week1 DBMS, RDBMS basics
      • Week2 SQL
      • Week3 Index
      • Week4 Anomaly, Functional Dependency, Normalization
      • Week5 DB Transaction, Recovery
    • Normalization
      • 1st Normal Form
      • 2nd Normal Form
      • 3rd Normal Form
  • NETWORK
    • HTTP & TCP head of line blocking
    • HTTP 0.9-3.0
    • Blocking, NonBlocking and Sync, Async
    • Network Questions
      • Week1 Computer Network Basic
      • Week2(1/3) Application Layer Protocol - HTTP
      • Week2(2/3) Application Layer Protocol - HTTPS
      • Week2(3/3) Application Layer Protocol - DNS
      • Week3 Application Layer
      • Week4 Transport Layer - UDP, TCP
      • Week5 Network Layer - IP Protocol
    • Network 101
      • https://www.google.com
      • TCP vs UDP
      • Http vs Https
      • TLS Handshake 1.2
      • HTTP Method
      • CORS & SOP
      • Web Server Software
  • OS
    • Operating System Questions
      • Week1 OS & How Computer Systems Work
      • Week2(1/2) Process
      • Week2(2/2) Thread
      • Week3 CPU Scheduling
      • Week4 Process Synchronize
      • Week5 Virtual Memory
    • Operating System 101
      • Operating system
        • The role of the operating system
        • The composition of the operating system.
      • Process
        • In Linux, are all processes except the initial process child processes?
        • Zombie process, orphan process
        • (Linux) Daemon process
        • Process address space
        • Where are uninitialized variables stored?
        • Determination of the size of the Stack and Heap
        • Access speed of Stack vs Heap
        • Reason for memory space partitioning
        • Process of compiling a process
        • sudo kill -9 $CURRENT_PID
      • Thread
        • Composition of a thread's address space
      • Process vs Thread
        • Creation of processes and threads in Linux
      • Multiprocessing
        • Web Browser
        • Implementation of multiprocessing
        • Application areas of multiprocessing
      • Multithreading
        • Application areas of multithreading
      • Interrupt
        • HW / SW Interrupt
        • Method of handling interrupts
        • Occurrence of two or more interrupts simultaneously
      • Polling
      • Dual Mode
        • Reason for distinguishing between user mode and kernel mode
      • System call
        • Differentiation between system calls
        • Types of system calls
        • Execution process of a system call
      • Process Control Block (PCB)
        • PCB의 구조
        • 쓰레드는 PCB를 갖고 있을까?
        • 프로세스 메모리 구조
      • Context switching
        • Timing of context switching
        • Registers saved during context switching
        • Context switching in processes
        • Context switching in threads
        • Difference between context switching in processes and threads
        • Information of the current process during context switching
      • Interprocess Communication (IPC)
        • Cases where IPC is used
        • Process address space in IPC Shared Memory technique
        • Types of IPC
  • COMPUTER SCIENCE
    • Computer Architecture 101
      • 3 components of a computer
      • RAM vs ROM
      • CPU vs GPU
      • SIMD
      • Two's complement
      • Harvard Architecture vs. von Neumann Architecture
      • The structure of a CPU.
      • Instruction cycle (CPU operation method)
      • Instruction pipelining
      • Bus
      • Memory area
      • Memory hierarchy structure
        • Reason for using memory hierarchy structure
      • Cache memory
      • L1, L2, L3 Cache
      • Locality of reference (cache)
      • Fixed-point vs Floating-point
        • epresentation of infinity and NaN (Not a Number) in floating-point
      • RISC vs CISC
      • Hamming code
      • Compiler
      • Linking
      • Compiler vs Interpreter
      • Mutex vs Semaphore
      • 32bit CPU and 64bit CPU
      • Local vs Static Variable
      • Page
  • Programming Paradigm
    • Declarative vs Imperative
  • JPA, QueryDsl
    • why fetchResults() is deprecated
  • PYTHON
    • Icecream
  • FASTAPI
    • Template Page
  • LINUX
    • Template Page
  • DATA STRUCTURE
    • Counting Sort
    • Array vs Linked List
  • GIT, Github
    • git clone, invalid path error
  • INFRA
    • Template Page
  • AWS
    • Server Log Archive Pipeline
    • Image Processing using Lambda
  • DOCKER
    • Docker and VM
    • Python Executable Environment
    • Docker commands
  • docker-compose
    • Kafka, Multi Broker
  • KUBERNATES
    • !Encountered Errors
      • my-sql restarts
      • kafka producer: disconnected
    • Kubernetes Components
    • Helm
      • Helm commands
    • Pod network
    • Service network
      • deployment.yaml
      • services.yaml
    • Service type
      • Cluster IP
      • NodePort
    • service-name-headless?
    • kube-proxy
  • GraphQL
    • Template Page
  • WEB
    • Template Page
  • Reviews
    • Graphic Intern Review
    • Kakao Brain Pathfinder Review
    • JSCODE 자바 1기 Review
  • 😁Dev Jokes
    • Image
      • Plot twist
      • Priorities
      • SQL join guide
      • Google is generous
      • Genie dislikes cloud
      • buggy bugs
      • last day of unpaid internship
      • what if clients know how to inspect
      • its just game
      • how i wrote my achievement on resume
      • self explanatory
      • chr(sum(range(ord(min(str(not))))))
Powered by GitBook
On this page
  • 요구사항 분석
  • 기능적 요구사항
  • 비기능적 요구사항
  • 2단계: 개략적 설계안 제시 및 동의 구하기
  • 클라이언트와 서버의 통신 방법
  • 데이터 저장 방식 제안
  • 시스템 확장성 고려
  • 3단계: 상세 설계
  • 메시지 흐름
  • 여러 단말 사이의 메시지 동기화
  • 소규모 그룹 채팅에서의 메시지 흐름
  • 접속상태 표시
  • 4단계: 마무리
  1. Books
  2. Learning the Basics of Large-Scale System Design through Virtual Interview Cases

12. Chat System Design

채팅 시스템 디자인

요구사항 분석

기능적 요구사항

  • 1:1 채팅: 두 명의 사용자가 실시간으로 메시지를 주고받을 수 있어야 합니다.

  • 그룹 채팅: 여러 사용자가 동시에 참여할 수 있는 채팅방을 지원해야 합니다.

  • 메시지 저장: 모든 메시지를 영구적으로 저장하고, 필요 시 검색할 수 있어야 합니다.

  • 푸시 알림: 새로운 메시지가 도착했을 때 사용자에게 알림을 보내야 합니다.

비기능적 요구사항

  • 확장성: 시스템은 수백만 명의 동시 접속자를 처리할 수 있도록 확장 가능해야 합니다.

  • 지연 시간 최소화: 실시간 채팅에서 지연 시간은 최소화되어야 합니다.

  • 가용성: 시스템은 24시간 내내 중단 없이 운영될 수 있어야 합니다.

  • 데이터 일관성: 메시지가 중복되거나 손실되지 않도록 보장해야 합니다.

2단계: 개략적 설계안 제시 및 동의 구하기

클라이언트와 서버의 통신 방법

폴링

폴링은 클라이언트가 일정한 간격으로 서버에 새로운 메시지가 있는지 확인하는 방법입니다. 클라이언트는 주기적으로 서버에 요청을 보내고, 서버는 새로운 데이터가 있을 경우 이를 응답합니다.

  • 장점: 구현이 간단하며, 서버의 복잡도를 낮출 수 있습니다.

  • 단점: 주기적인 요청으로 인해 서버와 네트워크 자원이 낭비될 수 있습니다. 실시간성이 떨어질 수 있습니다.

롱 폴링

롱 폴링은 폴링의 단점을 보완하기 위해 고안된 방식으로, 클라이언트가 서버에 요청을 보낸 후, 서버가 새로운 데이터가 생길 때까지 연결을 유지합니다. 새로운 데이터가 생기면 서버는 클라이언트에 응답을 보내고, 클라이언트는 다시 서버에 요청을 보냅니다.

  • 장점: 실시간성을 개선할 수 있으며, 폴링보다 자원 낭비가 적습니다.

  • 단점: 서버는 많은 연결을 관리해야 하므로, 서버의 부하가 증가할 수 있습니다.

웹소켓

웹소켓은 클라이언트와 서버 간의 양방향 통신을 가능하게 하는 프로토콜입니다. 초기 연결 이후 클라이언트와 서버 간의 지속적인 연결을 유지하며, 데이터를 실시간으로 주고받을 수 있습니다.

  • 장점: 진정한 실시간 통신이 가능하며, 클라이언트와 서버 간의 데이터 전송이 매우 효율적입니다.

  • 단점: 초기 설정이 복잡하며, 서버 자원의 효율적인 관리가 필요합니다.

데이터 저장 방식 제안

메시지와 사용자 데이터를 관리하기 위해 데이터베이스 설계를 해야합니다. 대규모 채팅 시스템에서는 NoSQL 데이터베이스가 적합할 수 있으며, 높은 가용성과 확장성을 달성할 수 있습니다.

  • 메시지 테이블: 각 메시지의 ID, 송신자 ID, 수신자 ID, 메시지 내용, 타임스탬프 등을 저장합니다.

  • 채팅방 테이블: 채팅방의 ID, 참여자 목록, 생성 시간 등을 저장합니다.

  • 사용자 테이블: 사용자 정보, 상태, 프로필 등을 저장합니다.

시스템 확장성 고려

  • 로드 밸런싱: 로드 밸런서를 통해 각 서버에 균등한 부하를 분배할 수 있으며, 특정 서버에 장애가 발생해도 로드 밸런서가 이를 감지하고 나머지 서버로 트래픽을 자동으로 분산시킴으로써 시스템의 가용성을 유지할 수 있습니다.

  • 데이터 분산: 분산 데이터베이스를 사용하면 데이터를 여러 노드에 나누어 저장하고, 데이터 접근 시 전체 시스템의 부하를 줄일 수 있습니다.

  • 세션 관리: 세션 스티키니스(Session Stickiness)**나 세션 공유(Session Sharing) 기법을 사용

세션 스티키니스, 세션 공유
  • 세션 스티키니스: 사용자의 세션을 최초에 연결된 서버에 고정시켜, 해당 사용자의 모든 요청이 같은 서버로 전달되도록 합니다. 이는 세션 관리의 복잡성을 줄여주지만, 특정 서버에 부하가 집중될 수 있습니다.

  • 세션 공유: Redis나 Memcached 같은 분산 캐시를 사용해 모든 서버가 동일한 세션 정보를 공유하도록 합니다. 이를 통해 사용자가 어떤 서버에 연결되더라도 세션 일관성이 유지됩니다.

3단계: 상세 설계

메시지 흐름

1:1 채팅 메시지 처리 흐름

  1. 사용자 A가 채팅 서버 1로 메세지 전송

  2. 채팅서버는 ID 생성기를 사용해 해당 메시지 ID 종류 결정

  3. 채팅 서버 1은 해당 메시지를 메시지 동기화 큐로 전송

  4. 메시지가 키-값 저장소에 보관(target userId : messageId)

  5. targetUserId를 확인하여 접속중이면 다음 채팅 서버로 전송, 아니면 푸시 알림 서버로 전달'

  6. 채팅 서버에서 사용자 B에게 메시지 전달

여러 단말 사이의 메시지 동기화

하나의 사용자가 두개의 단말기를 사용하는 예시입니다.

  1. cur_max_message_id를 통해 최신 메시지를 추적합니다.

  2. 키:값 저장소에 보관된 메세지들을 확인하여 cur_max_message_id보다 큰 값들을 전송한다.

소규모 그룹 채팅에서의 메시지 흐름

  1. 사용자 B, C는 각각 메시지 동기화 큐를 가지고 있습니다.

  2. 사용자가 많지 않으면 사용자 A의 메시지를 각 큐에 넣으면 됩니다.

접속상태 표시

  1. 온라인: 웹소켓 연결이 맺어지고 나면, 접속상태 서버는 키:값 저장소에 정보를 보관합니다.

  2. 오프라인: 일정 시간동안 클라이언트의 요청이나 응답이 없으면 사용자를 오프라인 상태로 업데이트 합니다

  3. 접속 장애시: HeartBeat 검사를 통해 주기적으로 이벤트를 서버에 보내도록하여 판별합니다.

상태 정보를 전송할떄는 Pub, Sub Event를 사용합니다. A-B, A-C 형태를 사용하여, A의 상태가 변경되면 이벤트를 발행합니다. 하지만 해당 방법은 사용자가 적을때 효과적이지만, 사용자가 많으면 비용과 시간이 많이 들게 됩니다.

이를 해결하기 위해서는 manual 업데이트를 유도하거나, 중요한 이벤트(그룹 채팅 입장) 같은 순간에 상태 정보를 업데이트 하는 방식을 사용합니다.

4단계: 마무리

추가적으로 고려할 수 있는 부분들은 다양한 데이터, 암호화, 캐시, 로딩 속도 개선, 오류 처리 등이 있습니다.

  • 다양한 데이터: 미디어를 지원하도록 하고, 그에 따른 압축 방식, 클라우드 저장소와 썸네일 생성 방법 논의

  • 암호화: 제3자가 메시지를 볼 수 없도록 처리

  • 캐시: 데이터베이스와 통신 횟수를 줄이기 위해 최신 메시지들만 캐싱하여 유지할 수 있습니다.

  • 로딩 속도 개선: CDN을 사용하여 지리적으로 데이터/채널을 분산하여 빠르게 get 할 수 있도록 합니다.

  • 오류 처리: 서버의 Failover처리와 SPOF를 해결할 수 있습니다. 메시지를 안정적으로 전송하기 위해 재시도 로직이나 메시징 큐의 로그파일을 유지할 수 있습니다.

Previous11. Designing a News Feed SystemNext13. AutoComplete

Last updated 9 months ago