Encoding and Evolution
How encoding formats (JSON, XML, Thrift, Protocol Buffers, Avro) handle schema change, and how encoded data flows between processes via databases, services and messages while old and new code coexist.
Key takeaways
- Backward compatibility: new code reads old data. Forward compatibility: old code reads new data. Rolling upgrades need both.
- Language built-in serialization is language-locked, insecure and ignores versioning: transient use only.
- JSON/XML/CSV suit cross-organization interchange but are vague about numbers and lack binary strings.
- Thrift/protobuf identify fields by tags: never change or reuse a tag; added fields must be optional or defaulted.
- Avro has no tags: the reader resolves the writer's schema against its reader's schema by name; only defaulted fields may be added or removed.
- Data outlives code: schema evolution makes years-old records readable as the current schema.
- RPC's location transparency is flawed: network calls time out, get retried and have variable latency.
- Services: servers upgrade first, so requests need backward and responses forward compatibility. Brokers decouple senders and receivers.
Formats for Encoding Data
Feature changes usually change stored data. Relational databases have one schema in force at a time (changed by migrations); schema-on-read databases can mix old and new formats.
Code cannot change everywhere at once: servers use a rolling upgrade (a few nodes at a time, no downtime); client users may not update for a long time. So old and new code and data coexist, and we need:
- Backward compatibility: newer code reads older data. Usually easy: you know the old format.
- Forward compatibility: older code reads newer data. Harder: old code must ignore additions.
Data lives in two representations: in memory (objects, lists, hash tables, with pointers, optimized for the CPU) and as a self-contained byte sequence for files or the network. Memory → bytes is encoding (serialization, marshalling); the reverse is decoding (parsing, deserialization, unmarshalling). The book avoids "serialization" because it means something else for transactions (Chapter 7). Encoding is unrelated to encryption.
Language-Specific Formats
Java java.io.Serializable, Ruby Marshal, Python pickle, Kryo: convenient, but:
- Tied to one language; blocks integration with other organizations.
- Decoding instantiates arbitrary classes: a security hole that can allow remote code execution.
- Versioning and efficiency are afterthoughts (Java's serialization is notoriously slow and bloated).
JSON, XML, and Binary Variants
Standard textual formats, widely supported and widely disliked: XML is verbose and complicated; JSON is popular via browser support and simplicity; CSV is weaker. Problems:
- Number ambiguity. XML/CSV cannot tell numbers from digit strings without a schema; JSON does not separate integers from floats or specify precision.
- Integers above 2⁵³ lose precision in IEEE 754 doubles (JavaScript). Twitter's API therefore returns 64-bit tweet IDs both as a number and as a decimal string.
- No binary strings: Base64 works but is hacky and adds 33%.
- XML Schema and JSON Schema are powerful but complicated; many JSON tools skip them and hardcode decoding logic.
- CSV has no schema and vague escaping (commas, newlines); not all parsers follow the spec.
Still good enough, especially for interchange between organizations, where agreeing on any format matters more than efficiency.
Binary encoding
Internally you can pick a compact, fast format; this matters at terabytes, not for small data. Binary JSON (MessagePack, BSON, BJSON, UBJSON, BISON, Smile) and binary XML (WBXML, Fast Infoset) stay niche. Lacking a schema, they keep the JSON model and embed every field name. Running example (Example 4-1):
{
"userName": "Martin",
"favoriteNumber": 1337,
"interests": ["daydreaming", "hacking"]
}
- MessagePack:
0x83= object with 3 fields;0xa8= 8-byte string, thenuserName;0xa6+Martin. Length prefixes remove end markers and escaping. - 66 bytes vs 81 for compact JSON: a small gain for lost readability. Schema formats reach 32.
Thrift and Protocol Buffers
Protocol Buffers (Google) and Thrift (Facebook), open-sourced 2007–08, both require a schema in an interface definition language (IDL), plus code generation into many languages:
struct Person { // Thrift
1: required string userName,
2: optional i64 favoriteNumber,
3: optional list<string> interests
}
message Person { // Protocol Buffers
required string user_name = 1;
optional int64 favorite_number = 2;
repeated string interests = 3;
}
- Thrift BinaryProtocol: 59 bytes. Type annotation and length per field, but field tags (1, 2, 3) replace field names.
- Thrift CompactProtocol: 34 bytes. Tag and type share one byte; variable-length integers use each byte's top bit as "more follows" (−64..63 in 1 byte, −8192..8191 in 2), so 1337 takes 2 bytes.
- Protocol Buffers: similar bit-packing, 33 bytes.
required/optionalare not encoded;requiredjust adds a runtime check.
Field tags and schema evolution
Schema evolution: schemas change over time. A record is its fields concatenated, each with tag and type; unset fields are omitted.
- Renaming a field is fine; changing a tag invalidates existing data.
- Add fields with new tags: old code skips unknown tags using the type to know the length (forward compatible). New code reads old data (backward compatible) only if added fields are optional or defaulted, never
required. - Remove only optional fields, and never reuse their tag numbers.
Datatypes and schema evolution
- Type changes risk precision loss: widening 32 → 64 bits is fine for new code, but old code truncates large values.
- Protobuf has no list type, only
repeated(the tag repeats), sooptionalcan becomerepeated: new code sees 0–1 elements, old code sees the last one. - Thrift's
listtype forbids that change but supports nested lists.
Avro
Started in 2009 as a Hadoop subproject because Thrift did not fit Hadoop. Schemas in Avro IDL (for humans) or JSON (for machines):
record Person {
string userName;
union { null, long } favoriteNumber = null;
array<string> interests;
}
- No tags; the encoding is 32 bytes, the smallest. Values are just concatenated with nothing identifying fields or types.
- The decoder walks fields in schema order, so data decodes correctly only with the exact schema it was written with.
The writer's schema and the reader's schema
- Writer's schema: the version the encoder knows. Reader's schema: the version the decoding code expects.
- They need only be compatible. The Avro library compares them and translates writer data into the reader's schema.
- Fields match by name (order may differ). Writer-only fields are ignored; reader-only fields get the reader's default.
Schema evolution rules
- Forward: new writer, old reader. Backward: new reader, old writer.
- Only add or remove fields with a default. Adding without one breaks backward compatibility; removing without one breaks forward.
nullneeds a union, e.g.union { null, long, string } field;, and is a valid default only as the union's first branch. Explicit nullability prevents bugs. So Avro uses unions and defaults, not optional/required.- Type changes work if Avro can convert. Renames via reader-side aliases, and adding union branches, are backward but not forward compatible.
| Change | Thrift / Protocol Buffers | Avro |
|---|---|---|
| Field identity | Numeric tag | Name, resolved across both schemas |
| Add field | New tag; optional or default | Must have default |
| Remove field | Optional only; never reuse tag | Must have default |
| Rename | Free | Aliases; backward only |
| Nullability | optional / required | Union with null |
But what is the writer's schema?
Embedding the schema in every record would erase the space savings. It depends on context:
- Large file with lots of records (Hadoop): schema once at the file start, in an Avro object container file.
- Database with individually written records: prefix each record with a schema version number and store the versions in the database (as Espresso does).
- Sending records over a network connection: negotiate the version at connection setup (Avro RPC).
A schema-version database also documents schemas and enables compatibility checks; versions can be an incrementing integer or a schema hash.
Dynamically generated schemas
- No tags makes Avro suit generated schemas: dump a relational database by generating one record schema per table, one field per column (named after it).
- When columns change, regenerate and export; readers still match fields by name.
- Thrift/protobuf would need tags assigned by hand (or by a generator careful never to reuse them). Generated schemas were Avro's design goal, not theirs.
Code generation and dynamically typed languages
- Code generation helps static languages (Java, C++, C#): efficient structures, type checks, IDE autocompletion.
- In dynamic languages (JavaScript, Ruby, Python) it adds a needless compile step, and blocks access to generated-schema data.
- Avro's code generation is optional. Container files embed the writer's schema, so they are self-describing; tools like Apache Pig can read and write them without thinking about schemas.
The Merits of Schemas
- These schema languages are far simpler than XML Schema or JSON Schema, so they support many languages.
- Not new: ASN.1 (1984) evolves via tags and its DER encoding still encodes X.509 certificates, but it is complex and badly documented.
- Databases use proprietary binary network protocols, decoded by vendor drivers (ODBC, JDBC).
Benefits of schema-based binary encodings:
- More compact than binary JSON (no field names).
- The schema is documentation that cannot go stale, since decoding needs it.
- A schema database lets you check compatibility before deploying.
- Generated code gives compile-time type checking.
Modes of Dataflow
Compatibility is a relationship between the process that encodes and the one that decodes. Data flows between processes in three common ways: databases, service calls (REST and RPC), and asynchronous message passing.
Dataflow Through Databases
- Writer encodes, reader decodes. Storing data is like messaging your future self: backward compatibility is required.
- Many processes share a database; during rolling upgrades old code may read what new code wrote, so forward compatibility is also often needed.
- Snag: old code reads a record with a new field, updates it and writes it back. It should keep the unknown field. Formats support this, but decoding into model objects and re-encoding can drop it; just be aware.
Different values written at different times
- A database holds values written milliseconds and years ago. Code is replaced in minutes; old data stays in its old encoding: data outlives code.
- Rewriting large datasets is expensive. Most relational databases add a column with a
nulldefault without rewriting (MySQL often rewrites anyway). Espresso uses Avro's evolution rules. - So the database appears to use one schema while storing many historical versions.
Archival storage
- Snapshots (backups, warehouse loads) are usually encoded consistently in the latest schema.
- Written once and immutable: Avro container files fit, or a columnar format such as Parquet.
Dataflow Through Services: REST and RPC
- Servers expose an API over the network, a service; clients call it. On the web, browsers use standard HTTP, URLs, TLS and HTML, so any browser reaches any site.
- Native apps and client-side JavaScript (
XMLHttpRequest, Ajax) also call servers, usually getting data such as JSON through an application-specific API. - Servers can be clients of other services. Splitting an app this way is service-oriented architecture (SOA), now microservices.
- Unlike databases' arbitrary queries, services expose only business-logic APIs: encapsulation.
- Goal: each team deploys its service independently, so client and server versions mix and encodings must stay compatible.
Web services
A web service uses HTTP, in three contexts: device apps calling over the internet; services within one organization (middleware); and cross-organization APIs (credit card processing, OAuth).
| REST | SOAP | |
|---|---|---|
| Nature | Design philosophy on HTTP principles | XML-based protocol |
| HTTP | URLs for resources; HTTP caching, auth, content negotiation | Aims to be HTTP-independent; WS-* standards |
| Description | OpenAPI (Swagger) | WSDL, with code generation |
| Status | Growing, esp. cross-organization and microservices | Large enterprises; tool-dependent, vendor interop issues |
An API following REST is RESTful. SOAP is not required for SOA.
The problems with remote procedure calls (RPCs)
Earlier technologies: EJB and RMI (Java only), DCOM (Microsoft only), CORBA (very complex, no compatibility). All are RPC (since the 1970s), which makes a remote call look local: location transparency. This is fundamentally flawed:
| Local call | Network request |
|---|---|
| Predictable | Lost messages, slow or down remote; must retry |
| Returns, throws or hangs | Can time out, leaving the outcome unknown |
| Runs once | Retries may repeat the action unless you add idempotence |
| Consistent duration | Much slower; under 1 ms to many seconds |
| Passes pointers | Must encode all parameters; hard for big objects |
| One language | Types translated across languages (e.g. 2⁵³ in JavaScript) |
So do not make remote services look like local objects. REST appeals partly because it does not hide the network.
Current directions for RPC
- Thrift and Avro include RPC; gRPC uses Protocol Buffers; Finagle uses Thrift; Rest.li uses JSON over HTTP.
- They admit calls are remote: Finagle and Rest.li use futures for failable async calls and combining parallel requests; gRPC has streams of requests and responses. Some offer service discovery.
Data encoding and evolution for RPC
- Assume servers upgrade first, clients second: requests need backward, responses forward compatibility.
- Rules come from the encoding: Thrift, gRPC and Avro RPC follow their formats; SOAP's XML schemas have pitfalls; REST typically uses schemaless JSON, where adding optional request parameters or response fields is compatible.
- Providers cannot force external clients to upgrade, so compatibility may last forever and breaking changes mean multiple API versions side by side.
- Versioning has no standard: REST puts it in the URL or
Acceptheader, or the server stores each API key's version, set via an admin interface.
Message-Passing Dataflow
Between RPC and databases: messages arrive with low latency, but via a message broker (message queue) that stores them temporarily. Versus direct RPC, a broker:
- Buffers for unavailable or overloaded recipients, and redelivers after crashes.
- Hides recipient addresses (useful when cloud VMs come and go).
- Fans out one message to many recipients, and decouples senders from consumers.
Messaging is usually one-way and asynchronous; any reply uses a separate channel.
Message brokers
- Once commercial (TIBCO, IBM WebSphere, webMethods); now open source (RabbitMQ, ActiveMQ, HornetQ, NATS, Apache Kafka).
- Producers send to a named queue or topic; the broker delivers to consumers or subscribers. Consumers can chain to other topics or answer on a reply queue.
- Messages are bytes plus metadata, so any encoding works; compatible encodings let you deploy publishers and consumers in any order.
- Republishing consumers must preserve unknown fields (as in Figure 4-7).
Distributed actor frameworks
- The actor model replaces threads (races, locks, deadlock) with actors: private state, asynchronous messages, one message at a time. Delivery is not guaranteed.
- Distributed actor frameworks use the same messaging across nodes, encoding remote messages transparently. Location transparency fits better here because loss is already assumed.
- Rolling upgrades still need forward and backward compatibility.
| Framework | Default encoding | Rolling upgrades |
|---|---|---|
| Akka | Java serialization | Possible if swapped for e.g. Protocol Buffers |
| Orleans | Custom format | No by default: new cluster, move traffic; plug-ins possible |
| Erlang OTP | Records, hard to change | Need careful planning; maps (R17, 2014) may help |
Summary
- Encoding choices affect efficiency and, more importantly, architecture and deployment options.
- Rolling upgrades give releases without downtime and lower risk, which helps evolvability; nodes then run mixed versions, so data needs backward and forward compatibility.
- Language-specific encodings: one language, often no compatibility.
- JSON, XML, CSV: widespread; compatibility depends on use; vague about numbers and binary strings.
- Thrift, Protocol Buffers, Avro: compact, clear compatibility semantics, schemas for docs and code generation; but not human-readable without decoding.
- Dataflow modes: databases (writer encodes, reader decodes), RPC and REST (requests and responses each encoded and decoded), async messaging via brokers or actors.
- With care, compatibility and rolling upgrades are quite achievable.
Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.