Course contentsShow
← Node.js
Lesson 1145 of 1,98010. Real-time Communication and WebsocketsFree lesson

Optimizing Message Payloads with Gzip/Brotli

You will apply transparent compression to WebSocket traffic to reduce total bandwidth usage.

In this lesson, you will learn how to reduce your WebSocket bandwidth consumption by transparently compressing data payloads using Gzip or Brotli before they leave your server.

While WebSockets are efficient, they lack the automatic HTTP-style Content-Encoding headers that browsers use to compress REST API responses. If your real-time application frequently sends large JSON objects—like high-frequency state updates or dashboard telemetry—the cumulative bandwidth can become a bottleneck. By manually applying compression, we can significantly shrink these payloads before they hit the wire.

Integrating Compression with Zlib

Node.js comes with a built-in zlib module that allows us to compress data into buffers. When sending a message over a WebSocket, we can intercept the outgoing data, transform it, and send the compressed buffer instead of the raw string.

Here is how you might implement a simple compression helper:

const zlib = require('zlib');

function sendCompressed(socket, data) {
  const payload = JSON.stringify(data);
  
  // Compress the payload using Brotli (often better for JSON)
  zlib.brotliCompress(payload, (err, buffer) => {
    if (!err) {
      // Send the compressed buffer
      socket.send(buffer);
    }
  });
}

Key Implementation Considerations

  1. Binary Frames: Ensure your client knows to expect binary data. WebSockets treat Buffer objects as binary frames. Your client-side code will need to use DecompressionStream (in modern browsers) or a matching library to inflate the message back into a JSON object.
  2. When to Compress: Compressing tiny messages (like a single character or a boolean) often results in a larger payload due to the compression algorithm's metadata overhead. Only apply this optimization to larger, repetitive JSON structures where the CPU cost of compression is outweighed by the savings in network throughput.
  3. Brotli vs. Gzip: Brotli generally offers superior compression ratios for text-heavy JSON payloads compared to Gzip, making it the preferred choice for real-time WebSocket traffic.

By shifting this minor CPU burden to the server, you significantly lower the "cost per message" for your infrastructure and improve performance for users on high-latency mobile networks.

Key Takeaway: Compressing WebSocket payloads using zlib allows you to trade a small amount of server CPU time for significant reductions in network bandwidth, especially for large, repetitive JSON messages.