Data serialization

Also known as: serialization

On this page 7

Data serialization is the process of converting in-memory data structures such as objects, records, lists and maps into a linear sequence of bytes or characters that can be stored in a file, sent over a network or handed to another process, and later reconstructed by deserialization. In software interoperability, serialization is the mechanism that lets two programs written in different languages, running on different machines or released years apart, exchange the same information without sharing memory.

The choice of serialization format determines how large the payload is, how fast it is encoded and decoded, whether humans can read it, and how gracefully the data survives schema changes over time. Formats such as JSON, XML, Protocol Buffers, Avro, MessagePack and CBOR all solve the same problem with different trade-offs.

How serialization turns objects into bytes

A serializer walks an object graph and writes each value in a defined order and encoding, so that a deserializer can rebuild an equivalent structure on the other side. Inside a running program, data lives as pointers, padding and language-specific layouts; none of these are meaningful to another process. Serialization replaces them with a self-contained representation that depends only on the format specification.

Every format must answer the same core questions: how values are typed, how field boundaries are marked, how text is encoded and how numbers are laid out. Text formats usually rely on UTF-8 character encoding and delimiters, while binary formats use length prefixes, tags and fixed-width integers, where the byte order or endianness must be fixed by the specification.

The following table lists the main stages of a serialization round trip and what can go wrong at each one.

StageWhat happensTypical failure
TraversalThe serializer visits every field and nested objectCyclic references cause infinite loops
Type mappingLanguage types map to format types64-bit integers lose precision as doubles
EncodingValues are written as bytes or textWrong character set produces mojibake
FramingMessage boundaries are markedTruncated streams parse as partial data
DecodingBytes are parsed back into valuesUnknown fields are rejected or dropped
ReconstructionObjects are rebuilt in the target languageMissing defaults leave fields undefined
Stages of a serialization round trip

Text and binary serialization formats

Serialization formats fall into two broad families: human-readable text formats and compact binary formats. Text formats such as JSON, XML and YAML are easy to inspect and debug but larger and slower to parse. Binary formats such as Protocol Buffers, Avro, Thrift, MessagePack and CBOR are smaller and faster, but require tools to read.

A second distinction separates schema-based formats, where a separate definition describes every field, from self-describing formats, where field names travel with each message. Schema-based formats produce smaller messages and catch type errors early, while self-describing formats are more flexible for loosely coupled systems.

FormatEncodingSchemaTypical use
JSONText, UTF-8Optional (JSON Schema)Web APIs, configuration
XMLTextOptional (XSD)Documents, enterprise integration
YAMLTextNone by defaultConfiguration files
Protocol BuffersBinary, tagged fieldsRequired (.proto)gRPC services, internal RPC
Apache AvroBinary, schema-resolvedRequired (JSON schema)Data pipelines, Kafka
MessagePackBinaryNoneCompact JSON-like messaging
CBORBinaryOptional (CDDL)Constrained devices, IoT
Common serialization formats compared

Language-specific mechanisms such as Java object serialization or Python pickle also exist, but they bind the data to one runtime and are poor choices for interoperability. They also carry security risks discussed below.

Schema evolution and compatibility

Schema evolution is the ability to change a data structure while old and new programs keep exchanging messages. In real systems, producers and consumers are rarely upgraded at the same moment, so a format must tolerate added, removed and renamed fields. This property is closely related to forward compatibility and backward compatibility of a file format.

Protocol Buffers achieves this with numbered field tags that never change meaning, while Avro resolves differences by comparing the writer schema and reader schema at read time. JSON has no built-in rules, so teams must agree on conventions such as ignoring unknown keys.

ChangeBackward compatibleForward compatibleSafe practice
Add optional fieldYesYes, if unknown fields are ignoredGive it a default value
Remove optional fieldYesYesReserve the old tag or name
Rename a fieldDepends on formatDepends on formatUse aliases or keep tag numbers
Change field typeUsually noUsually noAdd a new field instead
Make field requiredNoNoAvoid required fields entirely
Schema changes and their compatibility effect

Choosing a serialization format

The right format depends on who reads the data, how long it lives and how much it costs to move. A public web API benefits from JSON because every client can read it, while a high-volume internal service benefits from a binary format with a strict schema. Long-lived archives need a format whose specification is an open standard so that the data remains readable after the original software disappears.

SituationRecommended choiceReason
Public REST APIJSONUniversal client support and readability
Microservices with gRPCProtocol BuffersCompact, typed, generated code
Event streaming at scaleAvro with a schema registryManaged evolution across many consumers
Embedded sensorsCBORSmall code size and payloads
Human-edited settingsYAML or TOMLComments and readable syntax
Decision guide for format selection

Benchmarks vary widely with payload shape and library quality, so teams should measure with realistic data rather than rely on published speed comparisons. Binary formats often shrink payloads by roughly 30 to 80 percent compared with JSON, but compression such as gzip narrows that gap considerably.

Risks and common mistakes

The most serious risk is insecure deserialization, where a format that can instantiate arbitrary classes lets an attacker craft input that runs code on the receiving system. Native object serializers such as Java serialization and Python pickle are the classic examples, and they must never accept untrusted input.

  • Precision loss: JSON numbers are often parsed as 64-bit floating point, so identifiers above 2^53 must be sent as strings.
  • Date ambiguity: timestamps without a time zone or a fixed format such as ISO 8601 are misread across regions.
  • Encoding drift: text written in one character set and read in another produces corrupted characters.
  • Unbounded input: deeply nested or very large messages can exhaust memory unless parsers enforce limits.
  • Tight coupling: exposing internal class layouts directly ties every consumer to one implementation.

A non-technical view

Imagine packing furniture for a move. Inside your home, a bookshelf stands assembled; to ship it, you take it apart, label each piece and write instructions. Data serialization does the same for information inside a computer. It flattens organized data into a sequence that can travel or be saved, and the receiver follows the instructions to rebuild the original structure.

Different packing methods suit different trips. Some are easy for anyone to read, like a printed list, while others are compact codes that only the right tool understands. Choosing the method decides speed, size and who can open it.

A concrete example

An online retailer runs a checkout service in Java and a warehouse system in Python. When a customer places an order, the checkout service serializes the order, with items, quantities, prices and address, into Protocol Buffers and publishes it to a message queue. The warehouse service deserializes the same bytes into its own Python objects without knowing anything about Java.

Six months later, the team adds a gift-wrap option as a new field with tag number 12. Older warehouse instances still running the previous schema simply ignore the unknown tag, while upgraded instances read it. The rollout happens without downtime or coordinated releases, and order messages shrink to about one third of their former JSON size, reducing queue storage costs.