Machine Room

Polling vs WebSockets

How a chat app gets a new message: keep asking every second, or keep one connection open. The one-page notes from the reel, with the numbers from our one-minute test.

Download the PDF

One-page notes, Polling vs WebSockets. How a chat app gets a new message: keep asking, or keep one connection open. 1, The problem. server. app. lunch today?. On the web, a server can't speak first. It only answers when the app asks. RFC 6202: "a server cannot initiate a connection with a client nor send an unrequested HTTP response to a client". 2, Polling: keep asking. anything new?. empty. Every second, the app sends a request: anything new?. Nothing new? The server sends back an empty answer, and the app asks again next second. 3, Our test: 1 minute, 3 new messages. polling. WebSocket. way | requests | empty answers | bytes in the minute. polling | 60 | 57 | 12,510. WebSocket | 1 | 0 | 369. Same minute, same 3 messages. While nothing happens, the WebSocket sends nothing. 4, An empty answer isn't free. GET /poll HTTP/1.1. Host: api.example.com. Connection: keep-alive. 69 bytes. HTTP/1.1 204 No Content. Cache-Control: no-cache. Date: <date>. Connection: keep-alive. Keep-Alive: timeout=5. 136 bytes. 69 + 136 = 205 bytes, and no message inside. Each empty answer is a full request and a full reply, headers and all. Ask less often, and a new message waits longer at the server before it shows up. 5, The WebSocket handshake. GET /chat HTTP/1.1. Host: server.example.com. Upgrade: websocket. Connection: Upgrade. Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==. HTTP/1.1 101 Switching Protocols. Upgrade: websocket. Connection: Upgrade. Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=. handshake. One request asks to upgrade the connection. The server agrees, and the connection stays open. After the handshake, the connection is no longer HTTP. The example is RFC 6455's own. 6, Either side, any time. see you soon. on my way. RFC 6455: "each side can, independently from the other, send data at will". Nobody has to ask, so there are no empty answers. in our test | bytes. one message down | 28. one message up | 32. one quiet second | 0. 7, Which one?. polling. updates are rare. a short delay is okay. WebSocket. chat, games. anything live in both directions. How often you poll depends on how late an update may arrive. RFC 6455's own list: games, stock tickers, multiuser applications with simultaneous editing. Rare updates, a short delay is fine? Poll. Live in both directions? Open a WebSocket.

On a phone, press and hold the image to save it.