Search

Search papers and lessons

Data Serialization

Level 2 · 11 min read

Data serialization turns a structure in a program's memory into a flat sequence of bytes that another program can rebuild exactly, by agreeing on a layout for every field.

On this page

  • Colour = topic mix
  • Programming languages
  • Discrete math
  • Algorithms
  • Networking
  • Systems
  • ReadReady to readNot yet

TL;DR

A running program keeps its data as objects scattered through memory, linked by addresses. To send that data over a network or save it to a file, the program must flatten it into one sequence of bytes. Serialization is that flattening; deserialization is the rebuilding on the other side. It works only when both sides agree on the layout.

Builds on: Binary Numbers (Bits and Bytes), Type System · Leads to: Network Protocol, Structured Output

Where it's used

Web APIs. When a phone app asks a server for your profile, the server turns the profile object into JSON text, sends it over HTTP, and the app parses that text back into its own objects. Many public web APIs work this way.

Remote procedure calls. Systems such as gRPC run one service's functions on another machine. Each call's arguments are serialized with Protocol Buffers, a compact binary format, so a call with a few small fields often fits in a few dozen bytes instead of hundreds.

Saving game state and documents. A game that saves at a checkpoint writes its world (positions, inventory, flags) to disk as bytes. Loading the save is deserialization. A change to the layout can make old saves unreadable, which is why such formats carry a version number.

Large language model tool use. When a model must return a result that another program can read, it is asked to produce output that matches a fixed schema. That is the same job as serialization, done by the model instead of a library (see Structured Output).

How it works

Take one tiny record, a single field named count holding the integer 258, and turn it into bytes. The format used here is made up for teaching. Real formats differ in detail but follow the same steps.

flowchart LR
  A[Object in memory: count = 258] --> B[Write name length]
  B --> C[Write name bytes]
  C --> D[Write type tag]
  D --> E[Write value bytes]
  E --> F[Byte sequence sent or stored]
  F --> G[Reader reverses each step]
  G --> H[Object rebuilt: count = 258]
  1. Start with the value. In memory, count is a 32-bit integer whose bits happen to encode 258. The address where it sits is meaningless to any other program, so the address itself must not be written out. Check: the bytes we write must describe the value, not where it lives.
  2. Write the length of the name. The name count has five letters, so write the byte 05. Check: the reader now knows the next five bytes are the name.
  3. Write the name. The letters c, o, u, n, t have codes 63 6F 75 6E 74. Write those five bytes. Check: total so far is six bytes.
  4. Write the type tag. Agree that tag 01 means "32-bit signed integer". Write 01. Check: the reader now knows how many bytes the value takes.
  5. Write the value. 258 is 1 times 256 plus 2 times 1, so in base 256 its digits are 1 and 2. Write four bytes, most significant first: 00 00 01 02. Check: 00 00 01 02 read as base 256 is 0 + 0 + 256 + 2 = 258.
  6. Concatenate. The record is 05 63 6F 75 6E 74 01 00 00 01 02, eleven bytes in all. A network stream carries these bytes in order; TCP guarantees the order (see Transmission Control Protocol). Check: 1 + 5 + 1 + 4 = 11 bytes.
  7. Reverse it on the reader's side. Read the length 05, read five bytes to get count, read the tag 01, read four bytes, and compute 256 plus 2 to get 258. The rebuilt object equals the original. Check: decoding reverses each encoding step in the opposite order, and nothing is left over.

Notice what the reader needed. It could not decode the bytes without knowing the rules in steps 2 to 5. Those rules are the format, and they are the agreement the two programs must share.

The math

Let a record be a list of fields (n1,v1),…,(nk,vk)(n_1, v_1), \dots, (n_k, v_k), where each nin_i is a name and viv_i is a value.

A serializer is a Function EE that maps the record to a byte string. A deserializer DD maps bytes back to a record. The only requirement is that decoding undoes encoding, which makes EE an injective function:

D(E(r))=rfor every record r.D(E(r)) = r \quad \text{for every record } r.

Step 2 in symbols. The name nin_i is encoded as its length ℓi=∣ni∣\ell_i = |n_i|, stored in one byte, followed by its characters. For count, ℓ=5\ell = 5, so the encoding begins with the byte 0505.

Step 5 in symbols. A 32-bit integer vv with digits b3b2b1b0b_3 b_2 b_1 b_0 in base 256 is written as v=b3⋅2563+b2⋅2562+b1⋅256+b0,0≤bj<256.v = b_3 \cdot 256^3 + b_2 \cdot 256^2 + b_1 \cdot 256 + b_0, \qquad 0 \le b_j \lt 256. For v=258v = 258: b1=1b_1 = 1, b0=2b_0 = 2, b3=b2=0b_3 = b_2 = 0, giving the four bytes 00 00 01 0200\ 00\ 01\ 02.

Step 7 in symbols. The decoder computes the sum v=∑j=03bj⋅256jv = \sum_{j=0}^{3} b_j \cdot 256^j, which returns 258258. Because each byte value lies between 0 and 255, the base-256 digits are unique, so no other integer produces the same four bytes.

Worked examples

Example
Example 1: the smallest case (hand-computable)

Encode the field n = 1, where the name is the single letter n and the type is the 32-bit integer.

  1. Name length: 1, so write 01.
  2. Name byte: the letter n has code 6E, so write 6E.
  3. Type tag: integer, so write 01.
  4. Value 1 in four bytes, most significant first: 00 00 00 01.
  5. Result: 01 6E 01 00 00 00 01, seven bytes.
  6. Check: 1 + 1 + 1 + 4 = 7 bytes, and reading back gives name n, integer, value 0 + 0 + 0 + 1 = 1.

Interpretation: the smallest possible integer field still costs seven bytes here, because the name and tags travel with the value.

Example
Example 2: the standard case (two fields)

Encode the record count = 258 and ok = true. Use the same tags as before, and add tag 02 for a boolean, stored in one byte where 01 means true.

  1. The count field is the eleven bytes from the walkthrough: 05 63 6F 75 6E 74 01 00 00 01 02.
  2. The name ok has two letters, so write length 02.
  3. The letters o and k have codes 6F and 6B. Write 6F 6B.
  4. The type tag for a boolean is 02. Write 02.
  5. The value true is 01. Write 01.
  6. Concatenate the two fields: 05 63 6F 75 6E 74 01 00 00 01 02 02 6F 6B 02 01, which is 16 bytes.
  7. Decoding reads the first field as before, then reads the second by the same rule: length 2, name ok, tag boolean, one byte, value true.

Interpretation: each new field adds its name and its tag. A format that writes names every time is easy to read and easy to extend, but a larger one.

Example
Example 3: a realistic string field

A profile server sends a field name with the text Ada. Strings are often stored as a length followed by the characters in UTF-8 (for plain English letters, one byte each). Use tag 04 for a string and a four-byte length.

  1. Name length: name has four letters, so write 04, then 6E 61 6D 65.
  2. Type tag for a string: write 04.
  3. Length of the text Ada: three bytes, written as four bytes, 00 00 00 03.
  4. The characters A, d, a have codes 41, 64, 61. Write 41 64 61.
  5. The field is 04 6E 61 6D 65 04 00 00 00 03 41 64 61, which is 13 bytes.
  6. Decoding reads the length first, so it knows exactly how many bytes to take. It never has to search for an end marker inside the text.

Interpretation: storing the length first is what lets a reader take the right number of bytes from a stream, even when the text itself contains any byte value. Try it: encode the field age = 30 as a 32-bit integer, using the same rules as Example 1. Answer: 03 61 67 65 01 00 00 00 1E. The name age has length 3, its letters are 61 67 65, the tag is 01, and 30 is 1E in hexadecimal, so the value is 00 00 00 1E.

Common mistakes and tradeoffs

It is tempting to think that serializing an object means copying its memory. In fact memory copies break for several reasons. A Pointer holds an address that is valid only inside one process, so the receiver would read garbage. The layout of a struct can include padding that differs between compilers. And the byte order of a multi-byte integer (big-endian writes the most significant byte first, as in the example above; little-endian writes it last; see Binary Numbers (Bits and Bytes) for how digits map to bits) must be agreed, not assumed. A correct serializer writes values, not addresses, in a layout both sides define.

It is tempting to think that binary formats are always smaller and faster than text. Often they are, but not always. JSON is text, so a person can read it in a log file, and any language can parse it. Binary formats win on size and parsing speed, and they need the schema to be shared. Choose by what matters most: human readability and wide support, or compactness and speed between services you control.

It is tempting to think that deserializing is safe because the sender is trustworthy. In fact a length field can claim four gigabytes, and a naive decoder will try to allocate that much memory. Decoding bytes from an untrusted source must check every length against a limit before using it.

Tradeoffs in short:

ApproachExampleGood whenWeak when
Text with field namesJSONHumans read it, many languages parse itLarge payloads, slow parsing
Binary with a shared schemaProtocol BuffersServices you control, high volumeSchema changes must be managed
Binary, self-describingFormat with tags and names, as in this lessonReaders need no schema in advanceNames repeat in every message

History

In the early decades of computing, programs that saved data to tape or disk wrote their own layouts by hand, and a new program often could not read the old files. Sun Microsystems published External Data Representation, a standard way to lay out data for network calls, in the late 1980s. It fixed the byte order and the rules for each type, so machines of different kinds could share data.

JSON became popular in the early 2000s because browsers already ran JavaScript, and its text form was easy to read and to produce from almost any language. It was standardized as RFC 8259 in 2017. Google developed Protocol Buffers for its own services around 2001 and released them publicly in 2008, favouring a compact binary form that a schema describes. These two styles, text with names and binary with a schema, still share the field.

Recap

  • A running program's data is spread across memory and linked by addresses, so it cannot be sent as is.
  • Serialization writes each field's name or schema position, type, and value as bytes; deserialization reverses it.
  • The format is a contract: both sides must agree on lengths, tags and byte order.
  • Writing a length before each variable-sized value lets a reader know how many bytes to take.
  • Never trust lengths from an outside source without a limit.

Next, read Network Protocol to see how a shared format sits inside a set of rules for messages, and Structured Output to see a language model asked to produce a format a program can parse.

Check yourself

QuestionWhy can a program not send a [[pointer]]'s address to another machine and expect it to work?Show answer

An address names a place in one process's memory. On the other machine the same number points to some unrelated place or to nothing. Serialization must write the value the pointer leads to, in a layout both sides define, and rebuild a new pointer on the receiver.

QuestionEncode the field `z = 2` as a 32-bit integer with name `z`, using the rules in this lesson. Give the bytes.Show answer

The name z has length 1, so write 01. Its letter has code 7A. The integer tag is 01. The value 2 in four bytes is 00 00 00 02. The full field is 01 7A 01 00 00 00 02, seven bytes.

QuestionWhy does the format write the length of a string before its characters, instead of ending the string with a special marker?Show answer

A reader consuming a stream of bytes needs to know where a value ends. If the string may contain any byte, no marker is safe, because the marker's value could appear inside the text. A length tells the reader exactly how many bytes to take, and it is cheap to check against a limit before reading.

QuestionA service receives a message whose length field says 4 gigabytes, but the connection has sent 200 bytes. Explain the risk and one fix.Show answer

A naive decoder allocates a buffer for the claimed 4 gigabytes before reading, which can exhaust memory or crash the service, and an attacker can send such a message cheaply. A fix is to check every length against a maximum size the application allows before allocating, and to reject messages that exceed it or that stop arriving.

Sources