Bird
Raised Fist0
Interview Prepcomputer-networksmediumAmazonGoogleFlipkartSwiggyRazorpayCREDZepto

WebSockets vs HTTP Long Polling vs SSE - Real-Time Comparison

Choose your preparation mode3 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Steps
setup

Setup: Initialize Client and Server Nodes

We create the client and server nodes and set their initial states to idle, preparing for the connection attempts of WebSockets, HTTP Long Polling, and SSE.

💡 Setting up nodes is essential to visualize the packet flow and state changes clearly for each protocol.
Line:client = Node('client', 'idle') server = Node('server', 'idle')
💡 Understanding the roles of client and server nodes is foundational before observing their interactions.
📊
WebSockets vs HTTP Long Polling vs SSE - Real-Time Comparison - Watch the Algorithm Execute, Step by Step
Watching each packet and state change helps you understand the fundamental differences in connection persistence, data flow, and latency between these real-time communication methods.
Step 1/10
·Active fillAnswer cell
Initialized client and server nodes in idle state.
Hop: 0
Client
Server
Client sent WebSocket handshake HTTP Upgrade request.
Hop: 1
Client
Server
📦Packet
fromclient
toserver
📄 payloadGET /chat HTTP/1.1 Upgrade: websocket Connection: Upgrade
🔌 protocolHTTP
🚩 flagsUpgrade
srcclient_ip:12345
dstserver_ip:80
dataGET /chat HTTP/1.1 Upgrade: websocket Connection: Upgrade
flagsUpgrade
WebSocket Handshake Request: client→server
Server accepted WebSocket upgrade, connection now persistent.
Hop: 2
Client
Server
📦Packet
fromserver
toclient
📄 payloadHTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade
🔌 protocolHTTP
🚩 flags101 Switching Protocols, Upgrade
srcserver_ip:80
dstclient_ip:12345
dataHTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade
flags101 Switching Protocols, Upgrade
WebSocket Handshake Request: client→server
WebSocket Handshake Response: server→client
Client sent HTTP Long Polling request.
Hop: 3
Client
Server
📦Packet
fromclient
toserver
📄 payloadGET /updates HTTP/1.1
🔌 protocolHTTP
🚩 flags
srcclient_ip:12346
dstserver_ip:80
dataGET /updates HTTP/1.1
WebSocket Handshake Request: client→server
WebSocket Handshake Response: server→client
Long Polling Request: client→server
Server holds long polling request open, waiting for data.
Hop: 3
Client
Server
WebSocket Handshake Request: client→server
WebSocket Handshake Response: server→client
Long Polling Request: client→server
Server sent long polling response with new data.
Hop: 4
Client
Server
📦Packet
fromserver
toclient
📄 payloadHTTP/1.1 200 OK Content-Type: text/event-stream New data
🔌 protocolHTTP
🚩 flags200 OK
srcserver_ip:80
dstclient_ip:12346
dataNew data
flags200 OK
WebSocket Handshake Response: server→client
Long Polling Request: client→server
Long Polling Response: server→client
Client sent SSE HTTP request to open event stream.
Hop: 5
Client
Server
📦Packet
fromclient
toserver
📄 payloadGET /events HTTP/1.1 Accept: text/event-stream
🔌 protocolHTTP
🚩 flagsAccept: text/event-stream
srcclient_ip:12347
dstserver_ip:80
dataGET /events HTTP/1.1 Accept: text/event-stream
flagsAccept: text/event-stream
Long Polling Request: client→server
Long Polling Response: server→client
SSE Request: client→server
Server accepted SSE connection and keeps it open.
Hop: 6
Client
Server
📦Packet
fromserver
toclient
📄 payloadHTTP/1.1 200 OK Content-Type: text/event-stream
🔌 protocolHTTP
🚩 flags200 OK
srcserver_ip:80
dstclient_ip:12347
flags200 OK
Long Polling Response: server→client
SSE Request: client→server
SSE Response: server→client
Server sent SSE event data over persistent connection.
Hop: 7
Client
Server
📦Packet
fromserver
toclient
📄 payloaddata: New event data
🔌 protocolHTTP
🚩 flags
srcserver_ip:80
dstclient_ip:12347
datadata: New event data
SSE Request: client→server
SSE Response: server→client
SSE Event Data: server→client
Summary of protocol differences and connection states.
Hop: 7
Client
Server
SSE Request: client→server
SSE Response: server→client
SSE Event Data: server→client

Key Takeaways

WebSockets establish a persistent, full-duplex connection after an HTTP Upgrade handshake.

This insight is hard to see from code alone because the handshake and protocol switch are subtle but critical.

HTTP Long Polling simulates real-time by holding HTTP requests open and repeatedly reconnecting.

Visualizing the open-hold-respond cycle clarifies why long polling is less efficient and has higher latency.

SSE maintains a single persistent HTTP connection for server push, combining simplicity with efficiency.

Seeing the continuous data flow over one connection helps understand SSE's advantages over long polling.

Practice

(1/5)
1. When a user requests a web page through a CDN, what is the correct sequence of events if the requested content is not present in the edge cache?
easy
A. Edge server returns an error; user retries directly to origin server
B. Edge server serves stale cached content while asynchronously fetching fresh content
C. DNS server redirects user to origin server bypassing edge server
D. Edge server forwards request to origin server, caches response, then serves user

Solution

  1. Step 1: User request reaches edge server

    The edge server checks its cache for the requested content.
  2. Step 2: Cache miss triggers origin fetch

    If content is missing, the edge server forwards the request to the origin server.
  3. Step 3: Edge server caches the origin response

    Once the origin server responds, the edge server caches the content for future requests.
  4. Step 4: Edge server serves content to user

    The user receives the content from the edge server, reducing latency for subsequent requests.
  5. Final Answer:

    Option D -> Option D
  6. Quick Check:

    Edge servers act as intermediaries that fetch and cache content on cache misses.
Hint: Cache miss -> edge fetches origin -> caches -> serves user
Common Mistakes:
  • Assuming edge server returns error on cache miss
  • Thinking DNS redirects user directly to origin
  • Believing stale content is served without user awareness
2. In which scenario is the IP Hash load balancing algorithm most appropriate compared to Round Robin or Least Connections?
easy
A. When you need to ensure session persistence by routing requests from the same client IP to the same server
B. When servers have highly variable processing speeds and you want to balance load evenly
C. When the number of active connections per server is constantly changing and you want to minimize response time
D. When you want to distribute requests strictly in a cyclic order regardless of client identity

Solution

  1. Step 1: Understand IP Hash purpose

    IP Hash uses the client's IP address to consistently route requests to the same backend server, enabling session persistence (sticky sessions).
  2. Step 2: Why not Round Robin or Least Connections?

    Round Robin distributes requests evenly without regard to client identity, so it does not guarantee session persistence. Least Connections balances based on current load but also does not ensure the same client hits the same server.
  3. Step 3: Match scenarios to algorithms

    When you need to ensure session persistence by routing requests from the same client IP to the same server correctly identifies the scenario where IP Hash is preferred: session persistence. Options A and C describe scenarios better suited for Least Connections or Round Robin. When you want to distribute requests strictly in a cyclic order regardless of client identity describes Round Robin behavior.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    IP Hash -> session stickiness; Round Robin -> cyclic distribution; Least Connections -> load-aware balancing.
Hint: IP Hash = sticky sessions by client IP
Common Mistakes:
  • Confusing Least Connections with session persistence
  • Assuming Round Robin can maintain client affinity
  • Believing IP Hash balances load evenly regardless of client IP distribution
3. Trace the sequence of events when an external client accesses an internal web server via port forwarding configured on a NAT router.
easy
A. The router changes the destination IP and port to the internal server's IP and port, forwards the packet, and rewrites the source IP of the reply back to the router's public IP.
B. The router changes the destination IP and port to the internal server's IP and port, then forwards the packet; the server replies directly to the client.
C. The router only changes the destination IP but leaves the port unchanged; the internal server receives the packet and replies to the router.
D. The router forwards the packet without any translation; the internal server replies directly to the external client.

Solution

  1. Step 1: Understand port forwarding (DNAT)

    Port forwarding rewrites destination IP and port of incoming packets to internal server's IP and port.
  2. Step 2: Trace reply path

    The server replies to the router's internal IP, which rewrites the source IP back to its public IP before sending to the external client.
  3. Step 3: Analyze options

    The router changes the destination IP and port to the internal server's IP and port, forwards the packet, and rewrites the source IP of the reply back to the router's public IP correctly describes both forward and reply translation. The router changes the destination IP and port to the internal server's IP and port, then forwards the packet; the server replies directly to the client is incorrect because the server cannot reply directly to the client without NAT rewriting. The router only changes the destination IP but leaves the port unchanged; the internal server receives the packet and replies to the router misses port translation. The router forwards the packet without any translation; the internal server replies directly to the external client ignores NAT translation entirely.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Port forwarding requires bidirectional NAT translation [OK]
Hint: Port forwarding rewrites destination IP/port inbound and source IP outbound
Common Mistakes:
  • Assuming server replies directly to external client
  • Forgetting port translation in forwarding
  • Ignoring reply path NAT rewriting
4. Which of the following statements about subnet masks is INCORRECT?
medium
A. A subnet mask separates the network and host portions of an IP address by masking bits
B. The subnet mask must always be contiguous ones followed by zeros in binary
C. Changing the subnet mask does not affect the total number of IP addresses in the network
D. Subnet masks can be represented in dotted decimal or CIDR notation

Solution

  1. Step 1: Review subnet mask function

    Subnet masks define network and host bits, affecting subnet size and number of IP addresses.
  2. Step 2: Analyze each statement

    A subnet mask separates the network and host portions of an IP address by masking bits is true; subnet masks separate network and host bits. The subnet mask must always be contiguous ones followed by zeros in binary is true; subnet masks must be contiguous ones then zeros. Subnet masks can be represented in dotted decimal or CIDR notation is true; subnet masks can be in dotted decimal or CIDR.
  3. Step 3: Identify incorrect statement

    Changing the subnet mask does not affect the total number of IP addresses in the network is false; changing subnet mask changes subnet size and total IP addresses available.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Subnet mask directly impacts number of IP addresses in a subnet [OK]
Hint: Subnet mask length controls subnet size and IP count
Common Mistakes:
  • Believing subnet masks can have non-contiguous bits
  • Thinking subnet mask changes don't affect IP count
  • Confusing subnet mask notation formats
5. What is a key limitation of Port Address Translation (PAT) when many internal hosts simultaneously initiate outbound connections to the internet?
medium
A. PAT cannot translate destination IP addresses, so inbound connections are impossible
B. PAT requires a unique public IP per internal host, increasing IP address consumption
C. PAT can run out of available source ports, limiting the number of simultaneous connections
D. PAT causes all internal hosts to share the same source port, causing packet collisions

Solution

  1. Step 1: Recall PAT function

    PAT maps multiple internal IP:port pairs to a single public IP with unique source ports.
  2. Step 2: Identify limitation

    Since TCP/UDP ports are 16-bit, only ~65,000 ports are available per public IP, limiting simultaneous connections.
  3. Step 3: Analyze options

    PAT can run out of available source ports, limiting the number of simultaneous connections correctly identifies port exhaustion. PAT requires a unique public IP per internal host, increasing IP address consumption is false; PAT uses one public IP for many hosts. PAT cannot translate destination IP addresses, so inbound connections are impossible is unrelated to PAT's outbound translation. PAT causes all internal hosts to share the same source port, causing packet collisions is false; PAT assigns unique ports to avoid collisions.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    PAT port exhaustion limits simultaneous connections [OK]
Hint: PAT multiplexes ports but port space is finite
Common Mistakes:
  • Thinking PAT needs multiple public IPs
  • Confusing PAT with DNAT limitations
  • Believing PAT uses the same source port for all hosts