| |

Internet Frontend 08 ๐ŸŒ WebSockets vs Server-Sent Events

โฑ๏ธ Estimated read: 10 min | |

The choice between WebSockets and Server-Sent Events is not a choice between modern and legacy. It is a choice about the direction of the data flow. WebSockets provide a full-duplex channel: the client and the server can send messages to each other at any time, over a single connection that starts as an HTTP request and is upgraded to the WebSocket protocol. Server-Sent Events provide a unidirectional channel: the server pushes events to the client, and the client does not send messages back over the same connection. The direction is the constraint that determines which protocol fits the use case.

The WebSocket handshake is an HTTP Upgrade request. The server responds with 101 Switching Protocols, and the connection becomes a raw TCP socket that both sides can write to. The frames are small, the latency is low, and the protocol is designed for the interactive applications where the client sends as often as the server . The SSE connection is an ordinary HTTP response with the Content-Type: text/event-stream header. The response never ends, and the server writes events in a text format that the browser’s EventSource parses. The connection is one-way, and the client cannot send data back over the same channel .

Key point: WebSockets are full-duplex and require a protocol upgrade. Server-Sent Events are unidirectional, run over plain HTTP, and include automatic reconnection with Last-Event-ID resume. The choice is the direction of the data flow, not the novelty of the protocol.


Why the direction of the data flow is the decision

The interactive problem. A chat application, a multiplayer game, or a collaborative editor requires the client to send messages as often as the server. The WebSocket is the correct choice because the connection is bidirectional and the frames are small. The SSE connection would require a separate HTTP request for every client message, which defeats the purpose of the persistent connection .

The push-only problem. A news feed, a stock ticker, a notification stream, or an AI chat completion requires the server to push data to the client, and the client does not need to send anything back over the same channel. The SSE is the correct choice because the connection is simpler, it runs over plain HTTP, and the browser handles the reconnection automatically. The EventSource API is built into the browser, and the server implementation is a plain HTTP response that never ends .

The reconnection problem. The SSE specification includes the reconnection logic. The browser retries the connection with the retry delay, and it sends the Last-Event-ID header with the last event ID it received, so the server can resume the stream from the correct position. The WebSocket specification does not include the reconnection logic. A raw WebSocket connection simply closes when the network drops, and the application must implement the exponential backoff, the missed-message recovery, and the resume protocol . The reconnection is the hidden cost of the WebSocket, and it is the reason the SSE is the simpler choice for the push-only case.

The trade-off. The WebSocket is more capable, but it is also more complex. The SSE is less capable, but it is simpler and it handles the reconnection. The choice is the trade-off between the capability and the simplicity, and the direction of the data flow is the deciding factor.


a. The WebSocket mechanism and the full-duplex case

The WebSocket connection starts as an HTTP request with the Upgrade: websocket header. The server responds with 101 Switching Protocols, and the connection becomes a raw TCP socket that both sides can write to. The frames are small (2โ€“14 bytes of overhead), and the latency is low .

// The WebSocket client
const socket = new WebSocket('wss://example.com/chat');

socket.addEventListener('open', () => {
  socket.send(JSON.stringify({ type: 'join', room: 'general' }));
});

socket.addEventListener('message', (event) => {
  const message = JSON.parse(event.data);
  console.log('Received:', message);
});

The client sends the join message when the connection opens, and the server sends the messages when they arrive. The connection is bidirectional, and the client can send a message at any time. The reconnection logic is not built in; the application must implement it .

The wss:// scheme is the WebSocket over TLS. The connection is encrypted, and the proxy support is broad, but the Upgrade header can be stripped by some proxies and firewalls, which causes the connection to fail .


b. The SSE mechanism and the push-only case

The SSE connection is an HTTP request that receives a response with the Content-Type: text/event-stream header. The response never ends, and the server writes events in the text format.

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

id: 1
event: message
data: {"text": "Hello"}

id: 2
event: message
data: {"text": "World"}
// The SSE client
const source = new EventSource('/stream');

source.addEventListener('message', (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
});

source.addEventListener('error', () => {
  console.log('The connection will retry automatically.');
});

The EventSource API is built into the browser. The connection is one-way: the server sends the events, and the client receives them. The client cannot send data back over the same connection; it must use a separate HTTP request .

The SSE reconnection is automatic. The browser retries the connection with the retry delay, and it sends the Last-Event-ID header with the last event ID it received, so the server can resume the stream . The id field in the event is the mechanism that makes the resume possible.

The SSE limitation is the connection limit over HTTP/1.1. The browser limits the number of the SSE connections per domain to six, and the limit is shared across all the tabs. The HTTP/2 removes the limit because the multiplexing allows the many streams over a single connection . The limitation is the reason a production SSE deployment should use HTTP/2.


Complete Example Session

// ============================================
// PART 1: THE WEBSOCKET CLIENT
// ============================================

const socket = new WebSocket('wss://example.com/chat');

socket.addEventListener('open', () => {
  socket.send(JSON.stringify({ type: 'join', room: 'general' }));
});

socket.addEventListener('message', (event) => {
  const message = JSON.parse(event.data);
  console.log('Received:', message);
});

socket.addEventListener('close', () => {
  // The reconnection logic is the application's responsibility.
  setTimeout(connect, 1000);
});

// ============================================
// PART 2: THE SSE CLIENT
// ============================================

const source = new EventSource('/stream');

source.addEventListener('message', (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
});

source.addEventListener('error', () => {
  // The browser retries automatically.
  // The Last-Event-ID is sent with the retry.
});

// ============================================
// PART 3: THE SERVER-SIDE SSE EVENT
// ============================================

// The event format:
// id: 1
// event: message
// data: {"text": "Hello"}

// The id field is the resume mechanism.
// The event field is the named event.
// The data field is the payload.

// ============================================
// PART 4: THE DIRECTION DECISION
// ============================================

// The chat: the client sends and receives.
// The WebSocket is the correct choice.

// The notification feed: the server sends only.
// The SSE is the correct choice.

// ============================================
// PART 5: THE RECONNECTION
// ============================================

// The WebSocket: the application implements the reconnection.
// The SSE: the browser implements the reconnection.
// The Last-Event-ID is the SSE resume mechanism.

// ============================================
// PART 6: THE CONNECTION LIMIT
// ============================================

// The SSE over HTTP/1.1: six connections per domain.
// The limit is shared across the tabs.
// The HTTP/2 removes the limit.

// ============================================
// PART 7: THE BINARY DATA
// ============================================

// The WebSocket: the text and binary frames.
// The SSE: the UTF-8 text only.

// ============================================
// PART 8: THE PROXY AND FIREWALL
// ============================================

// The WebSocket: the Upgrade header can be stripped.
// The SSE: the plain HTTP response, the proxy-friendly.

// ============================================
// PART 9: THE AI STREAMING USE CASE
// ============================================

// The AI chat completion: the server streams the tokens.
// The client does not send the tokens back.
// The SSE is the correct choice.
// The LLM APIs stream the completions as text/event-stream.

// ============================================
// PART 10: THE CHECKLIST
// ============================================

// [ ] The direction of the data flow is identified.
// [ ] The WebSocket is chosen for the bidirectional communication.
// [ ] The SSE is chosen for the server-to-client push.
// [ ] The SSE deployment uses HTTP/2 if the many connections are expected.
// [ ] The WebSocket reconnection logic is implemented.
// [ ] The SSE Last-Event-ID resume is handled on the server.

The ten parts covered the WebSocket client, the SSE client, the server-side SSE event, the direction decision, the reconnection, the connection limit, the binary data, the proxy and firewall, the AI streaming use case, and the checklist. The through-line is that the direction of the data flow is the deciding factor.


Quick Reference

The protocol comparison

AspectWebSocketsSSE
DirectionFull-duplexServer-to-client only
ProtocolHTTP upgrade to WebSocketPlain HTTP
ReconnectionApplication codeBuilt-in, with Last-Event-ID
Data typeText and binaryUTF-8 text only
Browser support99%+98%+
Connection limitNone6 per domain over HTTP/1.1
ComplexityMedium to highLow

The use cases

Use caseProtocol
ChatWebSocket
Multiplayer gameWebSocket
Collaborative editorWebSocket
News feedSSE
Notification streamSSE
AI chat completionSSE
Stock tickerSSE

The reconnection

AspectWebSocketSSE
Retry logicApplicationBrowser
ResumeApplicationLast-Event-ID
Missed messagesApplicationServer buffer

Best Practices

โœ… Do This:

// Use the WebSocket for the bidirectional communication
const socket = new WebSocket('wss://example.com/chat');
// Use the SSE for the server-to-client push
const source = new EventSource('/stream');
// Use the SSE over HTTP/2 to avoid the connection limit
Content-Type: text/event-stream

โŒ Don’t Do This:

// Use the SSE for the bidirectional communication
// The client cannot send messages back over the same connection.
// Use the WebSocket for the simple push-only feed
// The reconnection logic is the unnecessary complexity.

Common Pitfalls

PitfallWhy It HappensFix
The SSE connection is blockedThe HTTP/1.1 connection limitUse HTTP/2
The WebSocket connection dropsThe network change or the proxyImplement the reconnection logic
The SSE events are bufferedThe proxy buffers the responseUse the X-Accel-Buffering: no header
The WebSocket is stripped by the proxyThe Upgrade header is removedUse the SSE or the WSS over the port 443

Summary

ItemValue
WebSocketFull-duplex, protocol upgrade, application-managed reconnection
SSEUnidirectional, plain HTTP, built-in reconnection
Decision factorThe direction of the data flow
SSE limit6 per domain over HTTP/1.1, removed by HTTP/2
SSE resumeLast-Event-ID
WebSocket binarySupported
SSE binaryNot supported

Key takeaways:

  • The direction of the data flow is the decision. The WebSocket is full-duplex, and the SSE is unidirectional. The chat, the game, and the collaborative editor need the WebSocket. The news feed, the notification stream, and the AI completion need the SSE .
  • The SSE reconnection is built into the browser. The EventSource retries with the retry delay, and it sends the Last-Event-ID header with the last event ID, so the server can resume the stream. The WebSocket reconnection is the application’s responsibility, and it is the most underestimated cost of the WebSocket .
  • The SSE connection limit is the HTTP/1.1 constraint. The browser limits the number of the SSE connections per domain to six, and the limit is shared across the tabs. The HTTP/2 removes the limit because the multiplexing allows the many streams over a single connection .
  • The SSE is the proxy-friendly choice. The SSE runs over plain HTTP, and the proxies and the CDNs understand it. The WebSocket requires the Upgrade header, which some proxies and firewalls strip .
  • The SSE is the AI streaming choice. The LLM APIs stream the completions as text/event-stream because the token-by-token output is strictly one-directional, text-only, and it benefits from the plain HTTP and the built-in resume semantics .

Remember: The WebSocket and the SSE solve the real-time communication at different levels. The WebSocket is the full-duplex channel for the interactive applications where the client sends as often as the server. The SSE is the unidirectional channel for the push-only applications where the server sends and the client receives. The direction of the data flow is the deciding factor, and the reconnection, the binary data, and the connection limit are the secondary considerations. The choice is not about the novelty; it is about the fit.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!