Module 1 · FundamentalsLesson 10 of 886 minBeginner

Serialization, JSON and Protobuf

To send data over a network you turn it into bytes. The format you pick affects size, speed and how easy it is to change later.

Try it

Send the same order as JSON, then as Protobuf, and compare size and time. Then try "Schema mismatch" to see what happens when the two sides disagree.

Objects in a program live in memory with pointers and types. A network can only carry bytes. Serialization is turning an object into bytes; deserialization is turning bytes back into an object.

JSON

{"id": 42, "total": 19.99, "items": ["mug", "tea"]}
  • Readable: you can look at it in logs and debug it by eye.
  • Universal: every language and browser understands it.
  • Loose: no schema, so the receiver has to check what it got.
  • Big and slow-ish: field names are repeated in every message, and numbers are written as text.

JSON is the default for web and public APIs.

Binary formats: Protobuf, Avro, MessagePack

Protocol Buffers (Protobuf) use a schema file both sides share:

message Order { int64 id = 1; double total = 2; repeated string items = 3; }

On the wire, it sends field numbers instead of names, and numbers as compact binary. Messages are often 3 to 10 times smaller and much faster to parse. Protobuf is what gRPC uses.

The trade-off: you can't read the bytes by eye, and both sides must have a compatible schema.

Changing formats without breaking things

Services are rarely updated at the same moment, so for a while an old reader will see new messages and a new reader will see old ones. Safe changes:

  • Add a new field and make it optional.
  • Ignore fields you don't recognise.

Unsafe changes:

  • Renaming or changing the type of an existing field.
  • Reusing an old field number for something new (the demo's "schema mismatch").

This idea, keeping old and new versions able to talk, is called backward and forward compatibility, and it applies to APIs, events and databases too.

Quick check

Two internal services exchange millions of small messages a second. Which format usually fits best?