Skip to content

Real-Time Communication: Short/Long Polling, SSE, WebSockets, Scaling Connections, Presence ​

"The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code." — RFC 6455, The WebSocket Protocol, Abstract (December 2011)

Summary: HTTP was built for "ask, then get an answer". Real-time features (chat, notifications, live dashboards, tracking a driver, prices that tick) need the server to speak first. There are four ways to fake or provide that (short polling, long polling, Server-Sent Events, WebSockets), and every one of them turns into the same three system problems at scale: holding many idle connections cheaply, fanning a message out to the right connections on many servers, and knowing who is online. Focus: The four techniques and their wire formats (hanging GET, text/event-stream, retry, Last-Event-ID, RFC 6455 upgrade, frames, opcodes, ping/pong, close codes, subprotocols, permessage-deflate), the browser limits (6 connections per host on HTTP/1.1), WebTransport and WebRTC data channels by contrast, choosing per use case, scaling connections (C10K/C10M, memory per connection, event loops, sticky vs stateless gateways, Redis Pub/Sub fan-out, sharding, idle timeouts on AWS ALB and NGINX, draining, reconnection storms with jitter), presence (heartbeats, TTL keys, last seen, multi-device), ordering and delivery (sequence numbers, cursors, resume, at-least-once plus dedup), socket auth (tickets, origin checks), and the products (Pusher protocol, Laravel Reverb and Echo, Socket.IO, Centrifugo, Ably, Phoenix Channels, AWS API Gateway WebSocket APIs, Cloudflare Durable Objects). Learning goal: For any real-time feature, pick the transport and say why, size the connection tier with numbers, design fan-out that survives a node loss, make reconnects lossless and duplicate-safe, keep presence correct across devices, and ship it in Go or Laravel without a reconnection storm on the next deploy.

This chapter sits in the Networking & Protocols group after HTTP/1.1, HTTP/2, HTTP/3, which owns multiplexing, keep-alive and HTTP/2 streams; it uses them without re-teaching them. Sockets, ports and file descriptors on one host are in Ports, Sockets & Connections; TCP behaviour is in TCP & UDP; TLS on the wire in TLS in Practice. Load balancer algorithms and affinity live in Load Balancing and proxy timeouts in Forward vs Reverse Proxies. Delivery semantics are owned by Delivery Guarantees, dedup tables by Idempotent Consumers & the Inbox, Redis Pub/Sub and Streams by Redis Streams & Pub/Sub and Redis. Collaborative editing needs CRDTs and Vector Clocks; this page only says when. Cookies and CORS are in Web Sessions, Cookies & CORS. This page owns the system-level decision, the numbers and the worked designs.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why HTTP needs tricks to pushWhy it exists
Comet, C10K, RFC 6202, RFC 6455, EventSourceWhere it comes from
Short polling and long pollingShort polling, Long polling
EventSource, text/event-stream, Last-Event-IDServer-Sent Events
Upgrade, 101, frames, ping/pong, close codesWebSocket, Heartbeats, Close codes
Subprotocols, permessage-deflateSubprotocols and compression
Slow clients, bounded queuesBackpressure
HTTP/2 and HTTP/3 WebSockets, WebTransport, WebRTCBeyond WebSocket
Sequence numbers, resume, dedupOrdering and delivery
Tickets, tokens, Origin, CSWSHAuth for sockets
Who is onlinePresence
C10K, memory per connection, event loopsHolding connections
Sticky vs stateless, Redis fan-out, shardingFan-out across servers
Deploys, draining, reconnection stormsDraining and storms
Pusher, Reverb, Socket.IO, Centrifugo, Ably, Phoenix, API Gateway, Durable ObjectsProducts
Wire formats, knobs, error text, capacity mathMechanics
CodeGo, Laravel
Classic failures and their fixesSolving the classic problems
Which technique for which featureChoosing
Monolith to distributed systemIn architecture
Measured connection cost, resume, jitterLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four techniques.

TechniqueIn plain wordsDirectionBrowser APIResume after a dropMain cost
Short pollingAsk every N secondsClient pullsfetch in a timerSend your cursorRequests with no news; latency about N/2
Long polling (hanging GET)Ask, and the server answers only when there is news or a timeoutClient pulls, server delaysfetch in a loopCursor in every requestOne held request per client; a full HTTP message per event
Server-Sent Events (SSE)One HTTP response that never ends; the server writes events into itServer to clientEventSourceBuilt in: id: and Last-Event-IDOne held connection; 6 per host on HTTP/1.1
WebSocketUpgrade one connection, then both sides send frames any timeBothWebSocketYou build it (sequence numbers)Stateful servers; you own heartbeats, auth, reconnect

What breaks first at scale.

ProblemSymptomFix on this page
Idle timeout on a proxyEvery connection dies after 60 s (NGINX, AWS ALB defaults)Heartbeats below the smallest timeout (Heartbeats)
Users on different serversMessage reaches half the roomPub/sub fan-out between gateways (Fan-out)
Messages missed during a reconnectGaps in chat, stale dashboardSequence numbers plus resume from a cursor (Ordering)
Duplicates after a retryMessage shown twiceClient-generated ids, client dedup (Ordering)
Slow clientMemory grows until the gateway is killedBounded per-connection queue, disconnect slow consumers (Backpressure)
Deploy or crashEveryone reconnects in the same secondDrain over minutes, backoff with full jitter (Storms)
Ghost users onlinePresence shows people who left an hour agoHeartbeat plus TTL, per-connection entries (Presence)
Cross-site page opens a socket with your cookieData leaks to an attackerOrigin allowlist, tickets (Auth)

Numbers to remember.

NumberMeaningSource
6Max HTTP/1.1 connections per browser and host, so max SSE streams across tabsMDN EventSource
100Default concurrent HTTP/2 streams negotiated by browsers and serversMDN EventSource
15 sSSE comment interval the HTML spec suggests against proxy timeoutsWHATWG HTML
30 sRFC 6202's "safer value" for a long-poll timeoutRFC 6202
60 sNGINX proxy_read_timeout default and AWS ALB idle_timeout.timeout_seconds defaultNGINX, AWS docs
10 min / 2 hAWS API Gateway WebSocket idle timeout / max connection durationAWS quotas
300 sAWS ALB default deregistration delay (draining)AWS docs
1,024stream_select open-file ceiling that limits Reverb's default event loopLaravel Reverb docs
~50 KBMeasured heap+stack per idle connection, both ends, in this page's Go hubLab, step 2
Short pollingGET every N sLong pollinghanging GETSSEtext/event-streamWebSocketRFC 6455clientserverclientserverclientserverclientserver204/same204/same200 new!204/sameheld until event200 + cursorheld (timeout 25 s)one response, never endsid: 41id: 42: ping (15 s)Upgrade101frameframeping/pongframeframelatency = interval/21 req per eventserver to clientboth directions

The picture shows the four lanes side by side. Short polling spends most of its requests on "nothing new". Long polling turns each event into one request and response, and waits on the server between them. SSE keeps one response open and writes events with ids into it. WebSocket upgrades once and then carries frames both ways, with ping/pong keeping the path alive.

Why it exists ​

HTTP is client-initiated: the server cannot send a byte unless a request is waiting for an answer. Every technique on this page is a way around that rule (polling, long polling, SSE) or a way out of it (WebSocket, WebTransport). The trade-off is always the same one: pulling is simple and stateless; pushing is fast and stateful.

Pull (short polling)Push (SSE, WebSocket)
Every request is independent; any server can answerA connection lives on one server; that server holds state
Works through every proxy, CDN and corporate firewallProxies must allow long-lived responses or the Upgrade
Latency is half the interval on averageLatency is one network transit
Cost grows with clients x frequency, even with no newsCost grows with connections held and messages sent
Loss is impossible: the next poll catches upLoss happens on every disconnect unless you resume
Scaling is the normal HTTP storyScaling needs fan-out between servers, draining, heartbeats

The analogy we reuse on this page: the restaurant pager. Short polling is walking to the kitchen every minute to ask "is my order ready?". Long polling is standing at the counter until the chef says "ready" or sends you back after 25 seconds to ask again. SSE is the buzzer pager: the kitchen can buzz you any time, but you cannot talk into it. A WebSocket is a two-way intercom. A heartbeat is the pager's periodic "still in range" blink; if it stops blinking, the host assumes you left. Presence is the host's seating chart, and the order number on every buzz is the sequence number that tells you whether you missed one.

Three common misunderstandings, up front ​

  1. "WebSocket is always the right answer for real-time." Most real-time features are one-way: notifications, dashboards, order status, AI tokens streaming. SSE does those with plain HTTP, built-in resume and no new protocol at the proxy. WebSocket earns its cost when the client also sends frequently (chat typing, games, collaborative cursors).
  2. "TCP is reliable, so my WebSocket messages cannot be lost." TCP is reliable only while the connection lives. Frames in flight when a phone switches from Wi-Fi to LTE are gone, and nothing in RFC 6455 tells either side which ones. Reliability across reconnects is something you build with sequence numbers and a resume cursor.
  3. "Scaling WebSockets means adding servers behind a load balancer." Adding servers splits the room: the sender is on node A, half the receivers on node B. You need fan-out between nodes (Redis Pub/Sub, Kafka, NATS, a managed service), and you need to survive the reconnect wave every time a node is replaced.

Where it comes from ​

The problem is as old as the web; the vocabulary settled between 1999 and 2015.

C10K, 1999. Dan Kegel's page opens with "It's time for web servers to handle ten thousand clients simultaneously, don't you think?" and notes that in 1999 cdrom.com "actually handled 10000 clients simultaneously through a Gigabit Ethernet pipe". It catalogued the I/O strategies (one thread per client, select/poll, epoll, kqueue) that every connection gateway still chooses between.

Comet and long polling, mid 2000s. Browser applications held XMLHttpRequests open or streamed into hidden iframes to get server push. RFC 6202 (April 2011) later documented the practice: long polling "attempts to minimize both the latency in server-client message delivery and the use of processing/network resources", and listed its issues: header overhead, maximal latency of "over three network transits", allocated resources, timeouts and caching.

WebSocket, December 2011. RFC 6455 standardised an opening handshake over HTTP/1.1 (Upgrade: websocket, 101 Switching Protocols) followed by "basic message framing, layered over TCP", with an origin-based security model. Its stated goal was two-way communication "that does not rely on opening multiple HTTP connections", which is exactly what long polling did.

Server-Sent Events. The WHATWG HTML Standard defines the EventSource interface and the text/event-stream format, with id, event, data and retry fields, automatic reconnection and the Last-Event-ID request header.

Compression, 2015; HTTP/2 and HTTP/3, 2018 and 2022. RFC 7692 (December 2015) added permessage-deflate. RFC 8441 (September 2018) defined "a mechanism for running the WebSocket Protocol (RFC 6455) over a single stream of an HTTP/2 connection" using extended CONNECT and SETTINGS_ENABLE_CONNECT_PROTOCOL; RFC 9220 (June 2022) did the same for HTTP/3.

WebRTC and WebTransport. WebRTC 1.0 became a W3C Recommendation in January 2021 (the current edition is dated 13 March 2025) and brought peer-to-peer data channels over SCTP. WebTransport, the client API over HTTP/3 with streams and unreliable datagrams, is a W3C Candidate Recommendation Snapshot dated 30 July 2026, not yet a Recommendation.

Scale stories. Discord's engineering blog (6 July 2017) described "nearly five million concurrent users" and said "most of it boils down to pub/sub". Slack's engineering blog (11 April 2023) described stateful Gateway Servers holding WebSocket subscriptions and Channel Servers placed on a consistent hash ring.

text
     Year   Event                                       What changed in practice
1    1999   Kegel's C10K page                            Event loops (epoll, kqueue) instead of a thread per client
2    2000s  Comet: long polling, iframe streaming        Server push over plain HTTP, with proxy pain
3    2011   RFC 6202 (April)                             Long polling documented: 30 s timeout advice
4    2011   RFC 6455 (December)                          Upgrade + frames: one connection, both directions
5    -      WHATWG EventSource, text/event-stream         Server push with built-in resume (Last-Event-ID)
6    2015   RFC 7692 permessage-deflate                  Per-message compression, memory per connection
7    2017   Discord: ~5M concurrent users                 Fan-out is the hard part, not the socket
8    2018   RFC 8441 WebSocket over HTTP/2               One TCP connection, many WebSockets
9    2021   WebRTC 1.0 Recommendation                    Unreliable, unordered data channels in browsers
10   2022   RFC 9220 WebSocket over HTTP/3               WebSocket on QUIC streams
11   2023   Slack: gateway + channel servers on a ring   Stateful gateways, consistent hashing, regional draining
12   2026   WebTransport Candidate Recommendation        Streams and datagrams over HTTP/3, not yet final

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a flow, real scenarios, how products provide it, and the fix.

Short polling Must-know ​

In plain words: the client asks "anything new?" on a timer, and the server answers immediately, usually with "no".

Common misunderstanding: "Polling is always wasteful, so never use it." With a cursor, ETag and 304 Not Modified, or a CDN in front, polling every 30 to 60 seconds is cheap, stateless and impossible to lose data with. It is the right answer for slow-changing data and for clients behind hostile networks. It is wrong when latency must be under a few seconds for many clients.

Definition: RFC 6202 describes the mechanism as retrieving updates on a schedule and warns that "the consumed resources (server processing and network) strongly depend on the acceptable latency in the delivery of updates from server to client".

text
     Client (polls every 5 s)                    Server
1    t=0   GET /orders/42/events?cursor=17
2                                                 nothing newer: 200 {events: [], cursor: 17}
3    t=5   GET ...?cursor=17                      200 {events: [], cursor: 17}
4    t=7                                          event 18 is written (order paid)
5    t=10  GET ...?cursor=17                      200 {events: [18], cursor: 18}
6          the user saw "paid" 3 s late; average delay is interval/2 = 2.5 s

Real scenario: a delivery app's order screen in its first version; an admin dashboard refreshing every 30 s; a status page; mobile apps in the background where the OS kills sockets; an IoT device that wakes every minute.

What provides it:

ProductShort-polling supportNote
Any HTTP server (Go net/http, Laravel)A normal GET endpointAdd a cursor and ETag, set Cache-Control deliberately
CDN (Cloudflare, CloudFront, Fastly)Cache the poll response for 1 to 5 sThousands of clients, one origin request per TTL
AWS API Gateway (REST/HTTP APIs)Throttling and caching per stageCheap until clients x frequency explodes
Laravel Reverb's Pulse integration"Connection activity is recorded by polling for new updates on a periodic basis"A first-party product that chose polling on purpose

Fix / how to use it: poll with a cursor, not "give me the whole resource"; return 304 or an empty list cheaply; add jitter to the interval so clients do not synchronise; back off when the tab is hidden (document.visibilityState). The bad first version is in Go: Before and Laravel: Before.

Long polling (hanging GET) Must-know ​

In plain words: the client asks, and the server holds the request open until something happens or a timeout fires; then the client asks again at once.

Common misunderstanding: "Long polling is free because the request is just waiting." Each waiting request holds a connection, a request slot in every proxy on the path and, on thread-per-request servers (PHP-FPM, classic Rails/Django), a whole worker. RFC 6202: "Frequently, the resources allocated to HTTP requests can be significant, and scaling the total number of requests outstanding can be limited on some gateways, proxies, and servers."

Definition: RFC 6202 section 2.1: "The server achieves these efficiencies by responding to a request only when a particular event, status, or timeout has occurred. Once the server sends a long poll response, typically the client immediately sends a new long poll request." The term "hanging GET" comes from the request "hanging" on the server; the RFC says requests "need to remain pending or 'hanging' until the server has something to send".

text
     Client                                       Server (hold up to 25 s)
1    GET /poll?topic=orders.42&cursor=17          nothing newer: request parked
2                                                 t+9 s: event 18 appended -> waiter woken
3                                                 200 {events:[18], cursor:18}
4    GET /poll?...&cursor=18                      parked again
5                                                 t+25 s: hold time expired
6                                                 204 No Content (same cursor)
7    GET /poll?...&cursor=18                      parked; the loop continues
     maximal latency = response + next request + response (RFC 6202: "over three network transits")

Real scenario: Socket.IO starts every session on it and Phoenix Channels offers it as a transport, for networks where WebSockets are blocked; corporate networks whose proxies strip Upgrade; payment or KYC status pages that wait for one event.

What provides it:

ProductLong pollingHold time / timeout knob
Socket.IO (Engine.IO)Default first transport, then upgrades to WebSocketpingInterval 25000, pingTimeout 20000
Phoenix Channels"either Websockets or long polling" transportslongpoll transport option
NGINX in frontMust allow the holdproxy_read_timeout (default 60 s)
AWS ALB in frontMust allow the holdidle_timeout.timeout_seconds (default 60)
Go net/httpOne goroutine per waiting request; cheapcontext.WithTimeout per request
PHP-FPM / LaravelOne FPM worker per waiting request; expensiverequest_terminate_timeout, max_execution_time

Fix / how to use it: keep the hold time below the smallest idle timeout on the path (25 s against 60 s defaults; RFC 6202: "generally 30 seconds is a safer value"); always send the cursor; answer 204 on timeout so the client re-polls with the same cursor; send Cache-Control: no-store; never long-poll from a thread-per-request runtime at scale. Code: Go long poll.

Server-Sent Events (SSE) Must-know ​

In plain words: the browser opens one ordinary HTTP GET, the server never finishes the response, and every few lines of text it writes are an event. If the connection breaks, the browser reconnects by itself and tells the server the last event id it saw.

Common misunderstanding: "SSE is just a worse WebSocket." For server-to-client traffic it is often better: plain HTTP (works through most proxies, HTTP/2 multiplexing, normal auth cookies and CORS), automatic reconnection, and resume built into the protocol. Its real limits are one direction, text only (UTF-8), and on HTTP/1.1 the browser's 6-connections-per-host limit.

Definition: the WHATWG HTML Standard defines EventSource and the text/event-stream format. Each event is a block of field: value lines ended by a blank line; fields are data, event, id and retry; a line starting with : is a comment. On reconnect the user agent waits the reconnection time and, if it has a last event ID, sets the Last-Event-ID header. "Clients will reconnect if the connection is closed; a client can be told to stop reconnecting using the HTTP 204 No Content response code."

text
     Browser (EventSource)                        Server
1    GET /events?topic=orders.42                  200 Content-Type: text/event-stream
2                                                 retry: 3000
3                                                 id: 41 / event: orders.42 / data: {"status":"paid"}
4    onmessage -> UI shows "paid"; lastEventId = 41
5                                                 : ping                    (every 15 s, keeps proxies happy)
6    Wi-Fi drops; readyState = CONNECTING; waits 3000 ms
7    GET /events?topic=orders.42  Last-Event-ID: 41
8                                                 replays 42, 43 from the log, then continues live

Real scenario: order and delivery status; notifications; live sports scores; build logs streaming in CI; stock tickers that only flow one way; LLM token streaming (Laravel's eventStream docs use exactly that example); progress bars for long jobs.

What provides it:

ProductSSE supportResume (id: / Last-Event-ID)
BrowsersEventSource, withCredentials optionAutomatic header on reconnect
Go net/httpWrite and http.NewResponseController(w).Flush()You read the header and replay
Laravel 13response()->eventStream() with StreamedEventNo id: lines in 13.x; use response()->stream() for resume
NGINXProxies it; buffering must be offX-Accel-Buffering: no or proxy_buffering off
CentrifugoSSE transport with channel historyBuilt in (offsets and epochs)
HTTP/2 servers and CDNsMany SSE streams over one connectionLifts the 6-connection limit

Fix / how to use it: give every event an id: that is a cursor into a durable log; send retry: once; send a comment line about every 15 s (the spec: "authors can include a comment line (one starting with a ':' character) every 15 seconds or so"); disable proxy buffering; serve over HTTP/2 so tabs do not hit the limit MDN describes ("the limit is per browser and set to a very low number (6)"); close streams after a few minutes so connections rebalance. Code: Go SSE, Laravel SSE.

WebSocket: upgrade, frames and masking Must-know ​

In plain words: the client sends a normal HTTP request saying "let's switch to WebSocket"; the server answers 101 Switching Protocols; from then on the same TCP connection carries small binary frames in both directions until someone sends a Close frame.

Common misunderstanding: "A WebSocket is a raw TCP socket in the browser." It is a message protocol: frames have opcodes, client frames are masked, text must be UTF-8, control frames are limited to 125 bytes, and the browser API exposes whole messages, not bytes. It also starts as HTTP, so every proxy, load balancer and auth layer on the path has to understand the Upgrade.

Definition: RFC 6455. Client handshake: GET with Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key (16 random bytes, base64), Sec-WebSocket-Version: 13, Origin, and optionally Sec-WebSocket-Protocol and Sec-WebSocket-Extensions. Server: HTTP/1.1 101 Switching Protocols with Sec-WebSocket-Accept = base64(SHA-1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")). Then frames: FIN bit, three RSV bits, a 4-bit opcode (%x0 continuation, %x1 text, %x2 binary, %x8 close, %x9 ping, %xA pong), a MASK bit, a 7/16/64-bit payload length, a 4-byte masking key on every client-to-server frame ("a client MUST mask all frames that it sends to the server"), and the payload.

text
     Client                                        Gateway
1    GET /ws?ticket=t1 HTTP/1.1
     Upgrade: websocket / Connection: Upgrade
     Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== / Sec-WebSocket-Version: 13
     Origin: https://app.example.com / Sec-WebSocket-Protocol: rt.v1
2                                                  checks ticket + Origin; 101 Switching Protocols
                                                   Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
                                                   Sec-WebSocket-Protocol: rt.v1
3    text frame (FIN=1, opcode=1, MASK=1) {"type":"publish",...}
4                                                  text frame (FIN=1, opcode=1, MASK=0) {"seq":7,...}
5                                                  ping (opcode 9)
6    pong (opcode A, same payload)
7    close (opcode 8, code 1000)                   close (opcode 8, 1000); server closes TCP

Real scenario: chat (Slack, Discord, WhatsApp Web); multiplayer cursors in Figma-like editors; trading terminals sending orders and receiving fills; live location sharing where the driver app sends GPS and receives jobs; customer support widgets; browser games.

What provides it:

ProductServer sideNote
Gogithub.com/coder/websocket (formerly nhooyr), github.com/gorilla/websocketcoder: context-aware, "Zero dependencies", Accept refuses cross-origin by default
LaravelReverb (Pusher protocol on a ReactPHP event loop)Not plain WebSocket messages: Pusher events and channels
Node.jsws, Socket.IO (its own protocol on top)Socket.IO clients cannot talk to plain WebSocket servers
ElixirPhoenix ChannelsTopics, presence, long-poll fallback
AWSALB (pass-through), API Gateway WebSocket APIs (managed)API Gateway: $connect, $disconnect, $default routes
CloudflareWorkers + Durable ObjectsHibernation API keeps clients connected while the object sleeps

Fix / how to use it: authenticate before the upgrade (Auth); negotiate a versioned subprotocol; set a read limit; run one reader and one writer per connection; bound the send queue (Backpressure); heartbeat below every idle timeout (Heartbeats); stamp every server message with a sequence number (Ordering). Code: Go hub.

Ping/pong, heartbeats and idle timeouts Must-know ​

In plain words: a connection with no traffic looks dead to every middlebox on the path, and a dead connection looks alive to both ends until they try to write. A heartbeat is a tiny message on a timer that fixes both problems.

Common misunderstanding: "TCP keepalive handles this." Linux's default TCP keepalive starts after two hours of idleness; load balancers cut idle connections after 60 seconds; mobile carriers' NAT tables forget idle flows in minutes. Keepalive is also invisible to the application, so it cannot detect a frozen process.

Definition: RFC 6455 section 5.5.2: "Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response", and "A Ping frame may serve either as a keepalive or as a means to verify that the remote endpoint is still responsive." Browsers answer pings automatically but give JavaScript no way to send one; the Pusher protocol notes "it is still not possible to trigger sending a ping, or binding to a pong from JavaScript using the W3C API", so client-side heartbeats are application messages (pusher:ping, Socket.IO PING packets, {"type":"hb"}).

text
     Client                     AWS ALB (idle 60 s)            Gateway (ping every 25 s)
1    connected, no messages
2                                                               t=25 ping ->
3    <- pong                    idle timer reset
4                                                               t=50 ping ->
5    (phone in a tunnel)
6                                                               t=50 + write deadline: no pong
7                                                               close; remove from rooms; presence TTL starts
8    without pings: t=60 ALB drops the flow; client sees 1006 when it next writes

Real scenario: dashboards on wall TVs that receive one event an hour; chat apps on mobile; trading terminals that must notice a dead feed within seconds; IoT devices behind carrier NAT.

What provides it:

ProductHeartbeatDefault
Pusher protocol (and Reverb)Protocol ping, or pusher:ping / pusher:pong eventsRecommended client activity timeout 120 s, pong wait 30 s; Reverb ping_interval 60, activity_timeout 30
Socket.IOServer PING, client PONGpingInterval 25000 ms, pingTimeout 20000 ms
coder/websocketConn.Ping(ctx) waits for the pongYou choose the interval
gorilla/websocketWriteControl(PingMessage), SetPongHandler, read deadlinesYou choose the interval
NGINXNo heartbeat; closes after proxy_read_timeout of silence (60 s)NGINX docs: the backend can "periodically send WebSocket ping frames to reset the timeout"
AWS API GatewayManaged; idle timeout 10 minutes, connection max 2 hoursNot adjustable
Cloudflare Durable ObjectsThe runtime answers protocol pings automatically; "Ping/pong handling does not interrupt hibernation"Keeps hibernation cheap

Fix / how to use it: pick the heartbeat interval as smallest idle timeout on the path divided by 2 or more (25 s against 60 s); treat any received message as proof of life; close and clean up on a missed pong; reconnect from the client when its own timer sees no traffic for interval + grace.

Close codes Important ​

In plain words: a Close frame carries a two-byte number that says why the connection ended; the client uses it to decide whether to reconnect, back off, or give up.

Common misunderstanding: "1006 is a code the server sent." RFC 6455: "1006 is a reserved value and MUST NOT be set as a status code in a Close control frame by an endpoint." It is what your library reports when the TCP connection vanished without a Close frame: network drop, proxy idle timeout, crashed server. 1005 (no status) and 1015 (TLS failure) are likewise never on the wire.

Definition: RFC 6455 section 7.4.1 defines 1000 ("normal closure"), 1001 ("going away, such as a server going down or a browser having navigated away from a page"), 1002 protocol error, 1003 unsupported data, 1007 invalid payload (for example non-UTF-8 text), 1008 policy violation, 1009 message too big, 1010 missing extension, 1011 ("a server is terminating the connection because it encountered an unexpected condition"). IANA's registry adds 1012 service restart, 1013 try again later, 1014 bad gateway. 4000 to 4999 are for applications; the Pusher protocol splits them: 4000-4099 "SHOULD NOT be re-established unchanged", 4100-4199 back off at least 1 second, 4200-4299 "SHOULD be re-established immediately".

text
     Event                                   Code the client sees     Client action
1    user closes the chat tab                 1000 (client sent)       nothing
2    rolling deploy drains the gateway        1001 Going Away          reconnect with jitter
3    ALB idle timeout / Wi-Fi drop            1006 (no Close frame)    reconnect with backoff + jitter
4    message over the read limit              1009 Message Too Big     fix the client; do not loop
5    ticket expired / origin refused          HTTP 401/403, no 101     fetch a new ticket, then connect
6    session revoked after connect            1008 Policy Violation    go to login, do not reconnect
7    history gap on resume                    1013 Try Again Later     reload state, then reconnect

Real scenario: a client that reconnects in a tight loop on 1008 (DDoSing your own auth service); a mobile app that treats 1006 as fatal and shows "disconnected" forever; a deploy that closes with 1011 instead of 1001 and pages the on-call.

What provides it:

ProductHow close codes appear
Browser WebSocketCloseEvent.code, CloseEvent.reason, wasClean
coder/websocketwebsocket.CloseStatus(err), StatusGoingAway, StatusPolicyViolation, StatusTryAgainLater
AWS API GatewayCloses with 1009 when a frame exceeds 32 KB
Reverb / Pusherpusher:error events with codes (Reverb sends 4200 "Invalid message format")
Cloudflare Durable ObjectswebSocketClose(ws, code, reason, wasClean) handler

Fix / how to use it: close deliberately with 1001 on drain, 1008 on auth failure after connect, 1009 on oversize, 1011 on bugs; on the client, map codes to Stop / Backoff / Immediate (the reconnect.Classify function in Go).

Subprotocols and compression (permessage-deflate) Important ​

In plain words: a subprotocol is the name of the message format you speak on top of WebSocket ("rt.v1", "graphql-transport-ws", "mqtt"); an extension changes the framing itself, and the one everybody uses compresses each message.

Common misunderstanding: "Turn on compression, it is free." permessage-deflate keeps a zlib context per connection and per direction when context takeover is on (coder/websocket documents a 32 KB sliding window per direction), so 100,000 connections can carry gigabytes of compression state; small JSON messages compress poorly; and compressing secrets next to attacker-controlled data reopens CRIME/BREACH-style length leaks.

Definition: Sec-WebSocket-Protocol lists the client's subprotocols in preference order and the server echoes exactly one (RFC 6455 section 1.9). RFC 7692 defines a framework that "compresses the payload data portion of WebSocket data messages on a per-message basis using parameters negotiated during the opening handshake", with parameters server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits; a compressed message sets RSV1.

text
     Client offer                                       Server answer
1    Sec-WebSocket-Protocol: rt.v2, rt.v1               Sec-WebSocket-Protocol: rt.v1   (old server)
2    Sec-WebSocket-Extensions: permessage-deflate;       Sec-WebSocket-Extensions: permessage-deflate;
       client_max_window_bits                              server_no_context_takeover
3    both sides now compress each message; the server resets its zlib state per message (less memory)

Real scenario: a rolling deploy where v2 clients meet v1 servers; GraphQL subscriptions (graphql-transport-ws); MQTT over WebSocket for IoT dashboards; large JSON snapshots for trading screens where compression pays.

What provides it:

ProductSubprotocolCompression default
coder/websocketAcceptOptions.SubprotocolsCompressionDisabled; CompressionContextTakeover / NoContextTakeover available
gorilla/websocketUpgrader.SubprotocolsCompression is "EXPERIMENTAL", opt-in with EnableCompression
Reverb / PusherPusher protocol version in the URL query (protocol=7)Not used for subprotocol negotiation
Socket.IOIts own protocol over Engine.IOperMessageDeflate disabled by default since v3.0.0
Browsersnew WebSocket(url, ["rt.v1"])Offer permessage-deflate automatically

Fix / how to use it: version the message format in the subprotocol; refuse connections that negotiate none; keep compression off by default, turn it on with no_context_takeover for large messages only, and never compress secrets together with user-controlled text.

Backpressure and slow consumers Must-know ​

In plain words: if you write to a client faster than it can read, the bytes pile up somewhere: in the kernel, in your queue, then in your heap. Backpressure is deciding in advance what happens to a client that cannot keep up.

Common misunderstanding: "A buffered channel of 1,000 is safe." For a room of 10,000 members, 1,000 queued 4 KB messages each is 40 GB. And a single blocking write in the fan-out loop means one phone in a tunnel stalls the whole room.

Definition: every connection gets a bounded send queue drained by its own writer goroutine or task. The fan-out path does a non-blocking enqueue; when the queue is full the policy fires: disconnect the slow consumer (close 1008 and let it resume from the cursor), drop and mark a gap, or coalesce (keep only the latest price per symbol). A write deadline bounds how long a writer waits for the TCP window.

text
     Fan-out loop                  Client A (fast)        Client B (phone in a tunnel)
1    enqueue m1..m64                queue 0/64             queue fills 1..64 (TCP window closed)
2    enqueue m65                    sent                   queue full -> kick(1008 "slow consumer")
3    fan-out continues at full speed; A never waits for B
4                                                          B reconnects: ?since=<last seq> -> replay from history

Real scenario: a live sports room with 200,000 viewers; a trading feed where some clients are on hotel Wi-Fi; a Discord-sized guild where a single publish reaches tens of thousands of sessions; a dashboard that renders slowly in an old browser.

What provides it:

ProductBackpressure behaviour
This page's Go hubBounded send channel per connection, non-blocking enqueue, close 1008, Kicked counter
coder/websocketWrite(ctx, ...) respects the context deadline
gorilla/websocketSetWriteDeadline; one concurrent writer only
Socket.IOBuffers in memory per socket; volatile emits can be dropped
CentrifugoClients that fall behind or reconnect catch up from channel history, "a bounded cache" that is never authoritative
BrowsersWebSocket.bufferedAmount shows unsent client bytes; check it before sending more

Fix / how to use it: size the queue for a burst (16 to 256 messages), not for an outage; disconnect rather than buffer without bound; make the disconnected client resume from history; coalesce data where only the latest value matters (prices, locations, cursors).

Beyond WebSocket: HTTP/2, HTTP/3, WebTransport and WebRTC data channels Good to know ​

In plain words: WebSocket gives you one ordered, reliable stream per connection. Newer options give many streams on one connection (HTTP/2 and HTTP/3 WebSockets, WebTransport) or unreliable, unordered delivery for data where late is worse than lost (WebTransport datagrams, WebRTC data channels).

Common misunderstanding: "WebTransport replaces WebSocket now." It is a Candidate Recommendation (30 July 2026 snapshot) that requires HTTP/3 end to end, which many corporate networks and load balancers still block or terminate. WebRTC data channels are peer-to-peer and need ICE, STUN and usually TURN servers; they are not a server push mechanism.

Definition: RFC 8441 runs one WebSocket on one HTTP/2 stream using extended CONNECT with the :protocol pseudo-header after the server sends SETTINGS_ENABLE_CONNECT_PROTOCOL = 1; RFC 9220 does the same on HTTP/3. WebTransport "defines a set of ECMAScript APIs in WebIDL to allow data to be sent and received between a browser and server" over HTTP/3 (QUIC), with bidirectional and unidirectional streams and datagrams. WebRTC's RTCDataChannel runs over SCTP and can be created with ordered: false and maxRetransmits or maxPacketLifeTime for partial reliability.

text
     Need                                           Transport                       Why
1    Many sockets from one page to one origin       WebSocket over HTTP/2 (RFC 8441) One TCP+TLS connection
2    Game state at 30 Hz, old state useless          WebTransport datagrams           No head-of-line blocking, no retransmit
3    Browser-to-browser file transfer or game        WebRTC data channel              Peer-to-peer, server only signals
4    Anything else, today                            WebSocket or SSE                 Works everywhere, simple ops

Real scenario: cloud gaming input channels; collaborative whiteboards with peer-to-peer cursors; live video plus chat where chat rides a data channel; telemetry from browsers where loss is acceptable.

What provides it:

OptionStatusServer support
WebSocket over HTTP/2RFC 8441 (2018)Browsers and some proxies (Envoy among them); often terminated to HTTP/1.1 behind the edge
WebSocket over HTTP/3RFC 9220 (2022)Limited server support
WebTransportW3C Candidate Recommendation Snapshot, 30 July 2026HTTP/3 servers (Go quic-go/webtransport-go, Cloudflare); check each browser
WebRTC data channelW3C Recommendation (2021, edition of 13 March 2025)Browsers; servers via Pion (Go), mediasoup, LiveKit

Fix / how to use it: start with SSE or WebSocket; move a specific feature to WebTransport or WebRTC only when measured head-of-line blocking or retransmission delay is the problem, and keep a WebSocket fallback.

Message ordering and delivery: sequence numbers, cursors, resume, dedup Must-know ​

In plain words: number every message per channel. The client remembers the last number it saw. When it reconnects it says "I have up to 41", and the server sends 42 onwards. If a number arrives twice, the client ignores the second one.

Common misunderstanding: "Redis Pub/Sub (or my broker) guarantees delivery to the browser." Redis Pub/Sub is at-most-once: "If the subscriber is unable to handle the message (for example, due to an error or a network disconnect) the message is forever lost." Even with a durable broker between servers, the last hop (gateway to browser) loses whatever was in flight when the socket died.

Definition: delivery to real-time clients is at-least-once with client dedup, built from four parts: a per-channel, gap-free sequence number assigned at publish time; a bounded history (Redis sorted set or stream, Kafka topic, database table); a resume request carrying the cursor (Last-Event-ID, ?cursor=, ?since=); and a message id generated by the sender so retries can be deduplicated. If the cursor is older than the history window, the server says so explicitly (Centrifugo's recovered: false, this page's 409 or close 1013) and the client reloads full state. The semantics themselves are owned by Delivery Guarantees.

text
     Sender (Alice)            Gateway A / Redis                 Receiver (Bob, on Gateway B)
1    send {id:"m-77"} -->      Lua: INCR seq=42, ZADD hist, PUBLISH
2                                                                 gets seq 42; last_seq = 42
3    no ack (Wi-Fi blip); resend {id:"m-77"}
4                              seq=43 for the same id             gets seq 43, id m-77 already seen -> drop
5                                                                 Bob's socket dies; seq 44, 45 published meanwhile
6                                                                 reconnect ?since=43 -> replay 44, 45 from hist
7                                                                 if hist starts at 50: 409 / close 1013 -> reload state

Real scenario: chat messages that must not vanish; order status that must end in the right state; collaborative editing operations (where ordering is causal, not total; see CRDTs and Vector Clocks); trading fills; notifications with unread counts.

What provides it:

ProductOrderingResumeDedup
SSE (spec)Per streamid: + Last-Event-IDYou implement
CentrifugoPer channel offset + epochBuilt in (recover, recovered: true/false)Offsets dedupe replay
AblyPer channelResume if reconnected within about two minutes, then resumed: falseMessage ids
Socket.IOPer socketConnection state recovery (maxDisconnectionDuration)Server offsets
Pusher / ReverbPer channel, no historyNone: reload over HTTPYou implement
Phoenix ChannelsPer topicNone built in; app-levelYou implement
Redis Pub/SubPer channel per subscriberNone (at-most-once)Use a sorted set or Stream for history

Fix / how to use it: assign the sequence number atomically with the publish (one Lua script; see fanout); keep history long enough to cover a deploy plus reconnect jitter (minutes, not seconds); make every client message carry an id it reuses on retry; on gap, reload state from the source of truth, never pretend. SQL for a durable log is in Solving: lost messages.

Authentication for sockets: tickets, tokens and origin checks Must-know ​

In plain words: decide who the user is before you say 101, check that the page asking is yours, and keep checking for the life of the connection.

Common misunderstanding: "Same-origin policy protects my WebSocket like it protects fetch." It does not. The browser will open a WebSocket to any host from any page and attach that host's cookies. OWASP: "Browsers include cookies in WebSocket handshake requests, making WebSocket applications vulnerable to Cross-Site WebSocket Hijacking (CSWSH)." The only browser-supplied defence is the Origin header, which you must check.

Definition: three layers. (1) Origin check at the handshake against an allowlist (RFC 6455 section 10.2; OWASP: "Validate the Origin header on every handshake. Always use an explicit allowlist of trusted origins."). (2) Identity: the browser WebSocket API cannot set an Authorization header, so use a cookie session plus the origin check, a short-lived single-use ticket fetched over an authenticated HTTP call and passed in the URL, or a token sent as the first message (OWASP prefers the first-message token and warns that tokens in URL query strings "can leak into access logs"; a ticket that works once for 30 seconds limits that leak). (3) Per-channel and per-message authorization, plus re-validation: close with 1008 when the session expires or the user logs out.

text
     Browser                         API (Laravel)                    Gateway (Go hub)
1    POST /realtime/ticket (cookie + CSRF token)
2                                    SET ticket:abc user=7 EX 30 NX
3    <- {ticket: "abc"}
4    GET wss://rt.example.com/ws?ticket=abc  Origin: https://app.example.com
5                                                                      GETDEL ticket:abc -> user 7
6                                                                      Origin in allowlist? room allowed for user 7?
7                                                                      101 Switching Protocols
8    replaying the same URL later: GETDEL returns nil -> 401; evil.example.net origin -> 403

Real scenario: a support chat where an attacker's page reads the victim's conversations through CSWSH; tokens in query strings showing up in ALB access logs; a fired employee whose open socket keeps receiving events after their account is disabled.

What provides it:

ProductIdentity at connectChannel authorizationOrigin check
Laravel Reverb + EchoPusher socket_id; private/presence channels signed by /broadcasting/authBroadcast::channel() callbacks in routes/channels.phpallowed_origins in config/reverb.php
Pusher ChannelsSame protocol; HMAC auth string per subscriptionYour auth endpointDashboard settings
Socket.IOauth payload in the handshake, middlewareRooms you join on the servercors.origin / allowRequest
CentrifugoJWT connection token, channel tokensProxy or token claimsallowed_origins
AWS API GatewayAuthorization "on the $connect route only"; failure returns 401 or 403In your route handlersYou check the header
coder/websocket (Go)Your middleware before AcceptYour codeAccept checks Origin; "Accept will not allow cross origin requests by default"

Fix / how to use it: never use InsecureSkipVerify or allowed_origins => ['*'] with cookie auth; prefer single-use tickets or first-message tokens; authorize every subscription and every client-to-server action; keep a session-to-connections index so logout can close sockets. Code: Go ticket, Laravel channels.

Presence: heartbeats, TTL, last seen, multi-device Must-know ​

In plain words: presence answers "who is here right now?". Each device says "I'm here" every few seconds; if it stops, it disappears after a timeout. A person is online while any of their devices is.

Common misunderstanding: "Online = has an open socket, offline = socket closed." Sockets die without a close (1006), so close events alone leave ghosts; and people have several tabs and devices, so removing the user on the first disconnect hides them while they are still on their laptop. Ably's docs describe exactly that: "If 'Sarah' leaves the channel on her mobile, your app sees the leave event and incorrectly removes her entry from the list."

Definition: presence is a set of connections, not users, each with an expiry refreshed by heartbeats. Typical model: a Redis sorted set per room with members user|connection and score = expiry time; heartbeat every 15 to 20 s with TTL 2 to 3 intervals; prune expired entries; report a user transition (offline to online, online to offline) only when the first device joins or the last device leaves; write last seen durably on the online-to-offline transition. Fan out transitions, not heartbeats, and only to people who can see the user.

text
     t     Sarah laptop          Sarah phone          Presence set (room team.7)       Emitted
1    0     join                                        sarah|laptop exp=45              sarah online
2    1                           join                  + sarah|phone exp=46             (nothing: 2nd device)
3    10                          close (1000)          - sarah|phone                    (nothing: laptop live)
4    15..60 heartbeat x4                               sarah|laptop exp=105
5    20    Omid's tab crashes (no close); omid|web exp=45
6    61    prune: omid|web expired                                                     omid offline, last_seen=61
7    70    close                                       empty for sarah                  sarah offline, last_seen=70

Real scenario: green dots in Slack (Slack's Presence Servers hash users and clients receive "presence notifications only for a subset of users that are visible in the app screen"); "3 people are viewing this ticket"; Google Docs avatars; driver availability in ride-hailing; "last seen 5 min ago" in messengers.

What provides it:

ProductPresence modelLeave detection
Laravel Reverb / Pusher presence channelsMember list per channel from your Broadcast::channel return array; here, joining, leaving in EchoSocket close or activity timeout
AblyMembers per clientId + connectionIdAbrupt disconnect becomes leave after 15 s without resume
Phoenix PresenceCRDT-replicated across the cluster: "no single point of failure, no single source of truth"Process monitoring
CentrifugoPresence per channel in memory or RedisClient ping timeout
Socket.IONone built in; rooms plus your own storedisconnect event
Redis (DIY)Sorted set with expiry scores, or one key per connection with SET ... EXTTL expiry

Fix / how to use it: track connections, derive users; expire by TTL, never rely only on close events; debounce offline by a few seconds to hide reconnects; store last seen in the database on transitions; cap fan-out of presence changes (large rooms show counts, not lists). Code: Go presence, Laravel Presence.

Holding connections: C10K, C10M, memory and event loops Important ​

In plain words: a held connection costs a file descriptor, kernel socket buffers, TLS state, and whatever your runtime keeps per connection (a thread, a goroutine, a PHP worker, buffers). Real-time scale is mostly the art of making that last part tiny.

Common misunderstanding: "One port can only accept 65,535 connections." A listening socket accepts connections identified by the four-tuple (client IP, client port, server IP, server port); the limit that bites is file descriptors and memory, and ephemeral ports only on the hop where one proxy opens many connections to one backend address (the Reverb docs' 28,231 figure from ip_local_port_range applies to that proxy-to-Reverb hop, not to clients reaching NGINX).

Definition: C10K is Kegel's 1999 question of serving 10,000 concurrent clients on one machine, answered by readiness-based event loops (epoll on Linux, kqueue on BSD and macOS) instead of a thread per connection. C10M is the later framing of 10 million connections per machine, which pushes into kernel-bypass networking and tight per-connection memory. Practical runtimes: Go's netpoller parks goroutines on epoll/kqueue (a goroutine starts with a small stack that grows); Node.js, ReactPHP (Reverb) and Erlang/BEAM run event loops or lightweight processes; PHP-FPM and thread-per-request servers hold a whole worker per connection.

text
     Back-of-envelope: 1,000,000 concurrent WebSocket clients
1    memory: measured ~50 KB per connection both ends in this page's lab -> budget ~25-50 KB server side
2            1,000,000 x 40 KB = ~40 GB  ->  e.g. 8 gateways x 125k connections x 5 GB
3    heartbeats: 1,000,000 / 25 s = 40,000 pings/s fleet-wide (tiny CPU, real packets)
4    reconnect after a lost gateway: 125,000 clients; at 500 handshakes/s per node with TLS -> spread them
5    file descriptors: ulimit -n >= 200,000 per gateway; NGINX worker_rlimit_nofile, worker_connections

Real scenario: sizing a chat tier; moving a PHP-FPM SSE endpoint that capped at a few hundred users to Reverb or a Go gateway; Erlang/BEAM connection servers (see Case Study: WhatsApp for the published numbers); Discord's Elixir session processes (Case Study: Discord).

What provides it:

Runtime / productModel per connectionLimit to watch
Go net/http + coder/websocket1 reader goroutine + 1 writer goroutine (measured 2.0 per connection in the lab)Heap from buffers, GC
Laravel ReverbReactPHP event loop; stream_select by default"typically limited to 1,024 open files"; install ext-uv above 1,000
PHP-FPM SSE / long pollOne worker per open streampm.max_children; blocks normal requests
Node.js ws / Socket.IOEvent loop, callbacksSingle core per process; cluster + adapter
Erlang/Elixir (Phoenix)Lightweight process per connectionMailbox growth (Discord's lesson)
NGINX (proxy)Event loop, two sockets per proxied connectionworker_connections, worker_rlimit_nofile
OS (Linux)One fd per socketulimit -n / limits.conf, fs.file-max, ip_local_port_range on the proxy hop

Fix / how to use it: measure your own per-connection cost (Lab); raise fd limits everywhere (systemd LimitNOFILE, Supervisor minfds, NGINX); never hold real-time connections in a thread-per-request runtime; keep per-connection buffers small (read limit, no compression by default).

Fan-out across servers: sticky sessions, stateless gateways, pub/sub, sharding Must-know ​

In plain words: once connections live on many servers, a message for a room must reach every server that has a member of that room. Either every server hears everything (broadcast pub/sub), or something knows which servers care (interest-based routing, sharding).

Common misunderstanding: "Sticky sessions solve WebSocket scaling." A WebSocket is already pinned to one server for its lifetime; stickiness only matters for protocols that spread one session over several HTTP requests (Socket.IO's long-polling phase: "you have to make sure that all requests associated with a particular session ID reach the process that originated them"). Stickiness does nothing for the real problem, which is getting a message from the sender's node to the receivers' nodes.

Definition: a connection gateway is a process whose only job is holding client connections and mapping channels to local connections. "Stateless" here means no business state and no state that must survive the process: any client can reconnect to any gateway and resume from shared history. Messages reach gateways by: broadcast pub/sub (every gateway PSUBSCRIBEs, filters locally; simple, wastes bandwidth at large scale); interest-based subscription (a gateway subscribes to a room's channel only while it has local members); or sharded routing (Slack: Channel Servers own channels by consistent hashing and push to subscribed Gateway Servers; Discord: guild processes fan out to session processes). Connection sharding by user (hash user id to a gateway) makes presence and per-user delivery local but complicates rebalancing.

text
     App server           Redis                       Gateway 1 (Alice)          Gateway 2 (Bob, Carol)
1    POST /rooms/9/messages
2    EVAL publish.lua -> INCR rt:{9}:seq = 120, ZADD rt:{9}:hist, PUBLISH rt:room:9
3                         -> pattern subscribers       local members of 9: Alice  local members of 9: Bob, Carol
4                                                      enqueue to Alice           enqueue to Bob, Carol
5    one publish = 1 Redis message per gateway + 1 socket write per member
browser tabEcho / EventSourcesecond tabsame usermobile appsame userreconnecting?since=41Load balancerAWS ALB / NGINXTLS terminationUpgrade passedidle timeout 60 s(ping every 25 s)least connectionsno stickiness forpure WebSocketGateway 1conns + rooms mapbounded queue per connGateway 2capacity: measure (lab)slow consumer: close 1008Gateway 3 (draining)close 1001 spread overminutes, 503 to newRedisPub/Sub channelrt:room:chat.1every gatewayPSUBSCRIBE rt:room:*history zsetrt:{chat.1}:hist (cap N)seq counter INCRpresence zsetuser|conn, score=expiryApp serversLaravel / Go APIpublish via Lua scriptOne publish1 INCR seq2 ZADD history3 ZREMRANGEBYRANK4 PUBLISH envelopeatomic: seq order =publish orderClient ruleskeep last seq per roomseq jumped: resume ?since=lastduplicate id: drop (at-least-once)close 1001/1006: backoff + full jitterhistory gap (1013): reload stateheartbeat every 15-20 s for presencepublishfan-out

The diagram is the shape this page's code builds: clients reach a load balancer that passes the Upgrade, gateways hold connections and bounded queues, and one Lua script in Redis assigns the sequence number, appends to history and publishes, so every gateway delivers the same order. Presence and tickets live in the same Redis.

Real scenario: Laravel Reverb's horizontal scaling ("Utilizing the publish / subscribe capabilities of Redis, Reverb is able to manage connections across multiple servers"); Socket.IO's Redis adapter; Phoenix PubSub ("If there are other nodes in the cluster, the local PubSub also forwards the message to their PubSubs"); Slack's Gateway and Channel Servers; Discord's guild and session processes; a Kafka-fed notification gateway where each gateway consumes a partition range.

What provides it:

ProductCross-node fan-outNotes
Laravel ReverbRedis Pub/Sub (REVERB_SCALING_ENABLED=true, channel reverb)Central Redis; all Reverb servers behind a load balancer
Socket.IOAdapters: Redis, Redis Streams, Postgres, clusterSticky sessions needed while long polling is enabled
CentrifugoMemory, Redis and PostgreSQL brokers (history included)Built for this; history stays a cache, the database stays the source of truth
PhoenixPhoenix.PubSub over distributed Erlang (or Redis)Presence replicated as a CRDT
RedisPUBLISH/PSUBSCRIBE; sharded SPUBLISH/SSUBSCRIBE since 7.0At-most-once; sharded pub/sub limits cluster-bus traffic
Kafka / NATSDurable topics / subjects per room or user shardGateways consume; history comes free with Kafka
Ably, Pusher, AWS API GatewayManaged: you publish over HTTP, they fan outAPI Gateway: @connections API per connection id

Fix / how to use it: start with one Redis and broadcast pub/sub; move to interest-based subscriptions or sharded pub/sub (SSUBSCRIBE on Redis Cluster) when gateways spend more time discarding messages than delivering them; put history next to the fan-out (Redis sorted set or stream, Kafka) so resume does not hit the primary database. Code: fanout/redis.go.

Draining, reconnection storms and jitter Must-know ​

In plain words: every deploy, crash or load balancer change disconnects thousands of clients at once. If they all come back in the same second, the handshakes, TLS setups, auth checks and history reads knock the new servers over, and the cycle repeats.

Common misunderstanding: "Exponential backoff prevents the storm." Without randomness every client that dropped at t=0 retries at exactly 1 s, 2 s, 4 s: the spikes just move. Centrifugo's docs say it plainly: "a balancer reload, a deploy, or a network blip drops everyone at once, and they all reconnect within seconds. If every returning client queries your database to refresh its state, that reconnect storm turns into a thundering herd right when your system is already under stress."

Definition: three defences. Server side: drain (deregister from the load balancer, refuse new connections with 503 + Retry-After, close existing ones with 1001 spread over minutes). Client side: exponential backoff with full jitter, delay = random(0, min(cap, base * 2^attempt)). Data side: resume from a fast history store, not a full reload from the primary database. AWS ALB gives a drain window by default ("waits 300 seconds before completing the deregistration process"); Kubernetes gives terminationGracePeriodSeconds (30 s by default) and a preStop hook.

Fixed delay, kill -9 restart100,000 clients retry after exactly 1 sDrain + full jitter1001 spread over 300 s, client waits random(0, cap)reconnects/sreconnects/stimetimehandshake + TLS + auth + history read, all at oncesame total work, spread thin; no second outage100k in 1 snode dies,all drop againand againabout 333/s for 300 s (100,000 / 300)Server: deregister from LB, stop accepting(503 + Retry-After), close 1001 in batchesClient: delay = random(0, min(cap, base * 2^n))resume with last seq, not a full reloadEdge: limit new connections per second;serve resume from Redis/Centrifugo history,not the primary database

The left half is a kill -9 style restart with a fixed retry: all 100,000 reconnects land in one second and the replacement node dies too. The right half drains with 1001 over five minutes and clients add full jitter: about 333 reconnects per second, which any gateway absorbs.

text
     t        Gateway 3 (100,000 conns)                   Fleet
1    0        SIGTERM: Draining=true, LB deregisters         new conns go to gateways 1-2
2    0..300   kick 333 conns/s with 1001 "server draining"   +333 handshakes/s, +333 history reads/s
3             clients: delay = random(0, min(30 s, 1 s*2^n))
4    300      0 conns left; process exits before ALB's 300 s deregistration delay
5    without this: 100,000 handshakes in ~1 s -> TLS CPU spike, auth DB spike, second outage

Real scenario: every Kubernetes rolling update of a socket tier; Slack's "draining mechanism for region failures that seamlessly switches the users in a bad region to the nearest good region"; an NGINX reload that drops all upgraded connections on old workers when worker_shutdown_timeout expires; a Redis failover that forces every gateway to resubscribe.

What provides it:

ProductDrain knobReconnect behaviour
AWS ALB / NLBderegistration_delay.timeout_seconds (300 default)Clients reconnect to healthy targets
KubernetesterminationGracePeriodSeconds, preStop, readiness probe off firstYou implement the spread
Laravel Reverbphp artisan reverb:restart "ensures all connections are gracefully terminated"Echo/pusher-js reconnects with backoff
Socket.IO clientreconnectionDelay 1000, reconnectionDelayMax 5000, randomizationFactor 0.5Built-in jitter "so that the clients do not reconnect at the exact same time"
CentrifugoRestart drops connectionsSDKs reconnect and recover from history (recovered: true/false)
This page's Go hubHub.Drain(ctx, window); 503 for new connectionsreconnect.FullJitter, reconnect.Classify

Fix / how to use it: never close all connections at once; drain over a window sized to (connections / acceptable handshake rate); jitter every client retry; serve resume from history; rate-limit new connections at the edge; alert on handshake rate, not only on connection count.

Products: Pusher protocol, Reverb, Echo, Socket.IO, Centrifugo, Ably, Phoenix, API Gateway, Durable Objects Important ​

In plain words: you rarely write the socket layer from scratch. The products differ in who runs the servers, which wire protocol clients speak, and whether history, presence and recovery are built in.

Common misunderstanding: "Reverb is a WebSocket server, so any WebSocket client can talk to it." Reverb speaks the Pusher protocol; Laravel's docs tell you to install pusher-js "since Reverb utilizes the Pusher protocol for WebSocket subscriptions, channels, and messages". Likewise a Socket.IO server only talks to Socket.IO clients.

Definition: the Pusher protocol is a JSON event protocol over WebSocket: pusher:connection_established (with socket_id and activity_timeout), pusher:subscribe with an HMAC auth signature for private channels and channel_data for presence, pusher_internal:member_added / member_removed, pusher:ping / pusher:pong, client events prefixed client-, and close-code ranges 4000-4299. Laravel Echo is the JavaScript client library that subscribes to channels for any Laravel broadcaster.

text
     Echo (browser)                    Reverb                        Laravel app
1    WebSocket to /app/{key}?protocol=7
2                                      pusher:connection_established {socket_id: "123.456", activity_timeout: 30}
3    POST /broadcasting/auth {socket_id, channel_name: "private-orders.42"}  ->  Broadcast::channel callback: true
4                                                                    <- {auth: "key:hmac"}
5    pusher:subscribe {channel: "private-orders.42", auth}
6                                      verifies HMAC; subscribes
7                                                                    OrderStatusUpdated -> queued job -> Reverb HTTP API (/apps/...)
8                                      event "order.status" to every subscriber of private-orders.42

Real scenario: a Laravel SaaS adding notifications in a day with Reverb; a Node team using Socket.IO with rooms; a Go or Python backend putting Centrifugo in front and publishing over its HTTP API; a team that does not want to run sockets at all using Ably or Pusher Channels; a serverless app on AWS API Gateway WebSocket APIs; a collaborative editor on Cloudflare Durable Objects, one object per document.

What provides it:

ProductWho runs itClient protocolHistory / recoveryPresenceScale-out
Pusher ChannelsManagedPusher protocolNoPresence channelsManaged
Laravel ReverbYou (PHP, ReactPHP)Pusher protocolNoPresence channelsRedis Pub/Sub
Laravel EchoClient libraryPusher, Ably, Reverb, Socket.IO broadcastersNojoin().here/joining/leavingn/a
Socket.IOYou (Node.js)Socket.IO over Engine.IO (long polling then WebSocket)Connection state recoveryDIY (rooms)Adapters (Redis, etc.)
CentrifugoYou (Go binary)Centrifugo protocol (WebSocket, HTTP-streaming, SSE, WebTransport, GRPC)Offsets + epochYesRedis, PostgreSQL brokers
AblyManagedAbly protocolYes (resume within about two minutes)Yes (15 s leave)Managed
Phoenix ChannelsYou (Elixir)Phoenix protocol (WebSocket, long poll)No (app-level)Phoenix Presence (CRDT)Distributed Erlang PubSub
AWS API Gateway WebSocketManagedPlain WebSocket; routes by routeSelectionExpressionNoDIY (DynamoDB)Managed; 500 new conns/s per account per Region by default
Cloudflare Durable ObjectsManaged edgePlain WebSocket into one objectObject storageDIY in the objectOne object per room; hibernation

Fix / how to use it: choose by who operates it and what is built in: if you need history and recovery, Centrifugo or Ably save months; if you are on Laravel and need private/presence channels, Reverb plus Echo is the shortest path; if you run serverless on AWS, API Gateway plus DynamoDB for connection ids; if each room is a unit of state (a document, a game), Durable Objects.

Mechanics ​

SSE wire format ​

LineMeaningNote
data: textOne line of the event's data; several lines are joined with \nEvents are UTF-8 only
event: nameEvent type; default is messageaddEventListener('name', ...)
id: 42Sets the last event IDSent back as Last-Event-ID on reconnect
retry: 3000Reconnection time in msInteger only
: commentIgnored; used as a heartbeatEvery ~15 s
blank lineDispatches the eventLast block without a blank line is discarded
HTTP 204Tells EventSource to stop reconnectingSpec: "told to stop reconnecting"
text
retry: 3000

id: 41
event: order.status
data: {"order_id":42,"status":"paid"}

: ping

id: 42
event: order.status
data: {"order_id":42,
data:  "status":"shipped"}

WebSocket handshake and frames ​

Client request (HTTP/1.1)GET /ws?ticket=... HTTP/1.1Host: rt.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13Origin: https://app.example.comSec-WebSocket-Protocol: rt.v1, rt.v0Sec-WebSocket-Extensions: permessage-deflateServer responseHTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept:s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-WebSocket-Protocol: rt.v1Accept = base64(SHA-1(key +"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))Origin checked first: else 4031. upgrade2. 101, same TCPconnection nowcarries framesFrame header (RFC 6455, section 5.2), bits left to rightFINRSV1-3RSV1 = deflateopcode (4 bits)0 1 2 8 9 AMpayload len (7 bits)126: +16 bit, 127: +64 bitextended length (0, 2 or 8 bytes)masking key (4 bytes)client to server onlypayload: application data, XOR-masked by clienttext must be valid UTF-8 (else close 1007)Opcodes0x0 continuation | 0x1 text | 0x2 binary | (data frames, may be fragmented)0x8 close (2-byte code + reason) | 0x9 ping | 0xA pong | (control: max 125 bytes, never fragmented)Close codes1000 normal | 1001 going away | 1006 abnormal (never on the wire) | 1008 policy | 1009 too big | 1011 server error

The upper half is the RFC 6455 example handshake with this page's subprotocol: the Sec-WebSocket-Accept value proves the server understood WebSocket (it is a hash of the client's key and a fixed GUID), not who the client is. The lower half is the frame header: client frames always carry a masking key; control frames (close, ping, pong) are at most 125 bytes and never fragmented.

FieldSizeValues
FIN1 bit1 = final fragment of a message
RSV1, RSV2, RSV31 bit each0 unless an extension defines them; RSV1 = compressed (RFC 7692)
Opcode4 bits0x0 continuation, 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong
MASK1 bit1 on every client-to-server frame, 0 from the server
Payload length7 bits (+16 or +64)0-125 direct, 126 = next 16 bits, 127 = next 64 bits
Masking key32 bitsRandom per frame, client to server only

Close codes ​

CodeNameSent on the wire?Client should
1000Normal ClosureYesNot reconnect (unless the app wants to)
1001Going AwayYesReconnect with jitter (drain, page navigation)
1002Protocol ErrorYesReport; reconnect with backoff
1003Unsupported DataYesFix the client
1005No Status ReceivedNeverTreat as abnormal
1006Abnormal ClosureNever (library-reported)Reconnect with backoff + jitter
1007Invalid Frame Payload DataYesFix encoding (non-UTF-8 text)
1008Policy ViolationYesRe-authenticate; do not loop
1009Message Too BigYesFix message size (API Gateway: 32 KB frames)
1010Mandatory ExtensionYes (client)Fix negotiation
1011Internal ErrorYesReconnect with backoff
1012 / 1013 / 1014Service Restart / Try Again Later / Bad Gateway (IANA)YesReconnect with backoff
1015TLS HandshakeNeverFix certificates
4000-4999Application-definedYesPer protocol (Pusher: 4000-4099 stop, 4100-4199 back off, 4200-4299 now)

Timeouts and knobs per product ​

ProductKnobDefaultWhat to set
NGINXproxy_read_timeout60 sAbove the heartbeat interval, or keep 60 s and ping every 25 s
NGINXproxy_http_version, proxy_set_header Upgrade $http_upgrade, Connection $connection_upgrade1.1 since 1.29.7 (1.0 before)Required for WebSocket proxying
NGINXproxy_buffering / X-Accel-Buffering: noBuffering onOff for SSE
AWS ALBidle_timeout.timeout_seconds60Above the heartbeat interval
AWS ALBclient_keep_alive.seconds3600Caps HTTP keep-alive, plan reconnects
AWS ALBderegistration_delay.timeout_seconds300At least your drain window
AWS API Gateway WebSocketIdle timeout / connection duration10 min / 2 hNot adjustable; heartbeat and reconnect every < 2 h
AWS API Gateway WebSocketFrame / message size; new connections32 KB / 128 KB; 500 per s per account per RegionSplit frames; request quota increases
Laravel Reverbping_interval, activity_timeout60, 30Below the proxy idle timeout
Laravel Reverbmax_message_size, max_request_size, max_connections10,000 bytes, 10,000 bytes, unsetCap abuse
Laravel ReverbREVERB_SCALING_ENABLED, REVERB_SCALING_CHANNELfalse, reverbtrue with a central Redis
Socket.IOpingInterval, pingTimeout25000 ms, 20000 msBelow proxy timeouts
Pusher protocolClient activity timeout, pong wait120 s, 30 s (recommended)Server value via activity_timeout
coder/websocketSetReadLimit32768 bytesYour maximum message size
Browser EventSourceReconnection time"a few seconds", implementation-definedretry:
KubernetesterminationGracePeriodSeconds30 sAt least the drain window

Error messages you will actually see ​

WhereMessageMeaning
coder/websocket Acceptrequest Origin "evil.example.net" is not authorized for Host "rt.example.com"Origin check refused the handshake (403)
coder/websocket AcceptWebSocket protocol violation: Connection header "keep-alive" does not contain UpgradeA proxy dropped hop-by-hop headers (NGINX without proxy_set_header)
coder/websocket Acceptunsupported WebSocket protocol version (only 13 is supported)Old or broken client
coder/websocket readread limited at 32769 bytesMessage over SetReadLimit; connection closed with 1009
Browser consoleWebSocket connection to 'wss://...' failedNo 101: wrong path, proxy, TLS, or HTTP error
Reverb / Pusher{"event":"pusher:error","data":{"code":4200,"message":"Invalid message format"}}Client sent non-Pusher JSON
AWS API GatewayClose 1009Frame over 32 KB
Laravel eventStreamFinal event with data </stream>End marker the framework appends; close the EventSource on it
NGINX504 Gateway Time-out on a long pollHold time above proxy_read_timeout
AWS ALB504 on a long poll, silent drop on WebSocketHold or silence above the idle timeout

Capacity arithmetic ​

QuantityFormulaExample (back-of-envelope)
Short-poll request rateclients / interval200,000 open pages / 5 s = 40,000 req/s, mostly empty
Long-poll request rateclients / hold + events200,000 / 25 s = 8,000 req/s at idle
Heartbeat rateconnections / ping interval1,000,000 / 25 s = 40,000 pings/s
Connection memoryconnections x per-connection cost1,000,000 x 40 KB = 40 GB across the fleet
Fan-out writesmembers x messages/sroom of 10,000 x 2 msg/s = 20,000 writes/s
Presence fan-out (naive)members^2 on a full join1,000 members each announcing to 999 = ~1,000,000 messages
Reconnect rate after drainconnections / drain window100,000 / 300 s = 333/s
History needed for resumepublish rate x (drain window + max jitter)50 msg/s x 330 s = 16,500 messages per hot room

Go ​

The module academy/realtime-polling-sse-websockets uses the standard library plus github.com/coder/websocket v1.8.15 (the maintained successor of nhooyr.io/websocket), github.com/redis/go-redis/v9 v9.17.0 and, in tests only, github.com/alicebob/miniredis/v2, so every test runs without a Redis server. go vet and go test -race pass.

Before ​

Short polling with no cursor, no caching and a fixed interval:

go
// Package before shows the first version most teams ship: short polling.
// It works, and it is bad design at scale: every client asks every second,
// almost every answer is "nothing changed", and each answer re-sends the
// whole resource and costs a database query.
package before

import (
	"context"
	"database/sql"
	"encoding/json"
	"net/http"
	"time"
)

// Order is the resource the page wants to keep fresh.
type Order struct {
	ID     int64  `json:"id"`
	Status string `json:"status"`
}

// StatusHandler answers GET /orders/{id}/status with the full order every time.
// No cursor, no ETag, no caching: 10,000 open tabs polling every second are
// 10,000 queries per second even when nothing happens.
func StatusHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var o Order
		err := db.QueryRowContext(r.Context(),
			`SELECT id, status FROM orders WHERE id = $1`, r.PathValue("id")).Scan(&o.ID, &o.Status)
		if err != nil {
			http.Error(w, "not found", http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(o)
	}
}

// PollLoop is the matching client: a fixed one-second interval with no jitter,
// so every client that loaded the page at the same moment stays in lock-step.
func PollLoop(ctx context.Context, c *http.Client, url string, onChange func(Order)) {
	t := time.NewTicker(time.Second)
	defer t.Stop()
	var last Order
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
		}
		resp, err := c.Get(url)
		if err != nil {
			continue
		}
		var o Order
		_ = json.NewDecoder(resp.Body).Decode(&o)
		resp.Body.Close()
		if o != last {
			last = o
			onChange(o)
		}
	}
}

After ​

The shared event log. Every transport resumes from the same cursor. Since reports a gap when the cursor is older than the retained window; Wait is how a hanging GET sleeps without polling.

go
// Package stream is the shared building block for every transport on the page:
// an append-only, bounded log of events with a monotonically increasing
// sequence number. Long polling, SSE and WebSockets all resume from a cursor
// (the last sequence number the client saw) against this log.
package stream

import (
	"context"
	"sync"
)

// Event is one published message. Seq is assigned by the log and is the
// resume cursor (SSE "id:", long-poll "cursor", WebSocket "seq").
type Event struct {
	Seq   uint64 `json:"seq"`
	Topic string `json:"topic"`
	Data  string `json:"data"`
}

// Log keeps the last Capacity events in memory. A real system keeps this
// window in Redis (sorted set or stream), Kafka or a database table.
type Log struct {
	mu       sync.Mutex
	capacity int
	events   []Event
	next     uint64
	changed  chan struct{} // closed and replaced on every Append
}

// NewLog returns a log that retains at most capacity events.
func NewLog(capacity int) *Log {
	return &Log{capacity: capacity, next: 1, changed: make(chan struct{})}
}

// Append stores an event, assigns its sequence number and wakes every waiter.
func (l *Log) Append(topic, data string) Event {
	l.mu.Lock()
	defer l.mu.Unlock()
	e := Event{Seq: l.next, Topic: topic, Data: data}
	l.next++
	l.events = append(l.events, e)
	if len(l.events) > l.capacity {
		l.events = l.events[len(l.events)-l.capacity:]
	}
	close(l.changed)
	l.changed = make(chan struct{})
	return e
}

// Since returns events with Seq > cursor for the topic ("" means all topics).
// ok is false when the cursor is older than the retained window: the client
// missed events that are gone and must reload full state (a "gap").
func (l *Log) Since(cursor uint64, topic string) (events []Event, ok bool) {
	l.mu.Lock()
	defer l.mu.Unlock()
	if len(l.events) > 0 && cursor+1 < l.events[0].Seq {
		return nil, false
	}
	for _, e := range l.events {
		if e.Seq > cursor && (topic == "" || e.Topic == topic) {
			events = append(events, e)
		}
	}
	return events, true
}

// Head returns the sequence number of the newest event (0 if empty).
func (l *Log) Head() uint64 {
	l.mu.Lock()
	defer l.mu.Unlock()
	return l.next - 1
}

// Wait blocks until an event newer than cursor exists for the topic, or ctx
// ends. It is the core of a hanging GET: no busy loop, no sleep.
func (l *Log) Wait(ctx context.Context, cursor uint64, topic string) ([]Event, bool, error) {
	for {
		l.mu.Lock()
		ch := l.changed
		l.mu.Unlock()
		events, ok := l.Since(cursor, topic)
		if !ok || len(events) > 0 {
			return events, ok, nil
		}
		select {
		case <-ch:
		case <-ctx.Done():
			return nil, true, ctx.Err()
		}
	}
}

Long polling with a 25 s hold, 204 on timeout, 409 on an expired cursor and Cache-Control: no-store:

go
// Package longpoll implements a hanging GET: the server holds the request
// until there is something newer than the client's cursor or a timeout fires.
package longpoll

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"strconv"
	"time"

	"academy/realtime-polling-sse-websockets/stream"
)

// Response is the body of a 200 answer. The client sends Cursor back on the
// next request, so nothing is lost between two polls.
type Response struct {
	Events []stream.Event `json:"events"`
	Cursor uint64         `json:"cursor"`
}

// Handler serves GET /poll?topic=orders.42&cursor=17.
//
//   - Hold time must stay below every idle timeout on the path (NGINX
//     proxy_read_timeout 60 s, AWS ALB idle_timeout 60 s by default); RFC 6202
//     calls 30 s "a safer value".
//   - 200 with events and the new cursor, 204 when the hold time expired,
//     409 when the cursor is older than the retained window (reload state).
type Handler struct {
	Log  *stream.Log
	Hold time.Duration // default 25 s
}

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	hold := h.Hold
	if hold == 0 {
		hold = 25 * time.Second
	}
	cursor, err := strconv.ParseUint(r.URL.Query().Get("cursor"), 10, 64)
	if err != nil && r.URL.Query().Get("cursor") != "" {
		http.Error(w, "bad cursor", http.StatusBadRequest)
		return
	}
	topic := r.URL.Query().Get("topic")

	ctx, cancel := context.WithTimeout(r.Context(), hold)
	defer cancel()
	events, ok, err := h.Log.Wait(ctx, cursor, topic)

	// Intermediaries must never cache a long-poll answer (RFC 6202, 5.6).
	w.Header().Set("Cache-Control", "no-store")
	switch {
	case !ok:
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusConflict)
		_ = json.NewEncoder(w).Encode(map[string]any{"error": "cursor_expired", "head": h.Log.Head()})
	case errors.Is(err, context.DeadlineExceeded):
		w.WriteHeader(http.StatusNoContent) // client re-polls immediately with the same cursor
	case err != nil:
		return // client went away; nothing to write
	default:
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(Response{Events: events, Cursor: events[len(events)-1].Seq})
	}
}
go
package longpoll

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/realtime-polling-sse-websockets/stream"
)

func TestHangingGetReleasedByAppend(t *testing.T) {
	l := stream.NewLog(100)
	srv := httptest.NewServer(Handler{Log: l, Hold: 2 * time.Second})
	defer srv.Close()

	go func() {
		time.Sleep(50 * time.Millisecond)
		l.Append("orders.42", `{"status":"paid"}`)
	}()
	start := time.Now()
	resp, err := http.Get(srv.URL + "?topic=orders.42&cursor=0")
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	var body Response
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != 200 || body.Cursor != 1 || len(body.Events) != 1 {
		t.Fatalf("status=%d body=%+v", resp.StatusCode, body)
	}
	if time.Since(start) > time.Second {
		t.Fatal("request was not released by the append")
	}
}

func TestTimeoutReturns204(t *testing.T) {
	srv := httptest.NewServer(Handler{Log: stream.NewLog(10), Hold: 50 * time.Millisecond})
	defer srv.Close()
	resp, err := http.Get(srv.URL + "?topic=orders.42&cursor=0")
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusNoContent {
		t.Fatalf("status=%d, want 204", resp.StatusCode)
	}
}

func TestExpiredCursorReturns409(t *testing.T) {
	l := stream.NewLog(2)
	for i := 0; i < 5; i++ {
		l.Append("orders.42", "x")
	}
	srv := httptest.NewServer(Handler{Log: l, Hold: 50 * time.Millisecond})
	defer srv.Close()
	resp, err := http.Get(srv.URL + "?topic=orders.42&cursor=1")
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusConflict {
		t.Fatalf("status=%d, want 409", resp.StatusCode)
	}
}

SSE with resume. id: on every event, retry: once, : ping comments, Last-Event-ID or ?lastEventId= on connect, a reset event on a gap, and a maximum stream age so connections rebalance. The test reconnects with Last-Event-ID: 1 and checks the replay and a multi-line live event.

go
// Package sse serves Server-Sent Events (text/event-stream) with resume:
// every event carries "id: <seq>", the browser's EventSource sends it back as
// the Last-Event-ID header when it reconnects, and the server replays the gap.
package sse

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"academy/realtime-polling-sse-websockets/stream"
)

// Handler serves GET /events?topic=orders.42.
type Handler struct {
	Log       *stream.Log
	Retry     time.Duration // sent once as "retry:"; EventSource waits this long before reconnecting
	Heartbeat time.Duration // comment line so idle proxies keep the stream open (spec: "every 15 seconds or so")
	MaxAge    time.Duration // end the stream after this long so connections rebalance across servers
}

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rc := http.NewResponseController(w)
	topic := r.URL.Query().Get("topic")

	// Resume cursor: the header on automatic reconnects, a query parameter on
	// the first connect (EventSource cannot set headers itself).
	raw := r.Header.Get("Last-Event-ID")
	if raw == "" {
		raw = r.URL.Query().Get("lastEventId")
	}
	cursor, _ := strconv.ParseUint(raw, 10, 64)

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("X-Accel-Buffering", "no") // NGINX: do not buffer this response
	w.WriteHeader(http.StatusOK)

	if h.Retry > 0 {
		fmt.Fprintf(w, "retry: %d\n\n", h.Retry.Milliseconds())
	}
	heartbeat := time.NewTicker(orDefault(h.Heartbeat, 15*time.Second))
	defer heartbeat.Stop()
	maxAge := time.NewTimer(orDefault(h.MaxAge, 10*time.Minute))
	defer maxAge.Stop()

	for {
		events, ok := h.Log.Since(cursor, topic)
		if !ok {
			// The gap is older than our window: tell the client to reload state
			// and continue from the current head.
			cursor = h.Log.Head()
			fmt.Fprintf(w, "id: %d\nevent: reset\ndata: {}\n\n", cursor)
		}
		for _, e := range events {
			writeEvent(w, e)
			cursor = e.Seq
		}
		if err := rc.Flush(); err != nil {
			return // client is gone
		}

		waitCtx, stop := context.WithCancel(r.Context())
		wait := make(chan struct{})
		go func(c uint64) {
			_, _, _ = h.Log.Wait(waitCtx, c, topic)
			close(wait)
		}(cursor)

		select {
		case <-wait:
		case <-heartbeat.C:
			fmt.Fprint(w, ": ping\n\n")
		case <-maxAge.C:
			stop()
			return // EventSource reconnects after "retry" with Last-Event-ID
		case <-r.Context().Done():
			stop()
			return
		}
		stop() // never leave a waiter behind after a heartbeat
		<-wait
	}
}

// writeEvent frames one event. A data value with newlines becomes several
// "data:" lines; the blank line ends the event.
func writeEvent(w http.ResponseWriter, e stream.Event) {
	fmt.Fprintf(w, "id: %d\nevent: %s\n", e.Seq, e.Topic)
	for _, line := range strings.Split(e.Data, "\n") {
		fmt.Fprintf(w, "data: %s\n", line)
	}
	fmt.Fprint(w, "\n")
}

func orDefault(d, def time.Duration) time.Duration {
	if d <= 0 {
		return def
	}
	return d
}
go
package sse

import (
	"bufio"
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"academy/realtime-polling-sse-websockets/stream"
)

// readEvents reads n complete events (blocks ending in a blank line) that
// carry an id, skipping the retry block and heartbeat comments.
func readEvents(t *testing.T, sc *bufio.Scanner, n int) []string {
	t.Helper()
	var out []string
	var cur []string
	for len(out) < n && sc.Scan() {
		line := sc.Text()
		if line == "" {
			block := strings.Join(cur, "\n")
			if strings.HasPrefix(block, "id: ") {
				out = append(out, block)
			}
			cur = nil
			continue
		}
		cur = append(cur, line)
	}
	return out
}

func TestResumeFromLastEventID(t *testing.T) {
	l := stream.NewLog(100)
	for _, s := range []string{"placed", "paid", "packed"} {
		l.Append("orders.42", s)
	}
	srv := httptest.NewServer(Handler{Log: l, Retry: 3 * time.Second, Heartbeat: time.Hour})
	defer srv.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"?topic=orders.42", nil)
	req.Header.Set("Last-Event-ID", "1") // the browser saw "placed" before the drop
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	if ct := resp.Header.Get("Content-Type"); ct != "text/event-stream" {
		t.Fatalf("content-type %q", ct)
	}
	sc := bufio.NewScanner(resp.Body)

	got := readEvents(t, sc, 2)
	if len(got) != 2 || !strings.Contains(got[0], "id: 2") || !strings.Contains(got[1], "data: packed") {
		t.Fatalf("replay = %q", got)
	}

	l.Append("orders.42", "shipped\nby courier")
	live := readEvents(t, sc, 1)
	want := "id: 4\nevent: orders.42\ndata: shipped\ndata: by courier"
	if len(live) != 1 || live[0] != want {
		t.Fatalf("live = %q, want %q", live, want)
	}
}

func TestGapSendsReset(t *testing.T) {
	l := stream.NewLog(2)
	for i := 0; i < 5; i++ {
		l.Append("orders.42", "x")
	}
	srv := httptest.NewServer(Handler{Log: l, Heartbeat: time.Hour})
	defer srv.Close()
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"?topic=orders.42&lastEventId=1", nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	got := readEvents(t, bufio.NewScanner(resp.Body), 1)
	if len(got) != 1 || !strings.Contains(got[0], "event: reset") {
		t.Fatalf("got %q, want a reset event", got)
	}
}

Ticket auth and the Origin check. Single-use, 30-second tickets; the Redis form for a fleet is SET ticket:<t> <user> EX 30 NX and GETDEL ticket:<t>.

go
// Package ticket implements ticket auth for WebSocket upgrades. The browser
// WebSocket API cannot set an Authorization header, so the client first calls
// an authenticated HTTP endpoint (cookie + CSRF token, or bearer token) to get
// a short-lived, single-use ticket, then opens wss://.../ws?ticket=... .
// A leaked ticket is useless after one use or a few seconds.
package ticket

import (
	"crypto/rand"
	"encoding/base64"
	"errors"
	"net/http"
	"net/url"
	"slices"
	"strings"
	"sync"
	"time"
)

var (
	ErrUnknown = errors.New("ticket: unknown or already used")
	ErrExpired = errors.New("ticket: expired")
)

type entry struct {
	userID  string
	expires time.Time
}

// Store keeps tickets in memory. In a fleet of gateways use Redis:
// SET ticket:<t> <user> EX 30 NX on issue, GETDEL ticket:<t> on redeem.
type Store struct {
	mu  sync.Mutex
	m   map[string]entry
	TTL time.Duration
	Now func() time.Time
}

func NewStore(ttl time.Duration) *Store {
	return &Store{m: map[string]entry{}, TTL: ttl, Now: time.Now}
}

// Issue returns a 128-bit random ticket bound to the user.
func (s *Store) Issue(userID string) string {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	t := base64.RawURLEncoding.EncodeToString(b)
	s.mu.Lock()
	s.m[t] = entry{userID: userID, expires: s.Now().Add(s.TTL)}
	s.mu.Unlock()
	return t
}

// Redeem consumes the ticket: a second call with the same value fails.
func (s *Store) Redeem(t string) (string, error) {
	s.mu.Lock()
	e, ok := s.m[t]
	delete(s.m, t)
	s.mu.Unlock()
	if !ok {
		return "", ErrUnknown
	}
	if s.Now().After(e.expires) {
		return "", ErrExpired
	}
	return e.userID, nil
}

// OriginAllowed is the Cross-Site WebSocket Hijacking (CSWSH) check: browsers
// attach cookies to the upgrade request from any page, but they also send an
// Origin header that page script cannot forge. Compare it with an allowlist.
func OriginAllowed(r *http.Request, allowed []string) bool {
	o := r.Header.Get("Origin")
	if o == "" {
		return false // non-browser clients must use tokens, not cookies
	}
	u, err := url.Parse(o)
	if err != nil || u.Host == "" {
		return false
	}
	return slices.Contains(allowed, strings.ToLower(u.Scheme+"://"+u.Host))
}

The WebSocket hub. bus.go is the fan-out contract (Publish assigns the per-room sequence, Subscribe delivers, History serves resume) with an in-process implementation. hub.go holds rooms and per-connection bounded queues, kicks slow consumers with 1008 and drains with 1001 spread over a window. server.go redeems the ticket, authorizes rooms, upgrades with the Origin check and subprotocol rt.v1, replays history for ?since=, then runs one reader loop and one writer goroutine with pings.

go
package hub

import (
	"context"
	"encoding/json"
	"sync"
)

// Envelope is what every client receives. Seq is per room and gap-free, so a
// client can detect loss (seq jumped) and resume (?since=<last seq>). ID is
// the publisher's message id, used by clients to drop duplicates.
type Envelope struct {
	Room string          `json:"room"`
	Seq  uint64          `json:"seq"`
	ID   string          `json:"id"`
	Body json.RawMessage `json:"body"`
}

// Bus moves messages between gateway nodes. LocalBus is for one process;
// fanout.RedisBus is the same contract over Redis Pub/Sub.
type Bus interface {
	// Publish assigns the next per-room sequence number and fans out.
	Publish(ctx context.Context, room, id string, body []byte) (Envelope, error)
	// Subscribe delivers every published envelope until ctx ends.
	Subscribe(ctx context.Context, deliver func(Envelope)) error
	// History returns retained envelopes with Seq > after; ok is false when
	// the window no longer reaches back that far.
	History(ctx context.Context, room string, after uint64) (events []Envelope, ok bool, err error)
}

// LocalBus is an in-process Bus with a bounded history per room.
type LocalBus struct {
	mu      sync.Mutex
	keep    int
	seq     map[string]uint64
	history map[string][]Envelope
	subs    []func(Envelope)
}

func NewLocalBus(keep int) *LocalBus {
	return &LocalBus{keep: keep, seq: map[string]uint64{}, history: map[string][]Envelope{}}
}

func (b *LocalBus) Publish(_ context.Context, room, id string, body []byte) (Envelope, error) {
	b.mu.Lock()
	defer b.mu.Unlock() // held while delivering: subscribers see rooms in seq order
	b.seq[room]++
	env := Envelope{Room: room, Seq: b.seq[room], ID: id, Body: append(json.RawMessage(nil), body...)}
	h := append(b.history[room], env)
	if len(h) > b.keep {
		h = h[len(h)-b.keep:]
	}
	b.history[room] = h
	for _, s := range b.subs {
		s(env)
	}
	return env, nil
}

func (b *LocalBus) Subscribe(ctx context.Context, deliver func(Envelope)) error {
	b.mu.Lock()
	b.subs = append(b.subs, deliver)
	b.mu.Unlock()
	<-ctx.Done()
	return ctx.Err()
}

func (b *LocalBus) History(_ context.Context, room string, after uint64) ([]Envelope, bool, error) {
	b.mu.Lock()
	defer b.mu.Unlock()
	h := b.history[room]
	if len(h) > 0 && h[0].Seq > after+1 {
		return nil, false, nil
	}
	var out []Envelope
	for _, e := range h {
		if e.Seq > after {
			out = append(out, e)
		}
	}
	return out, true, nil
}
go
// Package hub is a WebSocket gateway: it owns connections, rooms and
// per-connection bounded send queues, and receives messages from a Bus.
package hub

import (
	"context"
	"encoding/json"
	"sync"
	"sync/atomic"
	"time"

	"github.com/coder/websocket"
)

// client is one WebSocket connection. send is the bounded queue: the hub never
// blocks on a slow client, it disconnects it instead (backpressure policy).
type client struct {
	conn   *websocket.Conn
	user   string
	rooms  map[string]bool
	send   chan []byte
	once   sync.Once
	closed chan struct{}

	mu        sync.Mutex
	replaying bool
	pending   []Envelope
	lastSeq   map[string]uint64
}

// Hub maps rooms to local connections. One Hub per gateway process.
type Hub struct {
	mu        sync.RWMutex
	rooms     map[string]map[*client]struct{}
	conns     map[*client]struct{}
	queueSize int

	Kicked   atomic.Int64 // slow consumers disconnected
	Draining atomic.Bool
}

func New(queueSize int) *Hub {
	return &Hub{rooms: map[string]map[*client]struct{}{}, conns: map[*client]struct{}{}, queueSize: queueSize}
}

// Len is the number of open connections on this node.
func (h *Hub) Len() int {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return len(h.conns)
}

func (h *Hub) add(c *client) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.conns[c] = struct{}{}
	for r := range c.rooms {
		if h.rooms[r] == nil {
			h.rooms[r] = map[*client]struct{}{}
		}
		h.rooms[r][c] = struct{}{}
	}
}

func (h *Hub) remove(c *client) {
	h.mu.Lock()
	defer h.mu.Unlock()
	delete(h.conns, c)
	for r := range c.rooms {
		delete(h.rooms[r], c)
		if len(h.rooms[r]) == 0 {
			delete(h.rooms, r)
		}
	}
}

// Deliver is called by the Bus subscriber for every envelope. It encodes once
// and does a non-blocking send into each member's queue.
func (h *Hub) Deliver(env Envelope) {
	data, err := json.Marshal(env)
	if err != nil {
		return
	}
	h.mu.RLock()
	members := make([]*client, 0, len(h.rooms[env.Room]))
	for c := range h.rooms[env.Room] {
		members = append(members, c)
	}
	h.mu.RUnlock()
	for _, c := range members {
		h.enqueue(c, env, data)
	}
}

func (h *Hub) enqueue(c *client, env Envelope, data []byte) {
	c.mu.Lock()
	if c.replaying { // history replay in progress: hold live messages back
		if len(c.pending) >= h.queueSize {
			c.mu.Unlock()
			h.kick(c, websocket.StatusPolicyViolation, "slow consumer")
			return
		}
		c.pending = append(c.pending, env)
		c.mu.Unlock()
		return
	}
	if env.Seq <= c.lastSeq[env.Room] { // already sent during replay
		c.mu.Unlock()
		return
	}
	c.lastSeq[env.Room] = env.Seq
	c.mu.Unlock()
	select {
	case c.send <- data:
	default:
		h.kick(c, websocket.StatusPolicyViolation, "slow consumer")
	}
}

// kick closes a connection once, in the background (Close waits for the
// close handshake and must not run on the fan-out path).
func (h *Hub) kick(c *client, code websocket.StatusCode, reason string) {
	c.once.Do(func() {
		if code == websocket.StatusPolicyViolation {
			h.Kicked.Add(1)
		}
		close(c.closed)
		go c.conn.Close(code, reason)
	})
}

// Drain stops new connections and closes existing ones with 1001 Going Away,
// spread evenly over window so clients do not all reconnect in one second.
func (h *Hub) Drain(ctx context.Context, window time.Duration) {
	h.Draining.Store(true)
	h.mu.RLock()
	all := make([]*client, 0, len(h.conns))
	for c := range h.conns {
		all = append(all, c)
	}
	h.mu.RUnlock()
	if len(all) == 0 {
		return
	}
	step := window / time.Duration(len(all))
	for _, c := range all {
		h.kick(c, websocket.StatusGoingAway, "server draining, reconnect")
		select {
		case <-time.After(step):
		case <-ctx.Done():
			return
		}
	}
}
go
package hub

import (
	"context"
	"encoding/json"
	"net/http"
	"strconv"
	"time"

	"github.com/coder/websocket"

	"academy/realtime-polling-sse-websockets/ticket"
)

// Subprotocol is negotiated with Sec-WebSocket-Protocol. Versioning the
// application protocol here lets old and new clients coexist during a rollout.
const Subprotocol = "rt.v1"

// Server upgrades GET /ws?ticket=...&room=a&room=b&since=17 to a WebSocket.
type Server struct {
	Hub       *Hub
	Bus       Bus
	Tickets   *ticket.Store
	Origins   []string                      // host patterns for the Origin check, e.g. "app.example.com"
	Authorize func(user, room string) bool  // private channel check, like Laravel's routes/channels.php
	PingEvery time.Duration                 // below every idle timeout on the path (ALB 60 s, NGINX 60 s)
	Write     time.Duration                 // per-message write deadline
	ReadLimit int64                         // max inbound message size in bytes
	OnPublish func(user string, e Envelope) // optional hook (tests, metrics)
}

type inbound struct {
	Type string          `json:"type"` // "publish"
	Room string          `json:"room"`
	ID   string          `json:"id"` // client-generated, reused on retry: enables dedup
	Body json.RawMessage `json:"body"`
}

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.Hub.Draining.Load() {
		w.Header().Set("Retry-After", "5")
		http.Error(w, "draining", http.StatusServiceUnavailable)
		return
	}
	// 1. Authenticate before the upgrade: a single-use ticket from an
	//    authenticated HTTP call (browsers cannot set Authorization on ws://).
	user, err := s.Tickets.Redeem(r.URL.Query().Get("ticket"))
	if err != nil {
		http.Error(w, "invalid ticket", http.StatusUnauthorized)
		return
	}
	rooms := map[string]bool{}
	for _, room := range r.URL.Query()["room"] {
		if s.Authorize != nil && !s.Authorize(user, room) {
			http.Error(w, "forbidden room", http.StatusForbidden)
			return
		}
		rooms[room] = true
	}
	since, _ := strconv.ParseUint(r.URL.Query().Get("since"), 10, 64)

	// 2. Upgrade: Accept checks Origin against OriginPatterns (CSWSH), answers
	//    101 Switching Protocols with Sec-WebSocket-Accept and the subprotocol.
	conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
		Subprotocols:    []string{Subprotocol},
		OriginPatterns:  s.Origins,
		CompressionMode: websocket.CompressionDisabled, // permessage-deflate costs memory per connection
	})
	if err != nil {
		return // Accept already wrote 403 or 400
	}
	if conn.Subprotocol() != Subprotocol {
		conn.Close(websocket.StatusPolicyViolation, "subprotocol "+Subprotocol+" required")
		return
	}
	conn.SetReadLimit(s.ReadLimit) // larger messages close the connection with 1009

	c := &client{conn: conn, user: user, rooms: rooms, send: make(chan []byte, s.Hub.queueSize),
		closed: make(chan struct{}), replaying: true, lastSeq: map[string]uint64{}}
	s.Hub.add(c)
	defer s.Hub.remove(c)

	// The request context must not be used after Accept (hijacked connection).
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go s.writer(ctx, c)

	// 3. Resume: replay what the client missed, then release held live messages.
	if since > 0 {
		for room := range rooms {
			events, ok, err := s.Bus.History(ctx, room, since)
			if err != nil || !ok {
				s.Hub.kick(c, websocket.StatusTryAgainLater, "history gap, reload state")
				return
			}
			for _, e := range events {
				data, _ := json.Marshal(e)
				c.send <- data // the writer is already draining the queue
				c.mu.Lock()
				c.lastSeq[room] = e.Seq
				c.mu.Unlock()
			}
		}
	}
	c.mu.Lock()
	c.replaying = false
	held := c.pending
	c.pending = nil
	c.mu.Unlock()
	for _, e := range held {
		data, _ := json.Marshal(e)
		s.Hub.enqueue(c, e, data)
	}

	// 4. Read loop: the only reader of this connection.
	for {
		_, data, err := conn.Read(ctx)
		if err != nil {
			s.Hub.kick(c, websocket.StatusNormalClosure, "")
			return
		}
		var in inbound
		if json.Unmarshal(data, &in) != nil || in.Type != "publish" || !rooms[in.Room] || in.ID == "" {
			s.Hub.kick(c, websocket.StatusUnsupportedData, "bad message")
			return
		}
		env, err := s.Bus.Publish(ctx, in.Room, in.ID, in.Body)
		if err != nil {
			s.Hub.kick(c, websocket.StatusInternalError, "publish failed")
			return
		}
		if s.OnPublish != nil {
			s.OnPublish(user, env)
		}
	}
}

// writer is the only goroutine that writes data frames to the connection.
// It drains the bounded queue and sends a ping on a timer; a missing pong
// within the write deadline closes the connection.
func (s *Server) writer(ctx context.Context, c *client) {
	ping := time.NewTicker(s.PingEvery)
	defer ping.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-c.closed:
			return
		case msg := <-c.send:
			wctx, cancel := context.WithTimeout(ctx, s.Write)
			err := c.conn.Write(wctx, websocket.MessageText, msg)
			cancel()
			if err != nil {
				s.Hub.kick(c, websocket.StatusGoingAway, "write timeout")
				return
			}
		case <-ping.C:
			pctx, cancel := context.WithTimeout(ctx, s.Write)
			err := c.conn.Ping(pctx) // waits for the pong
			cancel()
			if err != nil {
				s.Hub.kick(c, websocket.StatusGoingAway, "ping timeout")
				return
			}
		}
	}
}

The tests cover room fan-out, a forged ticket (401), a cross-site Origin (403), someone else's private room (403), resume from since, a slow consumer being disconnected instead of buffered, and drain (1001 to existing clients, 503 to new ones):

go
package hub

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/coder/websocket"

	"academy/realtime-polling-sse-websockets/ticket"
)

type fixture struct {
	srv     *httptest.Server
	hub     *Hub
	bus     *LocalBus
	tickets *ticket.Store
}

func newFixture(t *testing.T, queue int) *fixture {
	t.Helper()
	f := &fixture{hub: New(queue), bus: NewLocalBus(100), tickets: ticket.NewStore(30 * time.Second)}
	ctx, cancel := context.WithCancel(context.Background())
	t.Cleanup(cancel)
	go f.bus.Subscribe(ctx, f.hub.Deliver)
	time.Sleep(10 * time.Millisecond) // let the subscriber register
	f.srv = httptest.NewServer(&Server{
		Hub: f.hub, Bus: f.bus, Tickets: f.tickets,
		Origins:   []string{"app.example.com"},
		Authorize: func(user, room string) bool { return !strings.HasPrefix(room, "private.") || room == "private."+user },
		PingEvery: time.Second, Write: time.Second, ReadLimit: 1 << 16,
	})
	t.Cleanup(f.srv.Close)
	return f
}

func (f *fixture) dial(t *testing.T, user, query string, hdr http.Header) (*websocket.Conn, *http.Response, error) {
	t.Helper()
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	u := "ws" + strings.TrimPrefix(f.srv.URL, "http") + "/ws?ticket=" + f.tickets.Issue(user) + "&" + query
	return websocket.Dial(ctx, u, &websocket.DialOptions{Subprotocols: []string{Subprotocol}, HTTPHeader: hdr})
}

func readEnv(t *testing.T, c *websocket.Conn) Envelope {
	t.Helper()
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	_, data, err := c.Read(ctx)
	if err != nil {
		t.Fatalf("read: %v", err)
	}
	var e Envelope
	if err := json.Unmarshal(data, &e); err != nil {
		t.Fatal(err)
	}
	return e
}

func TestFanOutToRoomMembers(t *testing.T) {
	f := newFixture(t, 16)
	a, _, err := f.dial(t, "alice", "room=chat.1", nil)
	if err != nil {
		t.Fatal(err)
	}
	defer a.CloseNow()
	b, _, err := f.dial(t, "bob", "room=chat.1", nil)
	if err != nil {
		t.Fatal(err)
	}
	defer b.CloseNow()
	if a.Subprotocol() != Subprotocol {
		t.Fatalf("subprotocol %q", a.Subprotocol())
	}

	msg := `{"type":"publish","room":"chat.1","id":"m-1","body":{"text":"hi"}}`
	if err := a.Write(context.Background(), websocket.MessageText, []byte(msg)); err != nil {
		t.Fatal(err)
	}
	for _, c := range []*websocket.Conn{a, b} {
		e := readEnv(t, c)
		if e.Seq != 1 || e.ID != "m-1" || string(e.Body) != `{"text":"hi"}` {
			t.Fatalf("got %+v", e)
		}
	}
}

func TestRejectsBadTicketOriginAndRoom(t *testing.T) {
	f := newFixture(t, 16)

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	u := "ws" + strings.TrimPrefix(f.srv.URL, "http") + "/ws?ticket=forged&room=chat.1"
	if _, resp, err := websocket.Dial(ctx, u, nil); err == nil || resp.StatusCode != http.StatusUnauthorized {
		t.Fatalf("forged ticket: err=%v", err)
	}

	hdr := http.Header{"Origin": {"https://evil.example.net"}}
	if _, resp, err := f.dial(t, "alice", "room=chat.1", hdr); err == nil || resp.StatusCode != http.StatusForbidden {
		t.Fatalf("cross-site origin: err=%v", err)
	}

	if _, resp, err := f.dial(t, "alice", "room=private.bob", nil); err == nil || resp.StatusCode != http.StatusForbidden {
		t.Fatalf("someone else's private room: err=%v", err)
	}
}

func TestResumeFromSince(t *testing.T) {
	f := newFixture(t, 16)
	for i := 0; i < 3; i++ {
		f.bus.Publish(context.Background(), "orders.42", "srv-"+string(rune('a'+i)), []byte(`{}`))
	}
	c, _, err := f.dial(t, "alice", "room=orders.42&since=1", nil)
	if err != nil {
		t.Fatal(err)
	}
	defer c.CloseNow()
	if e := readEnv(t, c); e.Seq != 2 {
		t.Fatalf("first replayed seq %d, want 2", e.Seq)
	}
	if e := readEnv(t, c); e.Seq != 3 {
		t.Fatalf("second replayed seq %d, want 3", e.Seq)
	}
	f.bus.Publish(context.Background(), "orders.42", "srv-d", []byte(`{}`))
	if e := readEnv(t, c); e.Seq != 4 {
		t.Fatalf("live seq %d, want 4", e.Seq)
	}
}

func TestSlowConsumerIsDisconnected(t *testing.T) {
	f := newFixture(t, 4)
	slow, _, err := f.dial(t, "alice", "room=ticker", nil)
	if err != nil {
		t.Fatal(err)
	}
	defer slow.CloseNow() // never reads: its TCP window fills, then its queue
	big := []byte(`"` + strings.Repeat("x", 64<<10) + `"`)
	deadline := time.Now().Add(5 * time.Second)
	for f.hub.Kicked.Load() == 0 && time.Now().Before(deadline) {
		f.bus.Publish(context.Background(), "ticker", "t", big)
	}
	if f.hub.Kicked.Load() != 1 {
		t.Fatal("slow consumer was not disconnected; the hub would buffer without bound")
	}
}

func TestDrainSendsGoingAway(t *testing.T) {
	f := newFixture(t, 16)
	c, _, err := f.dial(t, "alice", "room=chat.1", nil)
	if err != nil {
		t.Fatal(err)
	}
	defer c.CloseNow()
	go f.hub.Drain(context.Background(), 100*time.Millisecond)
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	_, _, err = c.Read(ctx)
	if got := websocket.CloseStatus(err); got != websocket.StatusGoingAway {
		t.Fatalf("close status %v, want 1001", got)
	}
	if _, resp, err := f.dial(t, "bob", "room=chat.1", nil); err == nil || resp.StatusCode != http.StatusServiceUnavailable {
		t.Fatalf("new connection during drain: err=%v", err)
	}
}

Redis fan-out between gateways. One Lua script does INCR, ZADD, ZREMRANGEBYRANK and PUBLISH, so sequence order equals publish order even with many app servers; keys share a hash tag (rt:{room}:...) so the script works on Redis Cluster. The test runs two "nodes" against one miniredis.

go
// Package fanout implements hub.Bus over Redis: one Lua script assigns the
// per-room sequence number, appends to a bounded history and PUBLISHes, so
// sequence order and publish order can never disagree. Every gateway node
// PSUBSCRIBEs and delivers to its local members.
//
// Redis Pub/Sub is at-most-once ("If the subscriber is unable to handle the
// message ... the message is forever lost"), which is why the history sorted
// set exists: a client that saw a gap resumes from it with ?since=<seq>.
package fanout

import (
	"context"
	"errors"
	"strconv"
	"strings"

	"github.com/redis/go-redis/v9"

	"academy/realtime-polling-sse-websockets/hub"
)

// KEYS[1] seq counter, KEYS[2] history zset; ARGV[1] channel, ARGV[2] id,
// ARGV[3] body, ARGV[4] history length.
var publish = redis.NewScript(`
local seq = redis.call('INCR', KEYS[1])
local payload = seq .. '\n' .. ARGV[2] .. '\n' .. ARGV[3]
redis.call('ZADD', KEYS[2], seq, payload)
redis.call('ZREMRANGEBYRANK', KEYS[2], 0, -(tonumber(ARGV[4]) + 1))
redis.call('PUBLISH', ARGV[1], payload)
return seq
`)

// RedisBus is a hub.Bus backed by Redis Pub/Sub plus a sorted-set history.
type RedisBus struct {
	RDB  *redis.Client
	Keep int // history length per room
}

func channel(room string) string { return "rt:room:" + room }

// Keys share a hash tag so the script's keys land in one Redis Cluster slot.
func keys(room string) []string { return []string{"rt:{" + room + "}:seq", "rt:{" + room + "}:hist"} }

func (b RedisBus) Publish(ctx context.Context, room, id string, body []byte) (hub.Envelope, error) {
	if strings.ContainsRune(id, '\n') {
		return hub.Envelope{}, errors.New("fanout: id must not contain a newline")
	}
	seq, err := publish.Run(ctx, b.RDB, keys(room), channel(room), id, string(body), b.Keep).Uint64()
	if err != nil {
		return hub.Envelope{}, err
	}
	return hub.Envelope{Room: room, Seq: seq, ID: id, Body: body}, nil
}

func (b RedisBus) Subscribe(ctx context.Context, deliver func(hub.Envelope)) error {
	ps := b.RDB.PSubscribe(ctx, channel("*"))
	defer ps.Close()
	if _, err := ps.Receive(ctx); err != nil { // wait for the psubscribe confirmation
		return err
	}
	ch := ps.Channel()
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case m, ok := <-ch:
			if !ok {
				return errors.New("fanout: subscription closed")
			}
			if env, err := decode(strings.TrimPrefix(m.Channel, "rt:room:"), m.Payload); err == nil {
				deliver(env)
			}
		}
	}
}

func (b RedisBus) History(ctx context.Context, room string, after uint64) ([]hub.Envelope, bool, error) {
	k := keys(room)[1]
	oldest, err := b.RDB.ZRangeWithScores(ctx, k, 0, 0).Result()
	if err != nil {
		return nil, false, err
	}
	if len(oldest) == 1 && uint64(oldest[0].Score) > after+1 {
		return nil, false, nil // the window starts after the client's cursor: gap
	}
	raw, err := b.RDB.ZRangeByScore(ctx, k, &redis.ZRangeBy{Min: "(" + strconv.FormatUint(after, 10), Max: "+inf"}).Result()
	if err != nil {
		return nil, false, err
	}
	out := make([]hub.Envelope, 0, len(raw))
	for _, p := range raw {
		env, err := decode(room, p)
		if err != nil {
			return nil, false, err
		}
		out = append(out, env)
	}
	return out, true, nil
}

func decode(room, payload string) (hub.Envelope, error) {
	parts := strings.SplitN(payload, "\n", 3)
	if len(parts) != 3 {
		return hub.Envelope{}, errors.New("fanout: bad payload")
	}
	seq, err := strconv.ParseUint(parts[0], 10, 64)
	if err != nil {
		return hub.Envelope{}, err
	}
	return hub.Envelope{Room: room, Seq: seq, ID: parts[1], Body: []byte(parts[2])}, nil
}
go
package fanout

import (
	"context"
	"sync"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/redis/go-redis/v9"

	"academy/realtime-polling-sse-websockets/hub"
)

// Two gateway nodes share one Redis. A message published through node A
// reaches a subscriber on node B, with the sequence number from Redis.
func TestTwoNodesShareRedis(t *testing.T) {
	mr := miniredis.RunT(t)
	nodeA := RedisBus{RDB: redis.NewClient(&redis.Options{Addr: mr.Addr()}), Keep: 3}
	nodeB := RedisBus{RDB: redis.NewClient(&redis.Options{Addr: mr.Addr()}), Keep: 3}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	var mu sync.Mutex
	var got []hub.Envelope
	ready := make(chan struct{})
	go func() {
		ps := nodeB.RDB.PSubscribe(ctx, "rt:room:*")
		_, _ = ps.Receive(ctx)
		ps.Close()
		close(ready)
		_ = nodeB.Subscribe(ctx, func(e hub.Envelope) { mu.Lock(); got = append(got, e); mu.Unlock() })
	}()
	<-ready
	time.Sleep(50 * time.Millisecond)

	for _, id := range []string{"m1", "m2", "m3", "m4"} {
		if _, err := nodeA.Publish(ctx, "chat.1", id, []byte(`{"t":"`+id+`"}`)); err != nil {
			t.Fatal(err)
		}
	}
	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		mu.Lock()
		n := len(got)
		mu.Unlock()
		if n == 4 {
			break
		}
		time.Sleep(10 * time.Millisecond)
	}
	mu.Lock()
	defer mu.Unlock()
	if len(got) != 4 || got[0].Seq != 1 || got[3].Seq != 4 || got[3].ID != "m4" || got[0].Room != "chat.1" {
		t.Fatalf("node B received %+v", got)
	}

	// History keeps the last 3: resuming from 1 works, from 0 is a gap.
	ev, ok, err := nodeB.History(ctx, "chat.1", 1)
	if err != nil || !ok || len(ev) != 3 || ev[0].Seq != 2 {
		t.Fatalf("history after 1: %+v ok=%v err=%v", ev, ok, err)
	}
	if _, ok, _ := nodeB.History(ctx, "chat.1", 0); ok {
		t.Fatal("history after 0 should report a gap")
	}
}

Presence with a sorted set of user|connection entries scored by expiry. Transitions are reported only on the first device in and the last device out; last seen is written then.

go
// Package presence tracks who is online with heartbeats and expiring entries
// in Redis. One sorted set per room holds "user|connection" members scored by
// their expiry time, so:
//   - multi-device is natural: a user is online while any connection is live;
//   - a crashed gateway needs no cleanup: its entries simply expire;
//   - Heartbeat and Leave report transitions, so the app fans out a presence
//     change only when a user goes online or offline, not on every heartbeat.
package presence

import (
	"context"
	"strconv"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

type Tracker struct {
	RDB *redis.Client
	TTL time.Duration // 2-3 heartbeat intervals; Ably waits 15 s before a leave
}

func roomKey(room string) string     { return "presence:" + room }
func lastSeenKey(user string) string { return "lastseen:" + user }

// Heartbeat registers or refreshes one connection. cameOnline is true when
// this is the user's first live connection in the room.
func (t Tracker) Heartbeat(ctx context.Context, room, user, conn string, now time.Time) (cameOnline bool, err error) {
	before, err := t.devices(ctx, room, user, now)
	if err != nil {
		return false, err
	}
	exp := float64(now.Add(t.TTL).UnixMilli())
	if err := t.RDB.ZAdd(ctx, roomKey(room), redis.Z{Score: exp, Member: user + "|" + conn}).Err(); err != nil {
		return false, err
	}
	return before == 0, nil
}

// Leave removes a connection on a clean close. wentOffline is true when it
// was the user's last device; last-seen is recorded then.
func (t Tracker) Leave(ctx context.Context, room, user, conn string, now time.Time) (wentOffline bool, err error) {
	if err := t.RDB.ZRem(ctx, roomKey(room), user+"|"+conn).Err(); err != nil {
		return false, err
	}
	n, err := t.devices(ctx, room, user, now)
	if err != nil || n > 0 {
		return false, err
	}
	return true, t.RDB.Set(ctx, lastSeenKey(user), now.Unix(), 30*24*time.Hour).Err()
}

// Online prunes expired connections and returns the distinct online users.
// A user whose entries all expired is offline; last-seen is recorded when
// the prune notices (at most one Online call after the TTL).
func (t Tracker) Online(ctx context.Context, room string, now time.Time) ([]string, error) {
	cutoff := strconv.FormatInt(now.UnixMilli(), 10)
	expired, err := t.RDB.ZRangeByScore(ctx, roomKey(room), &redis.ZRangeBy{Min: "-inf", Max: cutoff}).Result()
	if err != nil {
		return nil, err
	}
	if len(expired) > 0 {
		t.RDB.ZRemRangeByScore(ctx, roomKey(room), "-inf", cutoff)
		for _, m := range expired {
			user, _, _ := strings.Cut(m, "|")
			if n, _ := t.devices(ctx, room, user, now); n == 0 {
				t.RDB.Set(ctx, lastSeenKey(user), now.Unix(), 30*24*time.Hour)
			}
		}
	}
	live, err := t.RDB.ZRangeByScore(ctx, roomKey(room), &redis.ZRangeBy{Min: "(" + cutoff, Max: "+inf"}).Result()
	if err != nil {
		return nil, err
	}
	seen := map[string]bool{}
	var users []string
	for _, m := range live {
		user, _, _ := strings.Cut(m, "|")
		if !seen[user] {
			seen[user] = true
			users = append(users, user)
		}
	}
	return users, nil
}

// LastSeen returns the Unix time of the user's last disconnect (0 if never).
func (t Tracker) LastSeen(ctx context.Context, user string) (int64, error) {
	v, err := t.RDB.Get(ctx, lastSeenKey(user)).Int64()
	if err == redis.Nil {
		return 0, nil
	}
	return v, err
}

// devices counts the user's unexpired connections in the room.
func (t Tracker) devices(ctx context.Context, room, user string, now time.Time) (int, error) {
	live, err := t.RDB.ZRangeByScore(ctx, roomKey(room), &redis.ZRangeBy{
		Min: "(" + strconv.FormatInt(now.UnixMilli(), 10), Max: "+inf"}).Result()
	if err != nil {
		return 0, err
	}
	n := 0
	for _, m := range live {
		if strings.HasPrefix(m, user+"|") {
			n++
		}
	}
	return n, nil
}
go
package presence

import (
	"context"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/redis/go-redis/v9"
)

func TestMultiDeviceAndExpiry(t *testing.T) {
	mr := miniredis.RunT(t)
	tr := Tracker{RDB: redis.NewClient(&redis.Options{Addr: mr.Addr()}), TTL: 45 * time.Second}
	ctx := context.Background()
	t0 := time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)

	// Sarah opens the laptop, then the phone: only the first is a transition.
	if on, _ := tr.Heartbeat(ctx, "team.7", "sarah", "laptop", t0); !on {
		t.Fatal("laptop: want cameOnline")
	}
	if on, _ := tr.Heartbeat(ctx, "team.7", "sarah", "phone", t0.Add(time.Second)); on {
		t.Fatal("phone: second device must not announce online again")
	}
	tr.Heartbeat(ctx, "team.7", "omid", "web", t0)

	// Closing the phone does not make her offline (the Ably "Sarah" pitfall).
	if off, _ := tr.Leave(ctx, "team.7", "sarah", "phone", t0.Add(10*time.Second)); off {
		t.Fatal("phone closed but laptop is live: want still online")
	}

	// The laptop keeps heartbeating every 15 s; Omid's tab crashes silently.
	for s := 15; s <= 60; s += 15 {
		tr.Heartbeat(ctx, "team.7", "sarah", "laptop", t0.Add(time.Duration(s)*time.Second))
	}
	users, err := tr.Online(ctx, "team.7", t0.Add(61*time.Second))
	if err != nil || len(users) != 1 || users[0] != "sarah" {
		t.Fatalf("online = %v, %v; want [sarah] (omid expired after TTL)", users, err)
	}
	if ls, _ := tr.LastSeen(ctx, "omid"); ls != t0.Add(61*time.Second).Unix() {
		t.Fatalf("omid last seen = %d", ls)
	}

	if off, _ := tr.Leave(ctx, "team.7", "sarah", "laptop", t0.Add(70*time.Second)); !off {
		t.Fatal("last device closed: want wentOffline")
	}
}

Client reconnect rules: close-code classification (RFC 6455 and Pusher ranges), full jitter, and the server-side drain spread. The test shows 10,000 simultaneous reconnects spread over 80 buckets of 100 ms.

go
// Package reconnect decides whether and when a real-time client reconnects.
// The two rules that prevent reconnection storms: classify the close code,
// and spread retries with exponential backoff plus full jitter.
package reconnect

import (
	"math/rand/v2"
	"time"
)

// Policy is what the client should do after a close.
type Policy int

const (
	Stop      Policy = iota // do not reconnect unchanged (auth failed, policy violation)
	Backoff                 // reconnect after a jittered, growing delay
	Immediate               // reconnect now (server asked us to move, e.g. drain)
)

// Classify maps RFC 6455 close codes and the Pusher protocol ranges to a policy.
// 1006 is never sent on the wire; libraries report it when the TCP connection
// died without a Close frame (network drop, proxy idle timeout, crash).
func Classify(code int) Policy {
	switch {
	case code == 1000: // normal closure: we or the server finished on purpose
		return Stop
	case code == 1008 || code == 1003 || code == 1007 || code == 1009:
		return Stop // policy violation, bad data, message too big: retrying will fail again
	case code == 1001, code == 1006, code == 1011, code == 1012, code == 1013, code == 1014:
		return Backoff // going away, abnormal, server error, restart, try again later
	case code >= 4000 && code <= 4099: // Pusher: "SHOULD NOT be re-established unchanged"
		return Stop
	case code >= 4100 && code <= 4199: // Pusher: back off, at least 1 s
		return Backoff
	case code >= 4200 && code <= 4299: // Pusher: re-establish immediately
		return Immediate
	default:
		return Backoff
	}
}

// FullJitter returns random(0, min(cap, base*2^attempt)), the strategy Marc
// Brooker's AWS analysis found to do the least total work. attempt starts at 0.
func FullJitter(attempt int, base, cap time.Duration, r *rand.Rand) time.Duration {
	d := base
	for i := 0; i < attempt && d < cap; i++ {
		d *= 2
	}
	if d > cap {
		d = cap
	}
	return time.Duration(r.Int64N(int64(d) + 1))
}

// DrainSpread is the server side of the same idea: when a gateway drains N
// connections, it closes them over a window instead of all at once, so the
// fleet sees N/window reconnects per second rather than one spike.
func DrainSpread(n int, window time.Duration) time.Duration {
	if n <= 0 {
		return 0
	}
	return window / time.Duration(n)
}
go
package reconnect

import (
	"math/rand/v2"
	"testing"
	"time"
)

func TestClassify(t *testing.T) {
	cases := map[int]Policy{1000: Stop, 1001: Backoff, 1006: Backoff, 1008: Stop, 1011: Backoff,
		1012: Backoff, 4001: Stop, 4100: Backoff, 4200: Immediate}
	for code, want := range cases {
		if got := Classify(code); got != want {
			t.Errorf("Classify(%d) = %v, want %v", code, got, want)
		}
	}
}

// 10,000 clients dropped at the same instant: without jitter they all come back
// in the same 100 ms bucket; with full jitter (attempt 3: 0..8 s) the busiest
// 100 ms bucket holds a small fraction of them.
func TestFullJitterFlattensTheSpike(t *testing.T) {
	r := rand.New(rand.NewPCG(1, 2))
	buckets := map[int64]int{}
	for i := 0; i < 10000; i++ {
		d := FullJitter(3, time.Second, 30*time.Second, r)
		if d < 0 || d > 8*time.Second {
			t.Fatalf("delay %v out of range", d)
		}
		buckets[d.Milliseconds()/100]++
	}
	peak := 0
	for _, n := range buckets {
		peak = max(peak, n)
	}
	if peak > 300 {
		t.Fatalf("peak bucket %d of 10000; jitter is not spreading reconnects", peak)
	}
	t.Logf("10000 reconnects over %d buckets of 100 ms, peak %d", len(buckets), peak)
}

func TestDrainSpread(t *testing.T) {
	if got := DrainSpread(50000, 5*time.Minute); got != 6*time.Millisecond {
		t.Fatalf("got %v", got)
	}
}

The Go angle ​

Go featureUse in real-time serversNote
net/http + netpollerEach held request or socket parks a goroutine on epoll/kqueueCheap enough for long polling and SSE without an extra library
http.NewResponseController(w).Flush()Push SSE bytes nowReturns an error when the client is gone
context.WithTimeoutLong-poll hold time, write deadlines, ping timeoutsDo not use the request context after a hijack
github.com/coder/websocketAccept, Dial, Read, Write, Ping, Close, CloseStatusContext-aware; methods safe for concurrent use except Read/Reader; origin check on by default
github.com/gorilla/websocketUpgrader, ReadMessage, WriteMessage, WriteControlOne concurrent reader and one writer; CheckOrigin is yours to set
Buffered channelsPer-connection bounded send queueselect with default = non-blocking enqueue
sync.OnceClose a connection exactly once from any goroutineKicks from fan-out, writer and reader
github.com/redis/go-redis/v9PSubscribe, Publish, NewScript(...).Run, ZAdd, ZRangeByScorePubSub.Channel() delivers messages; resubscribes on reconnect
math/rand/v2Full jitterrand.Int64N
runtime.ReadMemStats, runtime.NumGoroutineMeasure per-connection costUsed by the lab

Laravel ​

Before ​

php
<?php

namespace App\Http\Controllers\Before;

use App\Models\Order;
use Illuminate\Http\JsonResponse;

// Short polling, first version: the page calls GET /orders/{order}/status
// every second with setInterval. Every call boots the framework, opens a
// session, runs a query and returns the whole order, even when nothing
// changed. 5,000 open order pages = 5,000 requests per second of no news.
class OrderStatusPollController
{
    public function __invoke(Order $order): JsonResponse
    {
        return response()->json($order->fresh()->load('items', 'shipments'));
    }
}

After ​

Install broadcasting with Reverb. php artisan install:broadcasting --reverb installs Reverb, creates config/broadcasting.php and routes/channels.php, and writes the environment variables. The .env side, with the two host pairs the Reverb docs warn not to confuse:

bash
BROADCAST_CONNECTION=reverb
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
REVERB_SERVER_HOST=0.0.0.0      # where the Reverb process listens
REVERB_SERVER_PORT=8080
REVERB_HOST=ws.example.com       # where Laravel and Echo send traffic (public)
REVERB_PORT=443
REVERB_SCHEME=https
REVERB_SCALING_ENABLED=true      # Redis Pub/Sub between Reverb servers
REVERB_APP_PING_INTERVAL=25      # below the ALB/NGINX idle timeout
REVERB_APP_ACTIVITY_TIMEOUT=30

The event log table (cursor for SSE and long polling) and durable last-seen:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // Append-only event log: the id is the resume cursor for SSE
        // (Last-Event-ID), long polling (?cursor=) and WebSocket (?since=).
        Schema::create('realtime_events', function (Blueprint $table) {
            $table->id();
            $table->string('channel', 191);
            $table->string('event', 100);
            $table->json('payload');
            $table->timestamp('created_at')->useCurrent();

            $table->index(['channel', 'id']);
            $table->index('created_at'); // pruning job deletes rows older than the resume window
        });

        // Durable last-seen; live presence itself stays in Redis with TTLs.
        Schema::create('user_presence', function (Blueprint $table) {
            $table->foreignId('user_id')->primary()->constrained()->cascadeOnDelete();
            $table->timestamp('last_seen_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('user_presence');
        Schema::dropIfExists('realtime_events');
    }
};

Write the state change and the event row in one transaction, broadcast after commit:

php
<?php

namespace App\Actions;

use App\Events\OrderStatusUpdated;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

// The state change, the durable event row and the broadcast belong together:
// the row is written in the same transaction (so SSE/long-poll resume can
// replay it), and the broadcast is dispatched only after commit.
class ShipOrder
{
    public function __invoke(Order $order): void
    {
        DB::transaction(function () use ($order) {
            $order->update(['status' => 'shipped']);

            $seq = DB::table('realtime_events')->insertGetId([
                'channel' => 'orders.'.$order->id,
                'event' => 'order.status',
                'payload' => json_encode(['order_id' => $order->id, 'status' => 'shipped']),
            ]);

            OrderStatusUpdated::dispatch($order->id, 'shipped', $seq);
        });
    }
}
php
<?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;

// Pushed to the customer's private channel through Reverb (Pusher protocol).
// ShouldDispatchAfterCommit: never broadcast a status the database rolled back.
class OrderStatusUpdated implements ShouldBroadcast, ShouldDispatchAfterCommit
{
    use Dispatchable, InteractsWithSockets;

    public function __construct(
        public int $orderId,
        public string $status,
        public int $seq, // realtime_events.id: lets the client detect gaps and dedup
    ) {}

    public function broadcastOn(): array
    {
        return [new PrivateChannel('orders.'.$this->orderId)];
    }

    public function broadcastAs(): string
    {
        return 'order.status';
    }

    public function broadcastWith(): array
    {
        // Small payload: an id, a status and a cursor, not the whole order.
        return ['order_id' => $this->orderId, 'status' => $this->status, 'seq' => $this->seq];
    }

    public function broadcastQueue(): string
    {
        return 'broadcasts'; // keep fan-out jobs away from slow business jobs
    }
}

A presence-channel chat message sent without the queue:

php
<?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;

// Chat message on a presence channel. ShouldBroadcastNow skips the queue:
// chat latency matters more than absorbing a Reverb hiccup in a worker.
class RoomMessagePosted implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets;

    public function __construct(
        public int $roomId,
        public string $clientMessageId, // generated by the sender; receivers dedup on it
        public int $userId,
        public string $text,
    ) {}

    public function broadcastOn(): array
    {
        return [new PresenceChannel('chat.'.$this->roomId)];
    }

    public function broadcastAs(): string
    {
        return 'message.posted';
    }
}

Channel authorization for the private and presence channels:

php
<?php

use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Broadcast;

// Private channel: Echo calls POST /broadcasting/auth with the socket_id and
// channel name; returning true lets Laravel sign the subscription (HMAC with
// REVERB_APP_SECRET), which Reverb verifies. No signature, no subscription.
Broadcast::channel('orders.{order}', function (User $user, Order $order): bool {
    return $user->id === $order->user_id;
});

// Presence channel: return the member info (or null to refuse). Reverb keeps
// the member list per channel and sends member_added / member_removed.
Broadcast::channel('chat.{roomId}', function (User $user, int $roomId): ?array {
    if (! $user->rooms()->whereKey($roomId)->exists()) {
        return null;
    }

    return ['id' => $user->id, 'name' => $user->name];
});

The Echo client. Configured by the installer; shown here because the behaviour matters: private() triggers the /broadcasting/auth call, join() gives the presence callbacks, whisper() sends a client event that never touches Laravel (on the same channel object, here the presence channel), and the event name starts with a dot because broadcastAs() was customised.

js
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;

window.Echo = new Echo({
  broadcaster: 'reverb',
  key: import.meta.env.VITE_REVERB_APP_KEY,
  wsHost: import.meta.env.VITE_REVERB_HOST,
  wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
  wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
  forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
  enabledTransports: ['ws', 'wss'],
});

let lastSeq = Number(sessionStorage.getItem('orders.42.seq') ?? 0);
Echo.private('orders.42').listen('.order.status', (e) => {
  if (e.seq <= lastSeq) return;                 // duplicate after a reconnect
  if (e.seq > lastSeq + 1) reloadOrderFromApi();  // gap: Pusher protocol has no history
  lastSeq = e.seq;
  sessionStorage.setItem('orders.42.seq', String(lastSeq));
  renderStatus(e.status);
});

const seen = new Set();
const room = Echo.join('chat.9')
  .here((users) => renderMembers(users))
  .joining((user) => addMember(user))
  .leaving((user) => removeMember(user))
  .listen('.message.posted', (e) => {
    if (seen.has(e.clientMessageId)) return;      // at-least-once on the sender side
    seen.add(e.clientMessageId);
    appendMessage(e);
  });

room.whisper('typing', { name: currentUser.name });   // client event on the same presence channel
room.listenForWhisper('typing', (e) => showTyping(e.name));

SSE with real resume. response()->eventStream() is the short path for one-shot streams (AI tokens); it writes event: and data: but no id: lines in 13.x, so for resumable streams write the frames with response()->stream():

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\StreamedResponse;

// SSE with resume. response()->eventStream() writes "event:" and "data:" but
// no "id:" lines (see Illuminate\Routing\ResponseFactory::eventStream in 13.x),
// so EventSource would never send Last-Event-ID. We write the frames ourselves.
//
// Each open stream holds one PHP-FPM worker (or one Octane worker) for its
// whole life: cap the stream length and size the pool, or use Reverb instead.
class OrderEventStreamController
{
    public function __invoke(Request $request, Order $order): StreamedResponse
    {
        Gate::authorize('view', $order);

        $cursor = (int) ($request->header('Last-Event-ID') ?? $request->query('lastEventId', 0));
        $channel = 'orders.'.$order->id;
        $request->session()->save(); // release the session lock before streaming

        return response()->stream(function () use ($cursor, $channel): void {
            echo "retry: 5000\n\n";
            $deadline = time() + 55;        // below NGINX proxy_read_timeout and ALB idle timeout
            $lastWrite = time();

            while (time() < $deadline && ! connection_aborted()) {
                $rows = DB::table('realtime_events')
                    ->where('channel', $channel)
                    ->where('id', '>', $cursor)
                    ->orderBy('id')
                    ->limit(100)
                    ->get(['id', 'event', 'payload']);

                foreach ($rows as $row) {
                    echo "id: {$row->id}\n";
                    echo "event: {$row->event}\n";
                    echo "data: {$row->payload}\n\n";
                    $cursor = $row->id;
                    $lastWrite = time();
                }

                if (time() - $lastWrite >= 15) {
                    echo ": ping\n\n";          // comment line keeps proxies from timing out
                    $lastWrite = time();
                }

                if (ob_get_level() > 0) {
                    ob_flush();
                }
                flush();
                sleep(1); // still a poll, but server-side and one query per stream
            }
            // Returning ends the response; EventSource reconnects after "retry"
            // with Last-Event-ID set to the last id it saw.
        }, 200, [
            'Content-Type' => 'text/event-stream',
            'Cache-Control' => 'no-cache',
            'X-Accel-Buffering' => 'no',
        ]);
    }
}

The one-shot form, straight from the Laravel 13 responses docs:

php
use Illuminate\Http\StreamedEvent;

Route::get('/chat', function () {
    return response()->eventStream(function () {
        foreach (Assistant::stream(request('prompt')) as $token) {
            yield new StreamedEvent(event: 'update', data: $token);
        }
    });
});

Tickets for a non-Pusher gateway (the Go hub above), stored where the gateway can GETDEL them:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

// Ticket auth for a non-Pusher gateway (for example the Go hub on this page).
// The browser calls this route with its session cookie and CSRF token, then
// opens wss://rt.example.com/ws?ticket=... . The gateway redeems the ticket
// with GETDEL, so it works once, for 30 seconds.
class RealtimeTicketController
{
    public function __invoke(Request $request): JsonResponse
    {
        $ticket = Str::random(32);

        Redis::set('ticket:'.$ticket, (string) $request->user()->id, 'EX', 30, 'NX');

        return response()->json(['ticket' => $ticket, 'expires_in' => 30]);
    }
}

Presence with heartbeats and TTL, the same model as the Go package (mind Laravel's Redis key prefix option if Go and PHP share keys):

php
<?php

namespace App\Support;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

// Same model as the Go presence package: a sorted set per room, members
// "user|connection", score = expiry in milliseconds. Heartbeats refresh the
// score; crashed tabs expire; a user is online while any device is live.
class Presence
{
    public function __construct(private int $ttlSeconds = 45) {}

    /** Returns true when this heartbeat brought the user online. */
    public function heartbeat(string $room, int $userId, string $connectionId): bool
    {
        $now = (int) (microtime(true) * 1000);
        $key = "presence:{$room}";
        $wasOnline = $this->devices($key, $userId, $now) > 0;

        Redis::zadd($key, ["{$userId}|{$connectionId}" => $now + $this->ttlSeconds * 1000]);

        return ! $wasOnline;
    }

    /** Returns true when the user's last device left; records last seen. */
    public function leave(string $room, int $userId, string $connectionId): bool
    {
        $now = (int) (microtime(true) * 1000);
        $key = "presence:{$room}";
        Redis::zrem($key, "{$userId}|{$connectionId}");

        if ($this->devices($key, $userId, $now) > 0) {
            return false;
        }

        DB::table('user_presence')->upsert(
            [['user_id' => $userId, 'last_seen_at' => now()]],
            ['user_id'],
            ['last_seen_at'],
        );

        return true;
    }

    /** @return list<int> distinct online user ids */
    public function online(string $room): array
    {
        $now = (int) (microtime(true) * 1000);
        $key = "presence:{$room}";
        Redis::zremrangebyscore($key, '-inf', (string) $now);

        $users = [];
        foreach (Redis::zrangebyscore($key, '('.$now, '+inf') as $member) {
            $users[(int) explode('|', $member, 2)[0]] = true;
        }

        return array_keys($users);
    }

    private function devices(string $key, int $userId, int $now): int
    {
        $prefix = "{$userId}|";

        return count(array_filter(
            Redis::zrangebyscore($key, '('.$now, '+inf'),
            fn (string $m): bool => str_starts_with($m, $prefix),
        ));
    }
}

NGINX in front of Reverb (from the Reverb docs, with the idle timeout made explicit). Reverb listens for WebSocket connections at /app and API requests at /apps:

nginx
location / {
    proxy_http_version 1.1;
    proxy_set_header Host $http_host;
    proxy_set_header Scheme $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_read_timeout 60s;          # Reverb pings every 25 s, so 60 s is safe
    proxy_pass http://0.0.0.0:8080;
}

The Laravel angle ​

Laravel 13 featureUseNote
php artisan install:broadcasting --reverbInstalls Reverb, Echo, routes/channels.phpAlso --pusher, --ably, --mercure
ShouldBroadcast / ShouldBroadcastNowQueued vs immediate broadcastQueued is the default; broadcastQueue() picks the queue
ShouldDispatchAfterCommitBroadcast only after the transaction commitsOtherwise a queue worker can broadcast rows that do not exist yet
PrivateChannel, PresenceChannel, EncryptedPrivateChannelChannel typesEncrypted channels: Pusher Channels or Mercure only
broadcastAs(), broadcastWith(), broadcastWhen()Event name, payload, conditionListen with a leading . for custom names
Broadcast::channel()Authorization callbacksPresence returns member data or null
broadcast(...)->toOthers(), InteractsWithSocketsSkip the sender's socketUses the X-Socket-ID header Echo adds
Broadcast::on(...)->send()Anonymous events without a classprivate(), presence(), sendNow()
Echo whisper() / listenForWhisper()Client events (typing)Reverb accept_client_events_from = members by default
response()->eventStream(), StreamedEventSSE for one-shot streamsEnds with </stream>; no id:
response()->stream()Hand-written SSE with id: and resumeSend X-Accel-Buffering: no
php artisan reverb:start, reverb:restartRun and gracefully restartRestart terminates connections gracefully
Reverb + Pulse recordersReverbConnections, ReverbMessagesRun pulse:check on one server
Redis facadeTickets, presence sorted setsAny command passes through

Solving the classic problems ​

Messages lost during reconnect ​

SolutionHowAdvantageCost / limitation
Sequence number + history + resumePublish assigns seq; client sends last seq on reconnectLossless within the windowHistory storage; gap handling
Durable event tablerealtime_events row in the same transaction as the changeSurvives Redis loss; simple SQL resumeDatabase load; prune old rows
Reload on reconnectFetch full state over HTTP after every reconnectAlways correctThundering herd after a deploy
Managed recovery (Centrifugo, Ably, Socket.IO CSR)Built inNo codeProduct lock-in, window limits

Resume from the durable log (PostgreSQL syntax; MySQL differs only in the interval literal):

sql
-- the event row is written in the same transaction as the state change
INSERT INTO realtime_events (channel, event, payload)
VALUES ('orders.42', 'order.status', '{"order_id":42,"status":"shipped"}');

-- resume: everything after the client's cursor, in order
SELECT id, event, payload
FROM realtime_events
WHERE channel = 'orders.42' AND id > 41
ORDER BY id
LIMIT 100;

-- gap check: is the cursor older than what we keep?
SELECT MIN(id) AS oldest FROM realtime_events WHERE channel = 'orders.42';

-- pruning job: keep 24 hours (MySQL: NOW() - INTERVAL 24 HOUR)
DELETE FROM realtime_events WHERE created_at < now() - interval '24 hours';

Duplicate messages after a retry ​

SolutionHowAdvantageCost / limitation
Client-generated message idSender creates id, reuses it on retry; receivers keep a seen-setWorks across any transportSeen-set per client (bounded, recent)
Server dedup on publishSET dedup:<id> 1 NX EX 300 before publishingOne copy in historyExtra Redis call; window
Seq-based dropIgnore seq <= last_seqFree once seq existsOnly dedups the replay overlap

The server-side variant is Idempotent Consumers & the Inbox applied to a socket.

Every connection drops after 60 seconds ​

SolutionHowAdvantageCost / limitation
Heartbeat below the idle timeoutPing every 25 sWorks through any LBSmall constant traffic
Raise the idle timeoutALB idle_timeout.timeout_seconds, NGINX proxy_read_timeoutFewer packetsDead connections linger longer; you do not control mobile NATs
SSE comments: ping every 15 sSpec-sanctionedSSE only

Reconnection storm after a deploy ​

SolutionHowAdvantageCost / limitation
Drain over a window503 to new connections, 1001 to old ones, spreadFlat reconnect rateDeploys take minutes
Full jitter on the clientrandom(0, min(cap, base * 2^n))Desynchronises clientsSome users wait longer
Resume from fast historyRedis/Centrifugo history, not the databaseReconnect cost stays smallHistory sizing
Edge rate limit on handshakesNGINX limit_req on the upgrade path, Cloudflare rate limitingProtects auth and originSome clients get 429 and retry later

One slow client, or memory that only grows ​

SolutionHowAdvantageCost / limitation
Bounded queue + disconnectNon-blocking enqueue; close 1008 when fullMemory is cappedSlow clients reconnect often
Write deadlineContext timeout per writeWriter cannot hang foreverNeeds a separate writer
CoalescingKeep only the latest value per keyPerfect for prices, locationsNot for chat

Presence flapping and ghost users ​

SolutionHowAdvantageCost / limitation
Per-connection entries with TTL`ZADD presence:room expiry userconn`Crash-safe, multi-device
Debounced offlineEmit offline only after N s without any deviceNo flicker on reconnectsDelay in showing offline
Visible-set fan-outSend presence only for users on screen (Slack's approach)Avoids N^2 fan-outSubscription bookkeeping

Messages only reach users on the same server ​

SolutionHowAdvantageCost / limitation
Redis Pub/Sub between gatewaysPSUBSCRIBE rt:room:*; Reverb REVERB_SCALING_ENABLEDOne settingAt-most-once; one Redis
Sharded routingRooms owned by nodes on a consistent hash ring (Slack)Scales past one RedisYou build membership and rebalancing
Managed fan-outPusher, Ably, API Gateway @connectionsNo serversCost per message, vendor limits

SSE stops working after six tabs ​

SolutionHowAdvantageCost / limitation
HTTP/2 or HTTP/3 to the browserTLS + h2 at the edge100 streams by defaultEdge must not downgrade to HTTP/1.1
One stream per browserSharedWorker or BroadcastChannel leader tabOne connection for all tabsMore client code
Separate hostnameevents.example.comSeparate 6-connection poolStill limited; CORS

Cross-site WebSocket hijacking ​

SolutionHowAdvantageCost / limitation
Origin allowlistcoder OriginPatterns, Reverb allowed_origins, gorilla CheckOriginStops browser-based CSWSHNon-browser clients can fake Origin, so also authenticate
Single-use ticketsAuthenticated POST, then ?ticket=No cookie on the socketExtra request; ticket store
SameSite=Lax/Strict cookiesSession cookie attributesCookie not sent cross-siteDoes not cover same-site subdomains

Choosing ​

Which technique for which feature ​

FeatureRecommendedExtra techniqueReason
Notifications, order status, unread countsSSE (or Reverb private channel on Laravel)id: + durable log; HTTP/2One direction, must not lose events
Live dashboard, metrics wallSSE, or short polling every 10-30 s behind a CDNCoalesce to latest valueFreshness of seconds is enough
Chat, support widgetWebSocket (Reverb, Socket.IO, Centrifugo, Go hub)Seq + history + client ids; presenceBoth directions, typing, presence
Collaborative editing (docs, whiteboards)WebSocket per document (Durable Objects, Phoenix, Go)CRDT or OT ops, causal ordering (CRDTs)Many small ops both ways, ordering is semantic
Live location (drivers, couriers)WebSocket or MQTT over WebSocketCoalesce, send deltas, geo-sharded fan-out (Geospatial Indexing)High frequency, only the latest point matters
Trading, auctions, bettingWebSocket with binary framesPer-symbol sequence numbers, snapshot + deltas, gap -> resnapshotOrdering and gap detection are correctness
Multiplayer games, cloud gaming inputWebSocket now; WebTransport datagrams or WebRTC where supportedClient predictionOld state is worthless; avoid head-of-line blocking
AI token streamingSSE (eventStream)End marker, cancel on disconnectOne response, one direction
Payment / KYC "wait for result" pageLong polling or short pollingIdempotent status endpointOne event, short wait, no infra
IoT telemetry and commandsMQTT (over WebSocket for browsers)Retained messages, QoS levelsPurpose-built pub/sub protocol

Which product ​

SituationChooseAvoid
Laravel app, private/presence channels, want to self-hostReverb + Echo, Redis scalingPHP-FPM SSE for thousands of users
Laravel app, do not want to run socketsPusher Channels or Ably via install:broadcastingBuilding your own gateway
Need history, recovery, presence in any languageCentrifugo (self-host) or Ably (managed)Raw Redis Pub/Sub alone
Node.js team, rooms, fallbacksSocket.IO + Redis adapterMixing plain WebSocket clients with Socket.IO
Go backend, custom protocol, very many connectionscoder/websocket gateway + Redis/Kafka/NATSOne goroutine blocking on fan-out
Serverless on AWSAPI Gateway WebSocket + DynamoDB connection tableLong-lived per-connection state in Lambda
One room = one stateful unit (doc, game)Cloudflare Durable Objects (hibernation)Global pub/sub for every keystroke
Elixir shop or need cluster presencePhoenix Channels + PresenceReinventing CRDT presence

In architecture: from a single process to a distributed system ​

The feature is the same at every size: "when an order changes or a message is posted, the right people see it within a second, and nobody misses it after a reconnect". What changes is where connections live and how the message travels.

Monolith: one process, one database ​

How it shows up: a single Go binary or one Laravel app plus one Reverb process. Connections and rooms are in one process, so fan-out is a loop over a map.

Simplest correct usage: even here, write the event row in the same transaction as the change and give it an id; broadcast after commit; heartbeat below the proxy timeout; reconnect with jitter.

Example (simple): a shop with one Laravel app, NGINX and one php artisan reverb:start under Supervisor; order status on a private channel; Echo reloads the order on a sequence gap.

Example (production-shaped): the same app with Horizon processing the broadcasts queue, Reverb's Pulse recorders on the dashboard, ext-uv installed because connections passed 1,000, ulimit -n and Supervisor minfds raised to 10,000.

Modular monolith: boundaries without the network ​

How it shows up: modules (Orders, Chat, Notifications) publish domain events in-process; one Realtime module owns channel naming, authorization and the event log, and is the only thing that knows Reverb or the hub exists.

Example: the Orders module raises OrderShipped; the Realtime module's listener writes realtime_events and dispatches OrderStatusUpdated. Chat never broadcasts directly; it calls Realtime::publish('chat.9', ...). Channel names and payload schemas are a contract owned by the Realtime module.

Microservices: every arrow is a decision ​

How it shows up: a dedicated connection gateway service (Go hub, Centrifugo, Reverb, or a managed service) that holds sockets and has no business logic. Domain services publish to it through a broker or its HTTP API; the gateway authenticates with tickets or tokens issued by the identity service.

Multi-service example:

text
     Service                 Action
1    Orders                  UPDATE orders; INSERT outbox row (same transaction)
2    Outbox relay            publishes OrderShipped to Kafka topic orders (key order_id)
3    Notifications           consumes; decides who must know; publishes to gateway: room user.7, id "order-42-shipped"
4    Gateway (Redis bus)     Lua: seq=88 for user.7; PUBLISH; history
5    Gateway nodes           deliver to user 7's laptop and phone; offline? -> mobile push (APNs/FCM) instead
6    Client                  seq 88 > last 87: show; id seen before after a retry: drop

What survives the boundary is the id and the sequence number; what does not is any transaction: the outbox (Transactional Outbox) makes the publish reliable, the gateway's history makes the last hop recoverable, and idempotency at both ends absorbs duplicates.

Distributed data: replicas, caches, regions ​

How it shows up: gateways in several regions (Slack deploys Gateway Servers "across multiple geographical regions"), a fan-out layer that crosses regions, presence that is eventually consistent, and read replicas that lag behind the event that triggered the push.

Where it breaks: a client receives "order shipped" over the socket, then fetches /orders/42 from a lagging replica and sees "paid": route that read to the primary or include the new state in the event (read-your-writes; see Consistency Models). Presence across regions converges, it is never instantaneous; Phoenix Presence uses a CRDT so every node can answer locally. A Redis failover loses in-flight Pub/Sub messages; clients detect the gap by sequence and resume.

Scaling path: 1x, 10x, 100x ​

LoadShapeWhat changes
1x (1,000 concurrent)One app + one Reverb/Go process, or SSE from GoHeartbeats, resume, after-commit broadcast
10x (10,000-100,000)2-4 gateways behind ALB/NGINX, one Redis for fan-out, presence and historyDrain on deploy, jitter, fd limits, ext-uv for Reverb, metrics on handshake rate
100x (1M+)Dedicated gateway fleet, sharded fan-out (Redis Cluster sharded pub/sub, Kafka, or channel servers on a hash ring), regional edgesInterest-based subscriptions, presence only for visible users, connection rate limits, history outside the primary DB, capacity tests per release

Lab: connection cost, resume and jitter, with numbers ​

Everything below runs in one process on loopback. Steps 1, 2 and 5 were run while writing this page (Apple M4 Pro, Go 1.27.4); steps 3, 4 and 6 are written as commands with expected output, not run.

Step 1: the tests.

bash
cd docs/snippets/system-design/realtime-polling-sse-websockets/go
gofmt -l . && go vet ./... && go test -race ./...
# ok  academy/realtime-polling-sse-websockets/fanout
# ok  academy/realtime-polling-sse-websockets/hub
# ok  academy/realtime-polling-sse-websockets/longpoll
# ok  academy/realtime-polling-sse-websockets/presence
# ok  academy/realtime-polling-sse-websockets/reconnect
# ok  academy/realtime-polling-sse-websockets/sse
# ok  academy/realtime-polling-sse-websockets/stream
# ok  academy/realtime-polling-sse-websockets/ticket

Step 2: what an idle connection costs. connlab starts the hub, opens N client connections on loopback, measures heap plus stacks and goroutines before and after, then publishes one message to the room and waits until every client has read it.

go
// Command connlab measures what an idle WebSocket connection costs in this Go
// gateway and how long one room-wide fan-out takes. Everything runs in one
// process on loopback: the server side and N client connections.
//
//	go run ./lab/connlab -n 2000
package main

import (
	"context"
	"flag"
	"fmt"
	"net/http/httptest"
	"runtime"
	"strings"
	"sync"
	"time"

	"github.com/coder/websocket"

	"academy/realtime-polling-sse-websockets/hub"
	"academy/realtime-polling-sse-websockets/ticket"
)

func heapMB() float64 {
	runtime.GC()
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	return float64(m.HeapInuse+m.StackInuse) / (1 << 20)
}

func main() {
	n := flag.Int("n", 2000, "connections (each uses 2 file descriptors here; raise ulimit -n)")
	queue := flag.Int("queue", 64, "per-connection send queue length")
	flag.Parse()

	h := hub.New(*queue)
	bus := hub.NewLocalBus(100)
	tickets := ticket.NewStore(time.Minute)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go bus.Subscribe(ctx, h.Deliver)
	srv := httptest.NewServer(&hub.Server{Hub: h, Bus: bus, Tickets: tickets,
		PingEvery: time.Minute, Write: 5 * time.Second, ReadLimit: 4096})
	defer srv.Close()
	base := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws?room=lobby&ticket="

	before, g0 := heapMB(), runtime.NumGoroutine()
	conns := make([]*websocket.Conn, 0, *n)
	start := time.Now()
	for i := 0; i < *n; i++ {
		c, _, err := websocket.Dial(ctx, base+tickets.Issue(fmt.Sprint("u", i)),
			&websocket.DialOptions{Subprotocols: []string{hub.Subprotocol}})
		if err != nil {
			fmt.Printf("dial %d failed: %v (raise ulimit -n)\n", i, err)
			break
		}
		conns = append(conns, c)
	}
	for h.Len() < len(conns) {
		time.Sleep(10 * time.Millisecond)
	}
	dialTime := time.Since(start)
	after, g1 := heapMB(), runtime.NumGoroutine()
	per := (after - before) * 1024 / float64(len(conns))
	fmt.Printf("connections: %d  dial+upgrade: %v (%.0f/s)\n", len(conns), dialTime.Round(time.Millisecond), float64(len(conns))/dialTime.Seconds())
	fmt.Printf("heap+stacks: %.1f MB -> %.1f MB  (~%.1f KB per connection, both ends)\n", before, after, per)
	fmt.Printf("goroutines: %d -> %d  (%.1f per connection, both ends)\n", g0, g1, float64(g1-g0)/float64(len(conns)))

	// One message to the whole room: time until every client has read it.
	var wg sync.WaitGroup
	t0 := time.Now()
	for _, c := range conns {
		wg.Add(1)
		go func(c *websocket.Conn) {
			defer wg.Done()
			rctx, rcancel := context.WithTimeout(ctx, 10*time.Second)
			defer rcancel()
			_, _, _ = c.Read(rctx)
		}(c)
	}
	bus.Publish(ctx, "lobby", "m-1", []byte(`{"text":"hello room"}`))
	wg.Wait()
	fmt.Printf("fan-out of 1 message to %d members: %v\n", len(conns), time.Since(t0).Round(time.Microsecond))

	for _, c := range conns {
		c.CloseNow()
	}
}
bash
ulimit -n 30000
go run ./lab/connlab -n 10000
# measured, not estimated (both ends of every connection live in this process):
# connections: 10000  dial+upgrade: 1.14s (8769/s)
# heap+stacks: 1.2 MB -> 493.5 MB  (~50.4 KB per connection, both ends)
# goroutines: 3 -> 20003  (2.0 per connection, both ends)
# fan-out of 1 message to 10000 members: 125.374ms

Read it carefully: the 2 goroutines are the server's reader and writer (the coder client starts none); about 50 KB covers both the server and client side of each connection plus httptest overhead, so a gateway alone will be lower; the fan-out time includes 10,000 reader goroutines being scheduled. With -n 4000 the same run gave about 50.9 KB per connection and 17 ms fan-out. Your numbers will differ; measure your own before sizing a fleet.

Step 3: SSE resume with curl (expected, not run). Run a tiny main that mounts sse.Handler on :8081 and appends an event every second, then:

bash
curl -N -H 'Last-Event-ID: 3' 'http://127.0.0.1:8081/events?topic=orders.42'
# expected, not run:
# retry: 3000
#
# id: 4
# event: orders.42
# data: tick 4
#
# id: 5
# ...
# (Ctrl-C, run again with Last-Event-ID: 5 and the stream continues at 6)

Step 4: the 60-second cut (expected, not run). Put NGINX in front with proxy_read_timeout 60s and the Upgrade headers, connect with websocat ws://127.0.0.1:8080/ws?..., and set the hub's PingEvery to 90 s:

text
expected, not run:
1    t=0     101 Switching Protocols
2    t=60    NGINX closes the upstream; websocat prints nothing, the client sees 1006 on its next write
3    set PingEvery=25s: the connection stays up for hours; NGINX sees a ping every 25 s

Step 5: jitter flattens the reconnect spike (run).

bash
go test -run TestFullJitterFlattensTheSpike -v ./reconnect
# === RUN   TestFullJitterFlattensTheSpike
#     reconnect_test.go:39: 10000 reconnects over 80 buckets of 100 ms, peak 156
# --- PASS

Without jitter all 10,000 land in one 100 ms bucket; with full jitter at attempt 3 (0 to 8 s) they spread over 80 buckets and the busiest held 156 of 10,000, about 1.6% (the test fails if any bucket exceeds 300).

Step 6: presence in Redis (expected, not run). With a local Redis and redis-cli:

bash
redis-cli ZADD presence:team.7 $(( ($(date +%s)+45)*1000 )) "sarah|laptop"
redis-cli ZADD presence:team.7 $(( ($(date +%s)+45)*1000 )) "sarah|phone"
redis-cli ZRANGEBYSCORE presence:team.7 "($(date +%s)000" +inf
# expected, not run:
# 1) "sarah|laptop"
# 2) "sarah|phone"
# wait 46 s, run the ZRANGEBYSCORE again: (empty array); prune with ZREMRANGEBYSCORE ... -inf <now>

Common misconceptions ​

BeliefReality
WebSocket is always the best real-time transportMost features are server-to-client; SSE gives resume and plain HTTP for free
TCP means WebSocket messages cannot be lostAnything in flight when the connection dies is lost; only seq + resume makes it lossless
Redis Pub/Sub delivers reliablyIt is at-most-once; "the message is forever lost" if a subscriber is disconnected
1006 means the server sent an error1006 is never sent; it means the connection ended without a Close frame
Sticky sessions are needed for WebSocketsA WebSocket stays on one server anyway; stickiness matters for multi-request transports (long polling)
A port limits a server to 65,535 connectionsConnections are four-tuples; file descriptors and memory are the limit (ephemeral ports matter on proxy-to-backend hops)
TCP keepalive replaces heartbeatsDefaults start after hours; proxies cut idle flows after 60 s
Same-origin policy protects WebSocketsBrowsers open sockets cross-origin and send cookies; you must check Origin
Exponential backoff alone prevents stormsWithout jitter all clients retry at the same instants
Presence = socket openSockets die silently and users have several devices; use per-connection TTLs
Compression is freepermessage-deflate keeps per-connection zlib state; small messages gain little
Laravel's eventStream() supports Last-Event-IDIn 13.x it writes no id: lines; resume needs a hand-written stream
Any WebSocket client can talk to Reverb or Socket.IOReverb speaks the Pusher protocol; Socket.IO has its own protocol
SSE cannot scaleIt scales like any long-lived HTTP response; the limits are the browser's HTTP/1.1 pool and your runtime model

Cheat sheet ​

TopicRemember
Pick the transportOne-way: SSE; both ways: WebSocket; rare events or hostile networks: polling; game datagrams: WebTransport/WebRTC
Long pollingHold under 30 s, cursor in every request, 204 on timeout, no-store
SSEid: + Last-Event-ID, retry:, : ping every 15 s, no proxy buffering, HTTP/2 against the 6-connection limit
WebSocket handshakeGET + Upgrade + Sec-WebSocket-Key -> 101 + Sec-WebSocket-Accept; check Origin first
FramesOpcodes 0/1/2 data, 8/9/A control; client frames masked; control <= 125 bytes
HeartbeatInterval below half the smallest idle timeout (25 s vs 60 s); missed pong -> close
Close codes1000 done, 1001 drain, 1006 dropped (never sent), 1008 auth, 1009 size, 1011 bug
BackpressureBounded queue per connection, non-blocking enqueue, disconnect slow consumers
DeliverySeq per channel, history window, resume from cursor, client ids for dedup = at-least-once
Fan-outRedis Pub/Sub between gateways first; sharded pub/sub or hash-ring channel servers later
AuthTicket or first-message token, Origin allowlist, per-channel auth, close on logout
PresenceConnections with TTL, users derived, transitions only, last seen on offline, visible-set fan-out
Draining503 to new, 1001 spread over minutes, ALB deregistration delay >= window
ReconnectFull jitter random(0, min(cap, base*2^n)), classify close codes, resume not reload
CapacityMeasure per-connection memory; fds; handshake rate; history = rate x (drain + jitter)

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A dashboard shows warehouse stock that changes a few times a minute; 30,000 staff keep it open. Which transport, and why not WebSocket? Must-know ​

Answer

Answer: SSE over HTTP/2 (or short polling every 10 to 30 s behind a CDN). Traffic is one-way, SSE gives automatic reconnection and Last-Event-ID resume, it passes proxies as plain HTTP, and HTTP/2 lifts the 6-connection limit. WebSocket adds a protocol, heartbeats and stateful auth for no benefit. See SSE and Choosing.

2 — Every WebSocket behind your AWS ALB dies after exactly one minute of silence. What is happening and what are two fixes? Must-know ​

Answer

Answer: The ALB's idle_timeout.timeout_seconds defaults to 60. Send a ping or application heartbeat every 25 s (preferred, also detects dead peers), or raise the idle timeout above the heartbeat interval. NGINX's proxy_read_timeout (60 s) causes the same symptom. See Heartbeats.

3 — Your client library reports close code 1006. Should the client reconnect, and did the server send 1006? Important ​

Answer

Answer: The server did not send it: RFC 6455 says 1006 "MUST NOT be set as a status code in a Close control frame". It means the connection ended without a Close frame (network drop, idle timeout, crash). Reconnect with exponential backoff and full jitter, then resume from the last sequence number. See Close codes.

4 — Alice is on gateway 1 and Bob on gateway 2. Alice's message never reaches Bob. What is missing, and what does Reverb need for it? Important ​

Answer

Answer: Cross-node fan-out: each gateway only knows its own connections. Publish through a shared bus (Redis Pub/Sub, Kafka, NATS) that every gateway subscribes to. Reverb: REVERB_SCALING_ENABLED=true and a central Redis. See Fan-out.

5 — Redis Pub/Sub is at-most-once. How can a chat built on it still be lossless for a client that reconnects? Important ​

Answer

Answer: Pub/Sub is only the live path. Assign a per-room sequence number at publish time and store the message in a bounded history (sorted set, stream, or table) atomically with the publish; the client tracks its last seq and resumes with ?since= after reconnecting; a gap older than the history triggers a full reload. See Ordering.

6 — A user has the app open on a laptop and a phone. The phone loses signal. What should presence show, and how does the design guarantee it? Important ​

Answer

Answer: Still online. Presence stores connections (user|connection) with TTLs; the phone's entry expires, the laptop's keeps being refreshed by heartbeats; the user is online while any connection is live, and an offline transition is emitted only when the last one goes. See Presence.

7 — You deploy a gateway that holds 120,000 connections. Describe a deploy that does not cause a reconnection storm. Important ​

Answer

Answer: Mark it draining (readiness off, LB deregisters, 503 + Retry-After to new handshakes), close existing connections with 1001 spread over a window (for example 120,000 over 400 s = 300/s), keep the ALB deregistration delay and Kubernetes grace period at least that long, have clients reconnect with full jitter and resume from fast history instead of reloading from the database. See Storms.

8 — Why is checking the Origin header required for a cookie-authenticated WebSocket, and why is it not enough on its own? Must-know ​

Answer

Answer: Browsers open WebSockets to any host and attach its cookies (CSWSH); only the Origin header, which page script cannot forge, tells you which site initiated it. Non-browser clients can send any Origin, so the connection also needs real authentication (ticket, token) and per-channel authorization. See Auth.

9 — One customer on bad hotel Wi-Fi makes the whole trading room lag. What design flaw does that reveal, and what is the fix? Important ​

Answer

Answer: The fan-out path blocks on a slow connection (or buffers without bound). Give each connection a bounded queue drained by its own writer with a write deadline, enqueue without blocking, disconnect (1008) or coalesce when full, and let the client resume from its cursor. See Backpressure.

10 — Your Laravel SSE endpoint built with response()->eventStream() never resumes after a reconnect. Why, and how do you fix it? Good to know ​

Answer

Answer: In Laravel 13, eventStream() writes event: and data: lines but no id: lines, so EventSource never has a last event ID to send. Write the stream with response()->stream(), emit id: <realtime_events.id>, read Last-Event-ID, and replay rows after it. Also remember each open stream holds a PHP-FPM worker. See Laravel.

11 — A 1,000-member presence channel feels slow every morning at 9:00. Estimate the message count when everyone joins and name a fix. Important ​

Answer

Answer: Each join notifies everyone already present: about 1,000 x 999 / 2 = ~500,000 member-added messages (close to a million with leaves and rejoins). Show counts instead of member lists for large rooms, send presence only for users visible on screen (Slack's approach), and batch or debounce presence changes. See Mechanics: capacity.

Glossary ​

TermMeaning
Short pollingClient requests updates on a fixed interval; server answers immediately
Long pollingServer holds the request until an event or timeout, then the client re-requests
Hanging GETAnother name for a held long-poll request
CometUmbrella name for HTTP server-push techniques before WebSocket
Server-Sent Events (SSE)WHATWG standard for a never-ending HTTP response carrying events
EventSourceThe browser API that consumes SSE and reconnects automatically
text/event-streamThe SSE MIME type and line format
Last-Event-IDRequest header carrying the last SSE id: on reconnect
retrySSE field that sets the reconnection time in milliseconds
WebSocketRFC 6455 protocol: HTTP upgrade, then framed two-way messages over TCP
UpgradeHTTP/1.1 hop-by-hop mechanism to switch protocols on a connection
101 Switching ProtocolsServer response that completes the WebSocket handshake
Sec-WebSocket-KeyRandom base64 nonce from the client handshake
Sec-WebSocket-Acceptbase64(SHA-1(key + GUID)) proving the server speaks WebSocket
FrameWebSocket unit: FIN, RSV, opcode, mask, length, payload
Opcode4-bit frame type: continuation, text, binary, close, ping, pong
Masking key32-bit random XOR key on every client-to-server frame
Ping / pongControl frames for keepalive and liveness checks
HeartbeatPeriodic message proving liveness (protocol ping or application message)
Close codeTwo-byte reason in a Close frame (1000, 1001, 1006, 1008, 1009, 1011, ...)
SubprotocolApplication protocol name negotiated with Sec-WebSocket-Protocol
permessage-deflateRFC 7692 extension compressing each message
Context takeoverReusing the zlib window across messages; better ratio, more memory
BackpressurePolicy for a consumer slower than the producer
Slow consumerClient whose queue fills; disconnected, dropped or coalesced
CoalescingKeeping only the newest value per key instead of every update
WebTransportW3C API for HTTP/3 streams and datagrams between browser and server
WebRTC data channelPeer-to-peer SCTP channel, optionally unordered and unreliable
Extended CONNECTRFC 8441 method that carries WebSocket over an HTTP/2 or HTTP/3 stream
C10K / C10MServing 10 thousand / 10 million concurrent connections on one machine
Event loopReadiness-based I/O loop (epoll, kqueue) serving many connections per thread
File descriptor (fd)Kernel handle per socket; ulimit -n caps them
Connection gatewayProcess that only holds client connections and maps channels to them
Sticky sessionLoad balancer affinity sending one client's requests to one server
Stateless gatewayGateway with no state that must survive it; clients resume anywhere
Pub/sub fan-outPublishing once and delivering to every subscriber node and member
Redis Pub/SubRedis PUBLISH/SUBSCRIBE; at-most-once, no history
Sharded pub/subRedis 7 SPUBLISH/SSUBSCRIBE, channels hashed to cluster slots
Connection shardingAssigning users or channels to specific gateways by hash
Idle timeoutTime a proxy or LB keeps a silent connection (ALB/NGINX 60 s)
DrainStop new connections and close existing ones gracefully before shutdown
Deregistration delayAWS ALB time to keep a draining target (300 s default)
Reconnection stormMany clients reconnecting at once after a failure or deploy
Thundering herdMany clients hitting the same resource at the same moment
Jitter / full jitterRandomised delay; full jitter = random(0, min(cap, base*2^n))
PresenceSet of currently connected users or devices in a channel
TTLExpiry after which an entry is considered gone
Last seenTime of a user's last disconnect, stored durably
Multi-deviceOne user with several simultaneous connections (tabs, phone, laptop)
Sequence numberGap-free per-channel counter stamped at publish
CursorPosition a client resumes from (last seq or event id)
Resume / recoveryReplaying missed messages after reconnect from history
EpochIdentifier of a history stream so a reset stream is not mistaken for the old one (Centrifugo)
At-least-onceEvery message delivered one or more times; needs dedup
DedupDropping repeated messages by id or sequence
Ticket authShort-lived single-use token fetched over HTTP and presented at upgrade
Origin checkComparing the handshake's Origin header with an allowlist
CSWSHCross-Site WebSocket Hijacking: a foreign page using the victim's cookies on your socket
Pusher protocolJSON event protocol over WebSocket used by Pusher Channels and Reverb
ReverbLaravel's first-party Pusher-protocol WebSocket server on ReactPHP
EchoLaravel's JavaScript client for broadcast channels
BroadcastingLaravel's system for sending server events to channels
Private channelChannel requiring authorization per subscription
Presence channelPrivate channel that also exposes the member list
Client event (whisper)Message sent client-to-client through the server without hitting the app
Socket.IONode.js real-time library with its own protocol over Engine.IO
CentrifugoSelf-hosted real-time server with history, recovery and presence
AblyManaged real-time platform with presence and recovery
Phoenix ChannelsElixir framework channels with Presence and PubSub
API Gateway WebSocket APIAWS managed WebSocket endpoint with $connect/$disconnect routes
Durable ObjectsCloudflare single-instance stateful objects that can hold WebSockets and hibernate

References ​

Built by Morteza Negahi