Part 4 of 11
Protobuf
Google built protobuf (short for Protocol Buffers) to encode records in binary. Facebook's Apache Thrift is very similar, and most points here apply to both.
- You must write a schema in protobuf's interface definition language (IDL).
- Each field has a type, a name, and a number.
- A code generator turns the schema into classes for many languages. Your app calls these classes to encode and decode records.
- The schema language is small: fields and types only, with no rules about allowed values (unlike JSON Schema).
Our example record takes only 22 bytes in protobuf. Here is how:
- Each field starts with one byte that packs two things: the field tag (the number from the schema) and the field's type.
- Field names never appear in the data. The tag is a compact stand-in for the name.
- Strings have a length, then UTF-8 bytes.
- Whole numbers use a variable-length form. The top bit of each byte means "another byte follows". So 300 needs two bytes, and our zip code needs three. With signed encoding, numbers from -64 to 63 fit in one byte, and -8,192 to 8,191 in two.
- There is no list type. A field marked
repeatedis a list, and each item simply appears as another copy of the same tag.
The record as protobuf bytes
Step 1 of 5
The record has a city, a zip code and two tags. The schema gives each field a number: city is 1, zip is 2, tags is 3.
Field tags and schema evolution
Guess first
In protobuf, can you rename a field without breaking data that is already stored?
Schema evolution means the schema changes over time, while old and new code stay compatible. A protobuf record is just its fields joined together, each with its tag and type. Fields that are not set are left out.
| Change | Safe? | Why |
|---|---|---|
| Rename a field | Yes | Names are not in the data |
| Change a field's tag | Never | All existing data would be read wrongly |
| Add a field with a new tag | Yes | Old code sees a tag it does not know and skips it, using the type to know how many bytes to skip; it can also keep those bytes and write them back. That gives forward compatibility |
| Read old data with new code | Yes | Tags keep their meaning, and new fields that are missing get defaults like an empty string or 0. That gives backward compatibility |
| Remove a field | Yes, with care | It is the mirror of adding. Never reuse its tag; mark the old number as reserved in the schema |
| Change a field's type | Risky | Widening a 32-bit number to 64 bits works for new readers (they pad with zeros), but old readers cut off large values |