WebSockets - For Real-Time APIs

While HTTP is great for request-response communication, but it struggles with real-time use cases like live chats, multiplayer games or collaborative editors. That’s where WebSockets shine.

Why WebSockets over HTTP ?

CharacteristicHTTPWebSocket
Communication StyleHalf-duplex (one way at a time)Full-duplex (bidirectional)
Connection TypeStateless, closes after requestPersistent, stays open
Connection LifecycleNew connection per requestSingle long-lived connection
Message InitiationClient-onlyBoth client and server
Server PushRequires workarounds (polling, SSE)Native support
OverheadHeaders sent with each requestOne-time handshake, minimal after
State ManagementRequires external mechanisms (cookies, sessions)Built-in connection state
Best Used ForRegular web requests, CRUD operationsReal-time updates, streaming data

How WebSockets Work ?

  1. The client sends an HTTP request with an Upgrade header:

    GET /chat HTTP/1.1
    Host: example.com
    Upgrade: websocket
    Connection: Upgrade
    
  2. The server accepts and switches protocols:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    
  3. The connection is upgraded from HTTP to WebSocket.

  4. Both sides can now send and receive messages asynchronously, without re-opening the connection.


HTTP workarounds !

Though if you are using HTTP for near real-time apps, following are the workarounds -

  • Short Polling - Client repeatedly asks for updates. Has high latency.
  • Long Polling - Client holds request open until update. Delayed responses and HTTP overhead.
  • HTTP Streaming - Keeps connection open to stream data. Works but still one-directional.

Conclusion

Despite using TCP like HTTP, WebSockets are more efficient because they eliminate the overhead of re-sending HTTP headers for every message.