Lesson · Serialization & Data Formats
Modern alternatives: JSON, Protobuf, Avro and the schema that saves you
14 min readModern Alternatives
Once a format can name classes, the reader has to trust the writer. The alternatives split into two families: self-describing text such as JSON, and schema-carrying binary such as Protobuf and Avro. Choose on schema evolution and trust, not on byte counts.
JSON: text, universal, and the typing trap
You need to hand one Order to another service. Java serialization does it in a line, and that line is the problem: the payload names classes, so the reader's classpath becomes the writer's toolbox. JSON is the usual replacement because it is readable, self-describing per document and needs no build step.
Jackson and Gson map JSON to your classes; with Jackson 2.12+ even records work out of the box on Java 16+, because the component names are in the class file. Plain classes need either -parameters at compile time or an explicit @JsonCreator, which is the same information by a different route.
The trap is polymorphic typing. Jackson can embed class names in the JSON so it can rebuild a subtype, and if you enable that globally (the old enableDefaultTyping, deprecated in favour of activateDefaultTyping) the payload decides which classes the reader instantiates. That is the Java serialization problem wearing JSON syntax, and it produced a long CVE family in jackson-databind starting with CVE-2017-7525. The safe pattern is for the receiver to own the type set: explicit DTOs per endpoint, or a named-subtype allowlist.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind") // a name travels, not a class name @JsonSubTypes({ @JsonSubTypes.Type(value = CardPayment.class, name = "card"), @JsonSubTypes.Type(value = InvoicePayment.class, name = "invoice") }) sealed interface Payment permits CardPayment, InvoicePayment { } record OrderDto(long id, String customer, BigDecimal total) { } // Jackson 2.12+ maps records
- Unknown properties: Jackson 2.x rejects them by default, which turns a drifted producer into a loud failure instead of a silently ignored field. Decide deliberately which side of that you want.
- Polymorphism belonging to the reader: a named-subtype allowlist keeps the payload to names you published, and never to classes you did not.
- No schema: JSON describes each document, not the agreement between producer and consumer; nothing stops a rename except tests and validators.
- Numbers and time: JSON has one number type and no date type, so BigDecimal scales and java.time formats belong to the contract you write down.
A JSON payload that carries a class name is Java serialization with a text encoding. The receiver must decide which types can appear, not the payload.
Protocol Buffers: schema first, field numbers are the contract
Protobuf starts from a .proto file and generates code from it. The wire format is a tag and a value per field, with integers written as varints, so the bytes scale with the numbers you actually send. Fields are identified by number, never by name, which makes the number a permanent identifier: numbers 1 to 15 encode in a single tag byte, higher numbers take more, and a number is never reused once a consumer has seen it.
Compatibility rules follow from that: adding a field is safe, changing a field's number or type is not, and retiring a field means reserving its number and name so no future developer resurrects a meaning. The format is not self-describing; without the .proto the bytes are just tags, and that is the point, because the reader never takes a class name from the payload.
syntax = "proto3"; message Order { reserved 4, 7; // numbers that are gone for good reserved "legacy_note"; // names too, so a rename cannot revive a meaning int64 id = 1; // 1 to 15 cost one byte of tag: spend them on hot fields string customer = 2; optional string promo_code = 3; // explicit presence (protobuf 3.15+) }
- Compact and fast: no field names on the wire, generated parsers, and gRPC is built on the same format.
- Not self-describing: readers need the
.proto, so a consumer cannot be tricked into loading a type the schema does not declare. - Unknown fields are preserved: proto3 has kept them since 3.5, so a new producer and an old consumer can be deployed in either order without losing data.
- No required in proto3: model absence explicitly with
optionaloroneof, and let the reader validate.
In Protobuf the schema is the API. Renaming a field is free, renumbering it is a data migration, and a reserved number is the only way to make that permanent.
Avro: the writer's schema travels with the data
Avro encodes records compactly and pairs every payload with the schema that produced it, either inside a container file or by an id that points at a registry. The reader brings its own schema and resolution happens at read time: fields are matched by name, a reader field that is missing from the data takes its declared default, extra writer fields are skipped, and a short list of promotions is allowed (int to long, float or double; string and bytes to each other).
That is the strongest evolution story of the three for data pipelines. Old data and a new reader schema is a supported combination, and the reason it works is the default: add a field without one and resolution fails for every record written before it existed.
- Field order does not matter: fields are matched by name, and a writer field the reader does not know is ignored.
- Defaults are load-bearing: a new reader field must declare one, or old data cannot satisfy it.
- Promotion is one-way and limited: int widens to long, float or double; nothing narrows back.
- Codegen is optional: generic records read and write Avro without generated classes, which is what most pipeline tools do.
- Registries are the coordination point: in Kafka ecosystems the writer schema is registered once and its id rides with each message.
Avro treats evolution as a read-time projection. Old bytes plus a new schema is a normal operation, provided every new field declares a default.
CBOR and MessagePack: binary JSON shapes, no schema required
CBOR (an IETF standard, RFC 8949) and MessagePack encode the same JSON-shaped data (maps, arrays, strings, numbers, byte strings) in binary, which makes payloads smaller and parsing cheaper without agreeing a schema or generating code. They are the right answer when a non-Java service needs compact data and the contract has not been written yet.
What they do not give you is a contract. Like JSON they are self-describing per document, so a renamed field is still a runtime surprise, and evolution discipline is yours to enforce.
Compression shrinks bytes; a schema shrinks coordination. Pick CBOR or MessagePack for size and interop, not for safety: the receiving code still decides what the data means.
Choosing: the table, and the through-line
The deciding questions are who writes the bytes, who reads them, and what has to change without a coordinated deploy. Readability and size matter, but they are second-order next to those three.
| Format | Encoding | Schema | Self-describing | Evolution | Best fit |
|---|---|---|---|---|---|
| Java serialization | binary object graph | class shape plus serialVersionUID | yes, class names included | brittle: UID and descriptor rules | state snapshots inside one trust boundary, and the default to migrate away from |
| JSON | text | none | yes, per document | additive changes plus tolerant readers | public HTTP APIs, configuration, anything a human or a browser reads |
| Protobuf | binary, varint tags | .proto, field numbers are the contract | no | strong: add fields, reserve retired numbers | service-to-service RPC, mobile clients, gRPC, long-lived wire contracts |
| Avro | binary, compact | writer schema travels with the data or by registry id | no (the schema is the description) | strongest for pipelines: reader-schema defaults resolve old data | data pipelines and topics where producers and consumers evolve on their own schedules |
| CBOR / MessagePack | binary, JSON-shaped | none | yes, per document | same as JSON: tolerant readers | interop with non-Java services when compactness matters and no schema is agreed |
- Class names in a payload are a liability. Java serialization and Jackson default typing share the flaw, in different syntaxes.
- A schema is a contract you can review. Protobuf field numbers and Avro schemas are versioned artifacts next to the code that uses them.
- Self-describing is not schema-free. JSON, CBOR and MessagePack describe each document, not the agreement between the two sides.
- Migration is a boundary, not a rewrite. Read both formats while producers move, and filter the old stream until the last writer is gone.
A format that can name classes hands the reader's classpath to the writer. A format with a schema keeps the choice of types inside the reader's own build.
Data formats one Order, four encodings
AC ED 00 05 stream header
TC_OBJECT / TC_CLASSDESC com.shop.Order, UID 1L
fields: id:int, customer:String, total:double
values: 7, "ana", 49.99
largest of the four for this record, and it grows with every class the graph names
keeps state, not trust: every reader loads classes the writer chose
Leaving Java serialization without a flag day
You rarely get to replace a format in one commit. The sequence below keeps the system running while the surface shrinks, and it starts with mitigation, because the vulnerable endpoint stays vulnerable until the last writer is upgraded.
- Inventory every ObjectInputStream, readObject call and Serializable payload that crosses a process boundary: HTTP, RMI, JMX, queues, caches, session stores.
- Classify by writer: the boundaries where you do not control who writes are the urgent ones. Install an allowlist filter there today, as mitigation, and note that it is mitigation.
- Define the new format from the consumer's needs, not from the shape of the current class: write the
.proto, the Avro schema or the DTO first, and review it as an API. - Run both: version the endpoint (new route or new content type), keep reading the old format behind the filter, and stop writing it producer by producer.
- Close the path: remove the Serializable classes from the API surface, and keep the filter until the last old producer is decommissioned, then remove the reader too.
You migrate a format producer by producer, not in one release. The old reader stays filtered until the last writer of the old format is gone, and then it is deleted.
Class names in the payload
Any format that carries class names (Java serialization, Jackson default typing) lets the writer choose what the reader instantiates. That is one vulnerability wearing different syntaxes. Prefer formats where the set of types is decided by the reader's schema or by explicit annotations, and never enable default typing as a shortcut because it made a polymorphic field compile.
Interview angles
Why are records a better DTO than a mutable bean?+
The component list is the contract: it cannot drift silently, every field is final, and Jackson 2.12+ maps records without annotations on Java 16+. There is no half-built object and no setter-only field that a producer can accidentally omit.
What is wrong with Jackson default typing?+
It writes class names into the payload and instantiates whatever the payload named, which recreates the Java serialization attack class. jackson-databind accumulated a long CVE family from exactly that.
Default typing is opt-in since Jackson 2.10, and the old enableDefaultTyping is deprecated in favour of activateDefaultTyping with a PolymorphicTypeValidator. That validator is a boundary, not a formality: use explicit DTOs or @JsonSubTypes allowlists so the receiver owns the type set.
Common misconception: A PolymorphicTypeValidator makes default typing safe in general.
What are the Protobuf field numbering rules?+
Numbers identify fields on the wire; 1 to 15 fit in a single tag byte. Adding a field is compatible, changing a number or a type is not, and retiring one means reserving both the number and the name.
proto3 has preserved unknown fields since 3.5, so an old consumer forwards fields it does not understand instead of dropping them, which is what makes independent deploys work.
How does Avro differ from Protobuf on evolution?+
Avro resolves at read time between the writer's schema and the reader's: fields match by name, a reader field missing from the data takes its declared default, and only declared promotions are allowed. Protobuf keeps the contract in field numbers and never needs the writer's schema at read time.
When are CBOR or MessagePack the right answer?+
When the data is JSON-shaped, a schema is not agreed, and size matters, typically for interop with a non-Java service. You get a compact encoding without a contract, so evolution discipline is the same as JSON's.
How do you migrate off Java serialization in a running system?+
Filter the old stream first as mitigation, define the new format from the consumer's needs, version the endpoint so both formats can be read, move producers one at a time, then delete the old reader and the Serializable classes.
Then the filter and the allowed class list are permanent code: review them like code, watch the jdk.Deserialization JFR events, and record the endpoint as a boundary you intend to retire.
Follow-up: What if a producer of the old format cannot be changed?