Bird
Raised Fist0

WebSockets vs Long Polling vs Server-Sent Events - When to Use Each

HLDmediumInterview freq: common
Choose your preparation mode4 modes available
▶
Request Trace
Step 1/7
Client

Sends message

Client sends a chat message via WebSocket, Long Polling, or SSE protocol

Protocol:WebSocket / HTTP Long Polling / SSE
BeforeClient has composed a new message ready to send
AfterMessage is transmitted over network to Load Balancer
Load Balancer

Routes request

Load Balancer routes incoming request to the correct server based on protocol

Protocol:HTTP / WebSocket
BeforeLoad Balancer has received client request with protocol info
AfterRequest forwarded to WebSocket, Long Polling, or SSE Server accordingly
WebSocket Server

Processes message

WebSocket Server receives message, validates, and publishes to Message Broker

Protocol:Kafka Publish
BeforeWebSocket Server has active connection and received message
AfterMessage published to Kafka topic for durable storage and distribution
Long Polling Server

Processes message

Long Polling Server receives HTTP request, processes message, and publishes to Message Broker

Protocol:Kafka Publish
BeforeLong Polling Server has received HTTP long polling request with message
AfterMessage published to Kafka topic for durable storage and distribution
SSE Server

Processes message

SSE Server receives event data and publishes to Message Broker

Protocol:Kafka Publish
BeforeSSE Server has received event data to push
AfterMessage published to Kafka topic for durable storage and distribution
Message Broker

Stores and forwards

Kafka stores message durably and forwards to subscribers or storage

Protocol:Kafka internal replication
BeforeMessage just published to Kafka topic
AfterMessage durably stored and ready for consumption by downstream systems
Storage

Persists message

Storage system writes message to persistent database for history and retrieval

Protocol:DB write
BeforeMessage available in Kafka for persistence
AfterMessage safely stored in database for future queries
🏗️
Architecture Diagram
Architecture Diagram
┌─────────┐
│ Client  │
└─────┬───┘
      │ HTTP/WebSocket
      ▼
┌───────────────┐
│ Load Balancer │
└─────┬─────────┘
      │ Routes based on protocol
      ▼
┌───────────────────────┐
│ WebSocket Server      │
│ (maintains WS conns)  │
└─────┬─────────────────┘
      │ Kafka Publish
      ▼
┌───────────────┐
│ Message Broker│
│ (Kafka cluster)│
└─────┬─────────┘
      │ Stores messages durably
      ▼
┌─────────┐
│ Storage │
│ (DB)    │
└─────────┘
      ▲
      │
┌───────────────────────────────┐
│ Long Polling Server            │
│ (handles HTTP long polling)   │
└─────┬─────────────────────────┘
      │ Kafka Publish
      ▼
┌─────────────────────┐
│ SSE Server          │
│ (pushes events over HTTP)│
└─────┬────────────────┘
      │ Kafka Publish
      ▼

This architecture compares three client-server communication methods: WebSocket, Long Polling, and Server-Sent Events (SSE). The Load Balancer routes client requests based on protocol to the appropriate server type. Each server processes incoming messages and publishes them to a Kafka-based Message Broker, which durably stores and distributes messages. Finally, messages are persisted in a Storage database for history. WebSocket Servers maintain persistent bidirectional connections, ideal for real-time interactive apps. Long Polling Servers handle repeated HTTP requests for near-real-time updates, suitable for legacy clients. SSE Servers push unidirectional event streams over HTTP, useful for live feeds. This design highlights trade-offs in connection persistence, protocol overhead, and scalability.

Primary Focus

✓

Practice

(1/5)
1. For candidate-job matching, which architecture better supports real-time personalized recommendations with low latency and frequent profile updates?
medium
A. Precomputed static candidate-job similarity scores stored in a relational database
B. Batch processing with nightly offline model training and periodic reindexing
C. Online feature store with streaming updates feeding a real-time scoring service
D. Client-side filtering of job listings based on cached candidate preferences

Solution

  1. Step 1: Analyze real-time personalization needs

    Low latency and frequent profile updates require online, streaming data processing.
  2. Step 2: Evaluate architectures

    Batch (A) is too stale; static precomputed scores (C) can't adapt quickly; client-side filtering (D) lacks server-side intelligence. Online feature store with streaming (B) supports fresh data and low latency scoring.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Streaming updates + real-time scoring -> fresh personalized matches [check]
Hint: Streaming + online features enable fresh real-time recommendations [check]
Common Mistakes:
2. At 10x scale, which component in the alerting system is most likely to become the bottleneck first, and why?
hard
A. Anomaly detection engine, because complex ML models require exponential compute as data volume grows
B. Event ingestion pipeline, due to limited write throughput and storage I/O constraints
C. Composite alert processor, because combining many alerts requires stateful joins that grow quadratically
D. Threshold alerting component, since static limit checks are CPU-light and easily parallelizable

Solution

  1. Step 1: Identify scale bottlenecks

    At 10x scale, write throughput and storage I/O become critical constraints for ingestion pipelines.
  2. Step 2: Compare component scalability

    Anomaly detection can be scaled horizontally; composite alerting state grows but less than ingestion I/O; threshold checks are lightweight.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Ingestion pipeline limited by write throughput and storage I/O [check]
Hint: 10x scale -> ingestion pipeline hits write I/O bottleneck first [check]
Common Mistakes:
3. At 10x current scale, which component in the YouTube view count system is most likely to fail first, and why?
hard
A. The CDN edge caches because they cannot handle the increased video delivery requests
B. The view count database because it is a centralized bottleneck for high write throughput
C. The transcoding pipeline because it cannot process 10x more video uploads in time
D. The upload service because it cannot handle 10x concurrent upload connections

Solution

  1. Step 1: Analyze component scalability at 10x load

    CDN edge caches (A) scale horizontally and are designed for massive read throughput. Transcoding pipeline (C) can be scaled with more workers. Upload service (D) can be scaled with load balancers and stateless servers.
  2. Step 2: Identify view count database bottleneck

    View count DB is a centralized write hotspot with high contention and latency sensitivity. At 10x scale, it becomes the first bottleneck due to write amplification and consistency requirements.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Centralized view count DB write bottleneck fails first [check]
Hint: Centralized DB write bottleneck breaks first at scale [check]
Common Mistakes:
4. At 10x scale, which MongoDB component is most likely to become the bottleneck first when using the bucket pattern for time-series data, and why?
hard
A. The application server, because it cannot generate bucket IDs fast enough for writes.
B. The MongoDB query router (mongos), because it must maintain metadata for all buckets and route writes precisely.
C. The shard servers, because bucket documents grow large and cause frequent document splits and index overhead.
D. The network layer, because increased bucket writes saturate bandwidth between shards.

Solution

  1. Step 1: Identify bucket pattern scaling challenges

    Bucket pattern creates many bucket documents requiring precise routing by mongos.
  2. Step 2: Mongos metadata overhead

    Mongos maintains routing metadata and must route each write to correct shard and bucket, increasing load at scale.
  3. Step 3: Compare other components

    Shard servers handle writes but document splits are less frequent; network saturates later; app server bottleneck unlikely.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Mongos routing metadata load grows fastest at 10x scale [check]
Hint: Mongos routing metadata overload is first bottleneck at scale [check]
Common Mistakes:
5. At 10x scale, which component in a full-text search system is most likely to become the bottleneck first, and why?
hard
A. The inverted index storage nodes, because random disk seeks increase dramatically with index size
B. The distributed log system (Kafka), because partition count limits throughput and causes uneven load
C. The indexing workers, because they must process and merge a growing volume of update events in real-time
D. The query router, because it must maintain stateful TCP connections to all index shards

Solution

  1. Step 1: Analyze query router bottleneck

    Query routers are typically stateless or use connection pooling; they scale horizontally well, so (A) is less likely.
  2. Step 2: Evaluate inverted index storage nodes

    As index size grows 10x, random disk seeks increase non-linearly, causing latency spikes and throughput degradation, making (B) the primary bottleneck.
  3. Step 3: Consider indexing workers and Kafka

    Indexing workers and Kafka scale with partitioning and parallelism, so (C) and (D) are secondary bottlenecks.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Disk seek latency grows fastest, limiting index node throughput [check]
Hint: Disk seeks grow fastest, hitting index storage nodes first [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard