# Cheat Sheet — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-cheatsheet

> Recall the key facts about SSE and WebSockets on one page before an exam or interview.

## Everything on one page

**Polling**: short polling asks on a timer; long polling holds the request until news arrives. Always resume from a cursor. **SSE**: `Content-Type: text/event-stream`; fields `data`, `event`, `id`, `retry`; `:` starts a comment; a blank line dispatches. EventSource is GET-only with no custom headers, reconnects automatically and sends `Last-Event-ID`; text only; watch the HTTP/1.1 limit of about six connections per origin. **WebSocket**: HTTP GET with `Upgrade: websocket`, answered by `101 Switching Protocols` and `Sec-WebSocket-Accept` (SHA-1 of key plus GUID, base64). Opcodes: text 1, binary 2, close 8, ping 9, pong A. Client frames are masked. Close codes: 1000 normal, 1001 going away, 1006 abnormal (never sent), 1008 policy, 1009 too big, 1011 server error. **Production**: heartbeats plus `terminate()`, jittered exponential backoff with resume, pub/sub fan-out across servers, `bufferedAmount` for backpressure, Origin allow-lists, short-lived tickets, `maxPayload`, rate limits and `wss://` everywhere.

## The whole course as one path

Every real-time feature follows the same path: choose the transport, build the protocol on top, scale it beyond one server, and secure it.

![Four connected stages in order: choose a transport, build the message protocol, scale across servers, secure the endpoints.](assets/figures/realtime-web/section-10-map.svg) — Figure 10.1: choose transport -> build protocol -> scale out -> secure

## Memorise by pairs

Learn facts in contrasting pairs: SSE versus WebSocket (one-way text versus two-way text and binary), 1000 versus 1006 (clean versus no close frame), `close()` versus `terminate()` (handshake versus immediate), pub/sub versus streams (fire-and-forget versus replayable). Examiners love the contrast.

**Quiz:** Which pair is correctly matched?

- [ ] Opcode 0x9: pong
- [ ] Close code 1006: sent by the server during deploys
- [x] `Last-Event-ID`: header sent by a reconnecting EventSource
- [ ] `Sec-WebSocket-Accept`: encrypts the session key

*Answer:* `Last-Event-ID`: header sent by a reconnecting EventSource. EventSource sends `Last-Event-ID` when it reconnects. 0x9 is ping (0xA is pong), 1006 is never sent on the wire, and the accept header is a handshake check, not encryption.
