Video in progress

When is it worth moving WebSocket messages from JSON to a binary format like Protobuf or MessagePack?

When messages are very numerous and small (quotes, telemetry, game state) and the traffic and the CPU spent on serialization become noticeable. For an ordinary chat or notifications, JSON is more convenient: it's readable in DevTools, debugging is cheap, and permessage-deflate narrows the gap a lot.

📖 Answer

Measure first. I usually take a sample of one day of real traffic and compare three numbers: the average message size (after compression), the share of server CPU spent on serialization, and traffic complaints from mobile clients. In most cases JSON plus deflate turns out to be enough.

When binary wins:

  • the message is mostly numbers (price, volume, ts): in JSON every number is text and the key names repeat in every message;
  • hundreds of thousands of messages per second, and serializing each broadcast shows up in the profiler;
  • a mobile audience, where traffic costs money.

On the browser side:

ws.binaryType = 'arraybuffer';
ws.onmessage = e => {
  const quote = Quote.decode(new Uint8Array(e.data)); // protobufjs
  render(quote);
};

On the server side with a raw handler it's BinaryMessage. It works in STOMP too: the body can be binary, with a content-type header. Spring has a ProtobufMessageConverter, which you add through configureMessageConverters.

The cost is rarely mentioned:

  • DevTools now shows bytes, so you need a separate decoder for debugging;
  • keeping the schema in sync between client and server: the .proto files live in a separate repo or artifact, with a compatibility check in CI;
  • MessagePack is schemaless, but it also sends the key names, so the gain isn't as big as with Protobuf.

There's a middle path too: keep the format JSON, but use short keys and arrays ([ts, price, vol]). Often that one change cuts the traffic in half and the code barely changes.