Video in progress

When does the permessage-deflate extension speed up WebSocket traffic, and when does it hurt?

On large, repetitive JSON messages it cuts traffic several times over. But the compression context takes memory for every connection and burns CPU, so it can hurt in systems with many connections and small messages.

📖 Answer

The extension is negotiated in the handshake: the client sends Sec-WebSocket-Extensions: permessage-deflate, and if the server agrees it returns it in the response. Browsers ask for it by default, and Tomcat and Jetty support it.

The benefit comes from "context takeover". The compression dictionary is kept between messages. From the second message on, repeated keys like "orderId" and "status" are almost free. On streams like price quotes or dashboard updates, a 3 to 5 times reduction in traffic is normal.

But it isn't free:

  • zlib state for each connection in both directions (compress and decompress), tens of kilobytes. At 100,000 connections that's gigabytes;
  • CPU. On small messages (up to 100 bytes) compression gives almost no benefit, but the CPU is spent anyway;
  • on a broadcast each client is compressed separately, because each has a different context.

On some servers you can reduce memory with no_context_takeover and a smaller window (server_max_window_bits), but the compression ratio drops too.

The decision has to rest on measurement. I usually run two tests under the same load, enabled and disabled, and compare RSS memory, CPU and egress traffic. If there are many mobile clients and the messages are large, it's usually worth enabling.