Skip to content

Serialization Formats: JSON, Protobuf, MessagePack, Avro, CBOR, XML ​

"JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format." — Tim Bray (ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format, December 2017

Summary: Serialization turns an in-memory value into bytes and back; the format you pick decides what those bytes can say (types, names, schema, versions), how big and fast they are, and which bugs and attacks you inherit. Focus: The bytes: JSON's real rules (numbers, duplicates, UTF-8), XML/YAML/TOML, the Protobuf wire format, MessagePack, CBOR, Avro, zero-copy formats, BSON and DER, language-native formats and their RCE risk, schema evolution per format, and one Order measured in every format. Learning goal: Read a hex dump of JSON, MessagePack, CBOR, Protobuf or Avro; predict what survives a round trip (big integers, money, dates, unknown fields); pick a format per use case; and evolve a schema without breaking old readers.

This page owns serialization at the level of bytes: what each format puts on the wire or on disk, how a decoder reads it back, and what goes wrong. It deliberately stays below the layers that sit on top. Message envelopes, schema registries, compatibility modes and versioning strategy for events live in Message Design & Schema Evolution; gRPC as an RPC system, and REST vs GraphQL vs gRPC, in gRPC & Protocol Buffers. The Go APIs get a full walkthrough in JSON, XML, Struct Tags, Encoder/Decoder and gRPC & Protobuf in Go. Underneath, characters become bytes in Bits, Bytes & Text Encoding, binary inside text becomes Base64 in Binary-to-Text Encoding, bytes get smaller in Compression, and get verified in Checksums & Hashing. Certificates as DER bytes are taken apart in TLS in Practice.

Page map ​

If you are looking forGo to
One table of every format: model, schema, size, best useEverything in one minute
Why we serialize at all, and the trade-offsWhy serialization exists
RFC 8259, XML 1.0, CBOR, Avro, Protobuf originsWhere it comes from
Wire vs storage, text vs binary, self-describing vs schema-basedThe three axes
JSON numbers, 2^53, NaN, escaping, duplicate keys, JSON Lines, JSON5, canonical JSONJSON in depth
XML namespaces, XSD, XXE; YAML and TOML pitfallsXML, YAML and TOML
Varints, zigzag, tags, field numbers, unknown fields, presenceProtobuf wire format
MessagePack, CBOR, Avro, Thrift, FlatBuffers, Cap'n Proto, BSON, ASN.1 DERBinary formats
gob, PHP serialize(), Java serialization, pickleLanguage-native formats
Which library does what with big ints, duplicates, NaN, unknown fieldsPer-library behaviour
Annotated hex dumps, measured sizes and ns/op, streaming parsers, error messagesMechanics
Money, dates, blobs, 64-bit IDs, schema evolution, defensive decodingSolving the classic problems
Symptoms and fixesTroubleshooting
Which format for API, events, config, storage, RPC, browserChoosing a format
Monolith to distributed systemIn architecture
Encode one object in five formats, hexdump, evolve the schemaLab
Wrong beliefs, cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The formats. Sizes are the same Order (id, customer, two items, total, paid flag, timestamp, three signed adjustments) encoded by the Go programs on this page; see Measured sizes.

FormatText or binaryNeeds a schema to read?Our OrderTypical home
JSON (RFC 8259)Text, UTF-8No (names in every object)211 bytesPublic HTTP APIs, browsers, logs, config
XML 1.0TextNo; XSD optional for validation354 bytesSOAP, SAML, office documents, RSS, legacy B2B
YAML / TOMLTextNon/aConfig files written by humans
MessagePackBinaryNo (JSON-like model)148 bytes (map, compact ints), 48 (array mode)Redis/cache values, RPC between dynamic languages
CBOR (RFC 8949)BinaryNo (JSON model + tags)148 bytes (deterministic)WebAuthn/passkeys, COSE, IoT, constrained devices
ProtobufBinaryYes, to know names and types56 bytesgRPC, internal service APIs, Kafka events
AvroBinaryYes, the writer schema, always46 bytesKafka + schema registry, Hadoop/Parquet-adjacent files
ThriftBinaryYesnot measuredOlder Facebook-style RPC stacks
FlatBuffers / Cap'n ProtoBinary, zero-copyYesnot measuredGames, mobile, mmap'd files, very low latency
BSONBinaryNonot measuredMongoDB documents and wire protocol
ASN.1 DERBinary TLVYes (ASN.1 module)n/aX.509 certificates, keys, signatures
Go gob / PHP serialize() / Java / pickleBinary or textNo, but language-bound327 bytes (gob)Same-language caches only; never untrusted input

The five questions that pick a format.

QuestionIf yesIf no
Will a human read or edit it?JSON, YAML/TOML for configBinary is fine
Is the reader a browser or a third party you do not control?JSON (maybe CBOR for WebAuthn)Any format both sides agree on
Do you need the smallest bytes and fastest decode?Protobuf, Avro, FlatBuffersJSON is usually fast enough
Will the schema change while old data or old services exist?Protobuf or Avro with written evolution rulesAnything; still plan for it
Do you hash or sign the bytes?Deterministic encoding: CBOR core deterministic, JCS for JSONDefault encoders are fine

The six rules that prevent most incidents.

RuleWhy
Money as integer minor units or a decimal string, never a float0.1 + 0.2 is 0.30000000000000004 in every IEEE 754 parser
IDs above 2^53 travel as strings in JSONJavaScript JSON.parse rounds 9007199254740993 to 9007199254740992
Dates as RFC 3339 strings with an offset (2026-11-25T09:30:00+03:30)A bare 2026-11-25 09:30 has no time zone
Never deserialize untrusted bytes with a language-native formatPHP unserialize(), Java readObject, Python pickle can run code
Limit size, depth and element counts before decodingDecoders allocate what the bytes claim
Add fields, never reuse names or numbers; give new Avro fields defaultsThat is what keeps old and new code talking

Why serialization exists ​

A value in memory is a graph: a struct with pointers to a slice, strings stored somewhere on the heap, a map whose layout is private to the runtime. None of that can cross a socket or survive a restart, because addresses mean nothing in another process. Serialization (also called encoding or marshaling) flattens the graph into a sequence of bytes with agreed rules; deserialization (decoding, unmarshaling, parsing) builds an equivalent value from those bytes, possibly in another language on another machine years later. The OWASP cheat sheet puts it simply: "Serialization is the process of turning some object into a data format that can be restored later."

There are two places the bytes go, and they pull in different directions:

On the wire (RPC, HTTP, messages)In storage (files, databases, caches, logs)
Lives milliseconds to daysLives months to decades
Writer and reader usually run at nearby versionsThe reader may be ten schema versions newer than the writer
Size and encode/decode time matter per requestSize matters per terabyte; random access and scanning matter
Both ends can negotiate (Content-Type, gRPC)Nobody is around to negotiate; the bytes must explain themselves or point to their schema
Example: JSON over HTTP, Protobuf over gRPCExample: Avro container files, JSON Lines logs, a jsonb column

The basic trade-off is readability and flexibility against size, speed and safety:

Text, self-describing (JSON)Binary, schema-based (Protobuf, Avro)
curl and your eyes are the debuggerYou need protoc --decode, a registry or the code
Any reader can parse it without coordinationReader and writer must share the schema
Field names repeated in every recordField numbers or positions instead of names
Numbers as decimal text; meaning is up to each parserExact integer and float types
Easy to break silently (a renamed key just disappears)Evolution rules are explicit and checkable

The analogy we reuse on this page: shipping flat-pack furniture. You cannot mail an assembled wardrobe, so you take it apart and pack the pieces. Self-describing formats label every piece ("left door, oak, 180 cm"): anyone can reassemble it, but labels take space. Schema-based formats number the pieces ("part 7") and ship the assembly manual separately: the box is smaller, but without the right edition of the manual, part 7 is a mystery. Zero-copy formats ship the wardrobe in a crate shaped so you can use it without unpacking. Language-native formats include "assembly instructions" that the receiver follows blindly, which is how a malicious sender gets your workshop to build something else.

Three common misunderstandings, up front ​

  1. "JSON has integers." It has decimal numbers of any length. Whether 9007199254740993 survives depends on the parser: Go into float64, JavaScript and jq arithmetic round it; Python, Go with UseNumber and PHP (a native 64-bit int; JSON_BIGINT_AS_STRING for anything above PHP_INT_MAX) keep it.
  2. "Binary formats are unreadable, so they are secure." Protobuf and MessagePack are trivially decoded without a schema (see the protowire walker); obscurity is not a control. Security comes from limits, strict decoding and never using language-native formats on untrusted data.
  3. "Adding a field is always safe." Only if every reader ignores unknown fields (Protobuf does; a Go decoder with DisallowUnknownFields does not) and, in Avro, only if the new field has a default.

Where it comes from ​

ASN.1 is the oldest format still everywhere: X.509 certificates are ASN.1 values in DER, which RFC 5280 states directly: "the data that is to be signed is encoded using the ASN.1 distinguished encoding rules (DER) [X.690]. ASN.1 DER encoding is a tag, length, value encoding system for each element." XML 1.0 (W3C Recommendation, Fifth Edition dated 26 November 2008) brought a universal text syntax with namespaces and schema languages (XSD). JSON was defined by RFC 4627, revised as RFC 7159 and then RFC 8259 (December 2017), which made UTF-8 mandatory between systems; RFC 7493 (I-JSON, March 2015) is the strict profile for Internet protocols, and RFC 8785 (JCS) defines canonical JSON for hashing and signing. CBOR was RFC 7049 and is now RFC 8949 (December 2020); its abstract names its ancestors: its design goals "make it different from earlier binary serializations such as ASN.1 and MessagePack." MessagePack describes itself as "an object serialization specification like JSON." Protocol Buffers (protobuf.dev) and Thrift (Apache) came out of large companies' RPC stacks; Avro (Apache, spec 1.12.0 used here) came from the Hadoop world, where files outlive the programs that wrote them; FlatBuffers (created at Google "for game development and other performance-critical applications") and Cap'n Proto pushed the idea that the in-memory layout can be the wire format. YAML (1.2.2, 2021-10-01) and TOML (v1.0.0) are human-first configuration languages. Dates for the company-internal origins of Protobuf and Thrift are not stated on the pages read for this chapter, so they are not given here.

The three axes ​

Each block: plain words, the usual wrong belief, a precise definition, a sequence, real scenarios, what each product does, and the fix in code.

Serialization: memory to bytes and back Must-know ​

In plain words: you turn a value into bytes so it can leave the process, and turn bytes back into a value on the other side. Everything else on this page is about which bytes and which rules.

Common misunderstanding: "Decoding gives me back the same object." It gives you an equivalent value as far as the format can express it. Pointers and cycles are flattened (Go gob: "Pointers are not transmitted, but the things they point to are transmitted"), private fields are dropped, time.Time loses its monotonic clock, a Go map loses its type if decoded into any, and an integer can come back as a float.

Definition: a serialization format is a mapping from a data model (scalars, strings, bytes, lists, maps, records, unions) to a byte sequence, plus decoding rules. The wire format is that mapping used between processes; the storage format is the same or a different mapping used at rest. A codec is code that implements both directions for one language.

text
     Service A (Go)                          bytes                          Service B (PHP)
1    order := Order{ID: 1001, ...}
2    b, _ := json.Marshal(order)    ->  {"id":1001,"customer":"Sara",...}
3                                        (HTTP body, Kafka value, Redis key, file)
4                                                                     $o = json_decode($b, true, 32, JSON_THROW_ON_ERROR)
5                                                                     $o['id'] === 1001   // equivalent, not identical

Real scenario: an HTTP API (JSON both ways); a Kafka event read by five services in three languages (Avro or Protobuf); a Laravel queue job (JSON envelope around a PHP-serialized command); a Redis cache value (whatever the client serializer is set to); a PostgreSQL jsonb column; an X.509 certificate (DER).

Where bytes goTypical formatWho must agree
HTTP request/responseJSON (application/json), sometimes CBOR or ProtobufClient and server, by Content-Type
gRPC callProtobuf over HTTP/2Both sides via .proto
Kafka record valueAvro, Protobuf or JSON with a schema registry prefixProducers, consumers, the registry
Cache valueMessagePack, igbinary, PHP serialize, JSONEvery app version that reads the cache
Database columnjsonb, BSON, bytea holding ProtobufEvery service and migration that touches it

Fix / how to use it: decide the format per boundary, write the schema down even for JSON (OpenAPI or JSON Schema), and round-trip test it. The Go lab program verifies a round trip for every format before timing it (sameOrder in formats/main.go).

Text vs binary Must-know ​

In plain words: text formats are made of printable characters you can read in a terminal; binary formats use every byte value and need a tool to read.

Common misunderstanding: "Binary is always much smaller." Binary with field names in every record (MessagePack map mode, BSON, CBOR) is only 20 to 30 percent smaller than JSON for typical objects; the big win comes from dropping names (Protobuf tags, Avro positions, MessagePack array mode). And after gzip or zstd, JSON's repeated keys compress very well (see Compression).

Definition: a text format restricts its bytes to a character encoding (JSON: UTF-8 between systems; XML: declared encoding, UTF-8 or UTF-16 by default) and writes numbers as decimal digits. A binary format writes numbers as fixed-width or variable-length integers and IEEE 754 floats, lengths as prefixes, and raw bytes as-is.

text
     value 1001 written by each format (bytes from this page's lab)
1    JSON          31 30 30 31            "1001" as four ASCII digits
2    MessagePack   cd 03 e9               uint16 marker + 2 bytes   (compact mode)
3    CBOR          19 03 e9               major type 0, 2-byte argument
4    Protobuf      08 e9 07               tag(field 1, VARINT) + varint 1001
5    Avro          d2 0f                  zigzag varint 2002 = 1001, no tag at all

Real scenario: logs and audit trails (text: grep-able, durable); a mobile app on a slow network (binary halves the payload); a Redis cache holding millions of keys (binary saves memory); IoT sensors (CBOR, because "extremely small code size" is a design goal of RFC 8949).

PropertyText (JSON, XML, YAML)Binary (Protobuf, Avro, MessagePack, CBOR)
Debuggabilitycurl, jq, browser devtoolsxxd, protoc --decode_raw, cbor.Diagnose
Raw bytes (images, hashes)Must be Base64 (+33%)Native byte strings
Number fidelityParser-dependentExact type on the wire
Size of our Order211 to 354 bytes46 to 195 bytes
Parse costCharacter scanning, number parsingLength-prefixed, mostly memcpy

Fix / how to use it: default to JSON at public edges, binary inside, and measure before switching: the Go numbers in Measured sizes show JSON decoding at about 850 ns for this object, which is rarely the bottleneck behind a database call.

Self-describing vs schema-based Must-know ​

In plain words: a self-describing format carries field names and types inside the bytes, so any reader can make sense of them; a schema-based format carries only values (or numbers for fields) and the reader needs the schema to know what they mean.

Common misunderstanding: "Schema-based means the bytes contain the schema." Protobuf and Avro bytes contain no schema at all. Avro files (Object Container Files) embed the writer schema in a header, and Kafka messages carry a 4-byte schema ID that points to a registry, but a single Avro record is meaningless without its schema.

Definition: self-describing: decoding requires only the format spec (JSON, XML, MessagePack, CBOR, BSON, gob within one stream). Schema-based: decoding requires an external definition: a .proto (Protobuf), a JSON schema document (Avro), an IDL (Thrift, FlatBuffers, Cap'n Proto) or an ASN.1 module (DER). Protobuf is in between: the bytes say field number and wire type, so a reader can skip and preserve what it does not know; Avro is fully positional and cannot even skip without the writer schema.

Self-describing (names + types in the bytes)Schema-required (reader needs the schema)TEXTBINARYJSON (RFC 8259), JSON LinesXML 1.0 (+ namespaces)YAML, TOML (config files)CSV (header row only)human-readable, big, slow to parse,numbers and bytes are ambiguousProtoJSON (protobuf mapped to JSON)Avro JSON encodingJSON + JSON Schema, XML + XSDschema validates or maps names;bytes are still readable textMessagePack, CBOR (RFC 8949)BSON (MongoDB documents)Go gob (type info at stream start)Java serialization, pickle,PHP serialize() (language-native)compact JSON model; native onescan build objects: RCE riskProtobuf (tag = field number)Avro (no tags; schema resolution)Thrift (binary / compact protocol)ASN.1 DER (X.509 certificates)FlatBuffers, Cap'n Proto: zero-copysmallest and fastest; needs codegenor a registry to read the bytes
text
     Same record, three levels of self-description
1    JSON     {"id":1001,"customer":"Sara"}     names + types (as text)
2    Protobuf 08 e9 07 12 04 53 61 72 61        field numbers + wire types, no names
3    Avro     d2 0f 08 53 61 72 61              values only, in schema order

Real scenario: a data lake where files are read years later (Avro container files carry their schema); a partner integration where you cannot ship code to the other side (JSON + OpenAPI); service-to-service gRPC where both sides compile the same .proto.

FormatField identity on the wireCan an old reader skip a new field?
JSON, MessagePack, CBOR, BSONName stringYes, if the reader ignores unknown names
Protobuf, ThriftField number + wire typeYes, and Protobuf preserves it
AvroPosition in writer schemaOnly via schema resolution with both schemas
FlatBuffersvtable slotYes (append-only tables)
ASN.1 DERTag (type, sometimes context number)Only where the ASN.1 module has extension markers

Fix / how to use it: if bytes outlive their writer, either embed the schema (Avro files), embed a pointer to it (registry ID), or choose a self-describing format. For anything schema-based, version the schema in git and generate code from it.

JSON in depth ​

JSON looks too simple to have pitfalls. Its grammar is a page long; the trouble is everything the grammar leaves to each parser. RFC 8259 says so itself: "This specification allows implementations to set limits on the range and precision of numbers accepted."

Numbers are not integers: 2^53, NaN and precision Must-know ​

In plain words: a JSON number is just decimal digits. Most parsers turn it into a 64-bit float, and a float can only hold integers exactly up to 2^53 (9,007,199,254,740,992). Bigger IDs silently change.

Common misunderstanding: "My Go/PHP backend uses int64, so 64-bit IDs are fine in JSON." Your backend is fine; the JavaScript frontend, jq arithmetic and any Go code that decodes into any are not.

Definition: RFC 8259 §6: "numbers that are integers and are in the range [-(253)+1, (253)-1] are interoperable in the sense that implementations will agree exactly on their numeric values." It also forbids non-finite numbers: "Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted." Leading zeros, +1, .5 and 1. are invalid. I-JSON (RFC 7493) turns the advice into a rule for protocols: "it is RECOMMENDED to encode them in JSON string values."

text
     Producer (Go, int64)                      Consumer
1    {"id": 9007199254740993}       ->         JavaScript: JSON.parse(...).id      -> 9007199254740992
2                                              jq '.id + 0'                        -> 9007199254740992
3                                              Go json.Unmarshal into any          -> 9.007199254740992e+15
4                                              Go Decoder.UseNumber()              -> 9007199254740993
5                                              Python json.loads                   -> 9007199254740993
6                                              SQLite json_extract                 -> 9007199254740993

Every line above was run on the author's machine (node, jq 1.7.1, Go 1.27.4, Python 3, SQLite 3.54); see the Lab.

Real scenario: snowflake-style 64-bit IDs shown wrong in a web UI and the "edit" button updating a different row; a payment amount 19.99 stored as 19.989999999999998 after a float round trip; a Python service emitting NaN (json.dumps(float("nan")) prints NaN, which is not JSON) and a Go consumer failing with invalid character 'N'.

ParserBig integer (> 2^53)NaN/Infinity on inputDecimal fraction
JavaScript JSON.parseRounded to nearest doubleSyntax errorIEEE double
Go encoding/json into float64/anyRoundedError; Marshal(NaN) returns unsupported value: NaNfloat64
Go with UseNumber or into int64ExactErrorjson.Number string
PHP json_decodeExact up to PHP_INT_MAX; then float unless JSON_BIGINT_AS_STRINGSyntax errorfloat
Python jsonExact (arbitrary-precision int)Accepts and emits NaN by defaultfloat (use parse_float=Decimal)
PostgreSQL jsonbExact (numeric)Rejected ("NaN and infinity values are disallowed")numeric
jq 1.7Literal preserved, arithmetic roundsErrordouble

Fix / how to use it: IDs above 2^53 and money as strings (json:"id,string" in Go, (string) $this->id in a Laravel resource); UseNumber when decoding into any; never emit NaN. The Go snippet below runs every case:

go
// Command jsonpitfalls shows the encoding/json behaviours that bite in
// production: big integers, unknown fields, duplicate keys, omitempty,
// RawMessage envelopes, bytes, time, money and streaming tokens.
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strings"
	"time"
)

// Payment keeps money as a decimal string and IDs as strings on the wire.
type Payment struct {
	ID        int64     `json:"id,string"`           // "9007199254740993" survives JavaScript
	Amount    string    `json:"amount"`              // "19.99", parsed with a decimal library
	Currency  string    `json:"currency"`            // ISO 4217
	Note      string    `json:"note,omitempty"`      // dropped when ""
	Refunded  *bool     `json:"refunded,omitempty"`  // nil = absent, false = explicit
	Signature []byte    `json:"signature,omitempty"` // base64 in JSON
	PaidAt    time.Time `json:"paid_at"`             // RFC 3339 with offset
}

// Envelope delays decoding of data until the type is known.
type Envelope struct {
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
}

func main() {
	// 1. Numbers: any JSON number into interface{} becomes float64.
	var anyv map[string]any
	_ = json.Unmarshal([]byte(`{"id": 9007199254740993}`), &anyv)
	fmt.Printf("1. float64 id      = %.0f (sent 9007199254740993)\n", anyv["id"])

	dec := json.NewDecoder(strings.NewReader(`{"id": 9007199254740993}`))
	dec.UseNumber()
	_ = dec.Decode(&anyv)
	n := anyv["id"].(json.Number)
	i, _ := n.Int64()
	fmt.Println("   UseNumber id    =", i)

	// 2. Unknown fields are ignored unless you ask for strictness.
	strict := json.NewDecoder(strings.NewReader(`{"amount":"1.00","amount_typo":"2"}`))
	strict.DisallowUnknownFields()
	var p Payment
	fmt.Println("2. strict decode  =", strict.Decode(&p))

	// 3. Duplicate keys: v1 accepts them and the last one wins.
	var dup map[string]string
	_ = json.Unmarshal([]byte(`{"role":"user","role":"admin"}`), &dup)
	fmt.Println("3. duplicate keys =", dup["role"])

	// 4. omitempty, pointer presence, []byte as base64, time as RFC 3339.
	tehran := time.FixedZone("IRST", 3*3600+1800)
	out, _ := json.Marshal(Payment{
		ID: 9007199254740993, Amount: "19.99", Currency: "EUR",
		Refunded: new(bool), Signature: []byte{0xde, 0xad, 0xbe, 0xef},
		PaidAt: time.Date(2026, 11, 25, 9, 30, 0, 0, tehran),
	})
	fmt.Println("4. marshal        =", string(out))

	// 5. HTML escaping is on by default; turn it off for non-HTML consumers.
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.SetEscapeHTML(false)
	_ = enc.Encode(map[string]string{"q": "a<b && c>d", "name": "سارا"})
	def, _ := json.Marshal(map[string]string{"q": "a<b && c>d"})
	fmt.Print("5. no-escape      = ", buf.String())
	fmt.Println("   default        =", string(def))

	// 6. Envelope: read the type, then decode the payload into the right struct.
	var env Envelope
	_ = json.Unmarshal([]byte(`{"type":"payment","data":{"id":"7","amount":"5.00"}}`), &env)
	if env.Type == "payment" {
		var pay Payment
		_ = json.Unmarshal(env.Data, &pay)
		fmt.Println("6. envelope       =", env.Type, pay.ID, pay.Amount)
	}

	// 7. Streaming: walk a large array element by element with Token/More.
	stream := json.NewDecoder(strings.NewReader(`[{"amount":"1.00"},{"amount":"2.50"},{"amount":"3.75"}]`))
	_, _ = stream.Token() // consume '['
	count := 0
	for stream.More() {
		var row Payment
		if err := stream.Decode(&row); err != nil {
			panic(err)
		}
		count++
	}
	_, _ = stream.Token() // consume ']'
	fmt.Println("7. streamed rows  =", count)

	// 8. NaN and Inf have no JSON form.
	_, err := json.Marshal(map[string]float64{"x": zero() / zero()})
	fmt.Println("8. NaN            =", err)
}

func zero() float64 { return 0 }

Output (go1.27.4, darwin/arm64):

text
1. float64 id      = 9007199254740992 (sent 9007199254740993)
   UseNumber id    = 9007199254740993
2. strict decode  = json: unknown field "amount_typo"
3. duplicate keys = admin
4. marshal        = {"id":"9007199254740993","amount":"19.99","currency":"EUR","refunded":false,"signature":"3q2+7w==","paid_at":"2026-11-25T09:30:00+03:30"}
5. no-escape      = {"name":"سارا","q":"a<b && c>d"}
   default        = {"q":"a<b && c>d"}
6. envelope       = payment 7 5.00
7. streamed rows  = 3
8. NaN            = json: unsupported value: NaN

Strings, escaping and UTF-8 Important ​

In plain words: JSON strings are Unicode text in UTF-8. Only the quote, the backslash and control characters must be escaped; everything else, Persian included, may be written as-is.

Common misunderstanding: "سارا is a different, safer encoding of «سارا»." It is the same string after decoding; it is just 24 bytes instead of 8, and unreadable in logs. PHP escapes non-ASCII by default; JSON_UNESCAPED_UNICODE turns that off.

Definition: RFC 8259 §7: characters that "MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)." Characters outside the Basic Multilingual Plane are escaped as a UTF-16 surrogate pair (😀); I-JSON forbids unpaired surrogates. §8.1: "JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8" and "Implementations MUST NOT add a byte order mark (U+FEFF)". Go escapes <, > and & as < etc. by default so JSON can be embedded in HTML (SetEscapeHTML(false) disables it); PHP escapes / unless JSON_UNESCAPED_SLASHES.

text
     PHP json_encode(['name' => 'سارا', 'price' => 10.0])
1    flags 0                                    {"name":"سارا","price":10}
2    JSON_UNESCAPED_UNICODE                     {"name":"سارا","price":10}
3    + JSON_PRESERVE_ZERO_FRACTION              {"name":"سارا","price":10.0}
4    invalid UTF-8 byte in input, no flag       false (json_last_error) or JsonException with JSON_THROW_ON_ERROR

Real scenario: a Persian product catalog whose API responses triple in size from \u escapes; a CSV export opened in Excel showing «Ø³Ø§Ø±Ø§» because a BOM was missing there while JSON forbids one; a Go v1 decoder silently replacing invalid UTF-8 with U+FFFD while the v2 decoder (default in Go 1.27) rejects it.

BehaviourGo encoding/jsonPHP json_encodeJavaScript
Non-ASCII outputLiteral UTF-8\uXXXX unless JSON_UNESCAPED_UNICODELiteral
<, >, &Escaped unless SetEscapeHTML(false)Literal unless JSON_HEX_TAG/JSON_HEX_AMPLiteral
/Literal\/ unless JSON_UNESCAPED_SLASHESLiteral
Invalid UTF-8 inputv1: replaced with U+FFFD; v2: errorError unless JSON_INVALID_UTF8_IGNORE/_SUBSTITUTEn/a (strings are UTF-16)

Fix / how to use it: in Laravel set flags once (the JsonCodec class below, or jsonOptions() on a resource); in Go disable HTML escaping for non-HTML consumers; validate UTF-8 at the edge. The character-level details are in Bits, Bytes & Text Encoding.

Duplicate keys and member order Important ​

In plain words: {"role":"user","role":"admin"} is legal JSON syntax, and different parsers disagree on which value you get. An attacker who knows two services parse differently can make them see different requests.

Common misunderstanding: "Duplicate keys are a syntax error." RFC 8259 only says names "SHOULD be unique" and then: "When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates."

Definition: a parser differential is any input two parsers interpret differently. The Go encoding/json/v2 documentation spells out the attack: "If an attacker were able to maliciously craft a JSON request such that both services believe that the same request is from different users, it could bypass the authenticator". Object member order carries no meaning either: I-JSON says "The order of object members in an I-JSON message does not change the meaning".

text
     body = {"user":"alice","user":"mallory"}
1    gateway (SQLite-style, first wins)   -> authorises "alice"
2    gateway forwards the raw body
3    backend (Go v1 / PHP / Python / jq, last wins)  -> acts as "mallory"
     Measured: sqlite3 json_extract(... '$.role') -> user ; jq -c . -> {"role":"admin"}

Real scenario: authorization at an API gateway and execution in a backend; a signature computed over one parse and a business rule applied to another; a jsonb column (keeps last) next to a json column (keeps both) in PostgreSQL.

ImplementationDuplicate keysSource
Go encoding/json v1Accepted, last winsgo doc encoding/json ("In v1, a JSON object with duplicate names is permitted")
Go encoding/json/v2 (Go 1.27)Rejected: jsontext: duplicate object member name "a"measured
PHP json_decodeLast winsmeasured behaviour of PHP arrays
Python jsonLast wins (object_pairs_hook to detect)measured
jq 1.7.1Last winsmeasured
SQLite 3.54 json_extractFirst wins; json() keeps bothmeasured
PostgreSQL json / jsonbjson keeps all; jsonb keeps lastPostgreSQL docs
CBOR (fxamacker)Configurable: DupMapKeyEnforcedAPF rejectsgo doc
sql
-- PostgreSQL: the docs state that json keeps every pair, jsonb keeps only the last
SELECT '{"role":"user","role":"admin"}'::json  ->> 'role';   -- 'admin' (processing functions use the last)
SELECT '{"role":"user","role":"admin"}'::jsonb;              -- {"role": "admin"}
SELECT '{"amount": 19.99}'::jsonb -> 'amount';               -- 19.99 as numeric, exact
SELECT '{"x": NaN}'::jsonb;                                  -- ERROR: NaN is not valid JSON input

-- SQLite 3.54 (run on the author's machine)
SELECT json('{"role":"user","role":"admin"}');               -- {"role":"user","role":"admin"}
SELECT json_extract('{"role":"user","role":"admin"}','$.role'); -- user   (first wins!)

Fix / how to use it: reject duplicates at the edge (Go v2 by default; CBOR DupMapKeyEnforcedAPF; Python object_pairs_hook), parse once and pass the parsed value (not the raw body) downstream, and sign the exact bytes you verify.

JSON Lines, JSON5 and JSONC Good to know ​

In plain words: JSON Lines is one JSON value per line, for logs and streams. JSON5 and JSONC are JSON with comments (and in JSON5's case trailing commas, single quotes, hex numbers) for files that humans edit.

Common misunderstanding: "tsconfig.json and VS Code settings are JSON." They are JSONC; a strict JSON parser rejects their comments. And a file of pretty-printed objects separated by newlines is not JSON Lines.

Definition: JSON Lines: UTF-8, "Each Line is a Valid JSON Value", "Line Terminator is '\n'", no BOM; extension .jsonl. JSON5: "a superset of JSON that aims to alleviate some of the limitations of JSON by expanding its syntax to include some productions from ECMAScript 5.1". JSONC: "JSONC follows the same syntax rules as JSON with the addition of JavaScript style comments", and "Removing all comments MUST yield the same data representation of the JSON values."

text
     orders.jsonl (append-only, one record per line, streamable with a 64 KiB buffer)
1    {"id":"1001","total":"42.00","at":"2026-11-25T09:30:00Z"}
2    {"id":"1002","total":"7.50","at":"2026-11-25T09:31:12Z"}
3    -> `wc -l` counts records; `tail -f | jq -c .` follows them; a corrupt line loses one record, not the file

Real scenario: structured logs (Laravel's JSON formatter, Go log/slog JSON handler) shipped to Loki or Elasticsearch; bulk export/import files; LLM fine-tuning datasets; Elasticsearch _bulk bodies (NDJSON).

VariantCommentsTrailing commasStrict JSON parsers accept?Typical file
JSON (RFC 8259)NoNoYesAPI bodies
JSON Lines / NDJSONNoNoPer lineLogs, exports
JSONCYesTolerated by many toolsNotsconfig.json, VS Code settings
JSON5YesYesNoHand-written config

Fix / how to use it: stream JSON Lines with bufio.Scanner (raise its buffer for long lines) or json.Decoder in a loop; in PHP read with SplFileObject line by line. Never use JSON5/JSONC on the wire.

Canonical JSON: hashing and signing JSON Important ​

In plain words: the same object can be written as many different JSON texts (key order, spaces, 1.0 vs 1, escapes). If you hash or sign JSON, both sides must produce the exact same bytes, or the signature fails.

Common misunderstanding: "Go sorts map keys, so json.Marshal is canonical." Go sorts map keys, but struct fields follow declaration order, floats use Go's formatting, and HTML escaping changes <. Another language will produce different bytes for the same value.

Definition: RFC 8785 (JCS): "Cryptographic operations like hashing and signing need the data to be expressed in an invariant format so that the operations are reliably repeatable." JCS restricts data to I-JSON, sorts properties by UTF-16 code units, and serializes numbers and strings with ECMAScript rules. Alternatives: sign the raw bytes and transmit them as-is (JWS does this by Base64url-encoding the payload), or use a format with a defined deterministic encoding (CBOR §4.2, used by COSE and WebAuthn).

text
     Signer                                         Verifier
1    {"b":2,"a":1}  sign(sha256(bytes))   ->        parses, re-serializes as {"a":1,"b":2}
2                                                   sha256 differs -> "invalid signature"
3    Fix A: verifier hashes the RECEIVED bytes, then parses
4    Fix B: both sides canonicalize with JCS (RFC 8785) before hashing

Real scenario: webhook signatures (Stripe-style HMAC over the raw body); idempotency keys derived from a request hash; content-addressed caches; JWS/JWT (the payload is Base64url of fixed bytes, so no canonicalization is needed: see Password Hashing & Signed Tokens).

ApproachWhere usedCost
Hash the raw received bytesWebhooks, HTTP message signaturesMust keep the raw body before parsing
JCS (RFC 8785)Signed JSON documents, verifiable credentialsLibrary per language; numbers must be I-JSON
CBOR core deterministic encodingCOSE, WebAuthn (CTAP2 canonical)Binary
Protobuf "deterministic" modeNever for hashing across binariesprotobuf.dev: "Deterministic serialization only guarantees the same byte output for a particular binary."

Fix / how to use it: in Laravel, verify a webhook with hash_hmac('sha256', $request->getContent(), $secret) before calling $request->json(); in Go read the body into []byte, verify, then json.Unmarshal. The deterministic-CBOR example is in the safe decoding snippet.

XML, YAML and TOML ​

XML: namespaces, XSD and XXE Important ​

In plain words: XML is a tree of tagged elements with attributes. It is verbose, but it has mature schemas, namespaces to mix vocabularies, and signatures; it also has a feature (external entities) that turns a parser into a file reader for attackers.

Common misunderstanding: "XML is dead." SAML single sign-on, SOAP banking and government integrations, Office documents (.docx is zipped XML), SVG, RSS/Atom, Android layouts and Maven pom.xml are all XML today.

Definition: XML 1.0 defines well-formed documents; Namespaces in XML qualifies names with URIs (xmlns:inv="urn:example:invoice") so two vocabularies can share a document; XSD (XML Schema) validates structure and types. A DTD can declare entities, including external ones (SYSTEM "file:///etc/passwd"). OWASP: "XML External Entity (XXE) injection occurs when an XML processor resolves an external entity from untrusted input. This can expose local files, cause server-side request forgery (SSRF), or exhaust resources." The general advice: "Disable document type definitions (DTDs) whenever possible."

text
     Attacker                                     Server (PHP, LIBXML_NOENT enabled)
1    POST /invoice  Content-Type: application/xml
     <!DOCTYPE x [ <!ENTITY e SYSTEM "file:///etc/passwd"> ]>
     <invoice><note>&e;</note></invoice>
2                                                 parser substitutes &e; with the file contents
3                                                 app echoes "note" in its error message
4    reads /etc/passwd in the response            (same trick: SYSTEM "http://169.254.169.254/..." = SSRF)

Real scenario: SAML assertion parsing in an SSO integration; a supplier's XML invoice feed; "billion laughs" (nested entity expansion) taking a parser to gigabytes of memory; SOAP envelopes with WS-Security signatures.

ParserExternal entities by defaultSafe setting
Go encoding/xmlNot supported (no DTD processing)Default is safe; still limit input size
PHP libxml (DOM, SimpleXML)libxml ≥ 2.9: "entity substitution is disabled by default"Never pass LIBXML_NOENT/LIBXML_DTDLOAD; reject DOCTYPE
Java JAXPHistorically enabledDisallow doctype declarations (feature flag)
Python xml.etreeVaries by versionUse defusedxml

Fix / how to use it: reject DOCTYPE and parse with network access off; the PHP version is in SafeDecoding::parseXml() below. Use XML where an ecosystem demands it, JSON elsewhere.

YAML and TOML: config, not data exchange Important ​

In plain words: YAML and TOML are for files people write by hand. YAML guesses types from how a value looks, and old YAML 1.1 parsers guess badly: NO becomes false, 0644 becomes 420.

Common misunderstanding: "YAML is a superset of JSON, so it is a fine data format." Its implicit typing differs between YAML 1.1 and 1.2 parsers, it has anchors and aliases (references that can explode in size), and some loaders build arbitrary objects (PyYAML's unsafe loader is listed by OWASP). Use it for config, not for messages.

Definition: YAML 1.1's boolean type accepts y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF; its integer type accepts 0[0-7_]+ as octal and [1-9][0-9_]*(:[0-5]?[0-9])+ as base 60. YAML 1.2.2's Core schema narrows booleans to true|True|TRUE|false|False|FALSE and octal to 0o[0-7]+. Anchors (&base) and aliases (*base) let one node be reused. TOML v1.0.0 has explicit types (strings must be quoted, dates are first-class) and no references, which is why Rust (Cargo.toml) and Python (pyproject.toml) chose it.

text
     norway.yaml                     Ruby 2.6 Psych (YAML 1.1 rules), run on the author's machine
1    id: 1                           "id"      => 1
2    country: NO                     "country" => false        <- the Norway problem
3    mode: 0644                      "mode"    => 420          <- octal
4    port: 22:22                     "port"    => 80520        <- base-60 rule (the spec's arithmetic gives 1342; this parser differs)

Real scenario: a country list where Norway disappears; Docker Compose ports: - 22:22 written unquoted; Kubernetes manifests with on: true keys; a GitHub Actions workflow whose on: key is read as boolean by a 1.1 parser.

FormatTypesReferencesCommentsGood for
YAML 1.1 parsers (PyYAML, Psych, older go-yaml)Implicit, surprisingAnchors/aliasesYesExisting ecosystems; quote every string
YAML 1.2 Core schemaImplicit, sanerAnchors/aliasesYesKubernetes, CI config
TOML 1.0ExplicitNoneYesApp and package config
JSONExplicit, few typesNoneNoMachine-written config

Fix / how to use it: quote strings in YAML (country: "NO"), set a schema or use a 1.2 parser, cap alias expansion, use safe loaders only, and never accept YAML from users. Generate YAML from code if it must be produced at scale.

Protobuf wire format ​

Varints, tags, wire types and field numbers Must-know ​

In plain words: Protobuf writes each field as "field number + kind" followed by the value. Integers use as few bytes as they need. Field names never appear on the wire, only the numbers from your .proto file.

Common misunderstanding: "Renaming a field breaks old clients." Renaming is free on the wire (names are only in generated code, and in ProtoJSON). Changing a field number, or reusing one, is what breaks them: the proto3 guide says "Field numbers should never be reused" because "Reusing a field number makes decoding wire-format messages ambiguous."

Definition: from the encoding guide: varints "allow encoding unsigned 64-bit integers using anywhere between one and ten bytes, with small values using fewer bytes. Each byte in the varint has a continuation bit that indicates if the byte that follows it is part of the varint." A record's tag is a varint "formed from the field number and the wire type via the formula (field_number << 3) | wire_type". The six wire types are VARINT (0: int32, int64, uint32, uint64, sint32, sint64, bool, enum), I64 (1: fixed64, sfixed64, double), LEN (2: string, bytes, embedded messages, packed repeated fields), SGROUP/EGROUP (3, 4: deprecated groups) and I32 (5: fixed32, sfixed32, float). Field numbers range from 1 to 536,870,911, with 19,000 to 19,999 reserved; "field numbers in the range 1 through 15 take one byte to encode. Field numbers in the range 16 through 2047 take two bytes."

1. Varint: 150 = 0x96 0x01 (MSB = "more bytes follow")2. Record = tag (field number + wire type) then payload3. Tag byte and packed repeated sint32 (zigzag)1 00101100 000000108e9 07120453 61 72 613a05ab 0200ac 02drop the MSBs, reverse the 7-bit groups:0000001 0010110 = 128 + 16 + 4 + 2 = 1501 to 10 bytes per integer; small numbers are 1 byte.int32 -2 costs 10 bytes (two's complement); sint32 -2 is zigzag 3 = 1 byte.tag 1:VARINTid = 1001tag 2:LENlength 4"Sara" in UTF-8No field names on the wire: only numbers.Unknown numbers are skipped (and kept),so old readers survive new fields.Zero values are not written at all(implicit presence in proto3).field 7, LEN5 bytes299 = -1500300 = 150tag = (field_number << 3) OR wire_type0x3a = 0011 1010 = field 7, type 2 (LEN)wire types: 0 VARINT, 1 I64, 2 LEN, 5 I32zigzag: (n << 1) XOR (n >> 31)fields 1-15 use a 1-byte tag; 16-2047 use 2
text
     08 e9 07 12 04 53 61 72 61 1a 0e 0a 07 42 4f 4f 4b 2d 34 32 10 02 18 dc 0b ...
1    08            tag 0000 1000 -> field 1, wire type 0 (VARINT)
2    e9 07         varint: 0x69 + 0x07*128 = 105 + 896 = 1001             id = 1001
3    12 04         field 2, LEN, length 4
4    53 61 72 61   "Sara"                                                  customer
5    1a 0e         field 3, LEN, 14 bytes: an embedded Item message
6      0a 07 ...   Item.sku (field 1, LEN 7) "BOOK-42"
7      10 02       Item.qty (field 2, VARINT) = 2
8      18 dc 0b    Item.price_cents (field 3) = 0x5c + 11*128 = 1500
9    20 e8 20      field 4 = 4200 ; 28 01 field 5 = true ; 30 80 82 92 c9 06 field 6 = 1764000000
10   3a 05 ab 02 00 ac 02   field 7, packed sint32: zigzag 299, 0, 300 -> -150, 0, 150

Real scenario: gRPC request and response bodies; Kafka events with a Protobuf schema in Confluent Schema Registry; Google Cloud APIs; Envoy configuration; mobile apps that need small payloads.

Proto typeWire typeEncodingNote
int32, int64VARINTTwo's complement as unsigned varintNegative numbers always take 10 bytes
sint32, sint64VARINTZigZag then varintUse for fields that are often negative
uint32, uint64, bool, enumVARINTVarintbool and enum encode like int32
fixed32, sfixed32, floatI324 bytes little-endian"More efficient than uint32 if values are often greater than 2^28"
fixed64, sfixed64, doubleI648 bytes little-endianHashes, random IDs
string, bytes, messages, packed repeatedLENVarint length + bytesStrings must be valid UTF-8 in proto3

Fix / how to use it: keep hot fields at numbers 1 to 15, use sint32/sint64 for signed deltas, and never change a number: delete the field and add reserved 6; reserved "created_unix"; instead. The wire snippet builds and walks the bytes with google.golang.org/protobuf/encoding/protowire:

go
// Command wire builds protobuf bytes by hand with protowire and then walks
// any protobuf message tag by tag, the way protoscope or `protoc --decode_raw` does.
package main

import (
	"encoding/hex"
	"fmt"

	orderv1 "academy/serialization-formats/orderpb/v1"

	"google.golang.org/protobuf/encoding/protowire"
	"google.golang.org/protobuf/proto"
)

func main() {
	// 1. The classic example from protobuf.dev: field 1 = 150 -> 08 96 01.
	var b []byte
	b = protowire.AppendTag(b, 1, protowire.VarintType) // (1 << 3) | 0 = 0x08
	b = protowire.AppendVarint(b, 150)                  // 0x96 0x01
	fmt.Println("field 1 = 150      ->", hex.EncodeToString(b))

	// 2. int32 -2 uses ten bytes (two's complement as uint64); sint32 -2 uses one.
	minusTwo := int64(-2)
	neg := protowire.AppendVarint(nil, uint64(minusTwo))
	zz := protowire.AppendVarint(nil, protowire.EncodeZigZag(minusTwo))
	fmt.Printf("int32 -2  varint   -> %s (%d bytes)\n", hex.EncodeToString(neg), len(neg))
	fmt.Printf("sint32 -2 zigzag   -> %s (%d bytes)\n", hex.EncodeToString(zz), len(zz))

	// 3. Field numbers 1..15 fit in a one-byte tag, 16..2047 need two.
	fmt.Println("tag size field 15  ->", protowire.SizeTag(15))
	fmt.Println("tag size field 16  ->", protowire.SizeTag(16))

	// 4. Walk a real message without its schema.
	msg := &orderv1.Order{
		Id: 1001, Customer: "Sara", TotalCents: 4200, Paid: true,
		Adjustments: []int32{-150, 0, 150},
	}
	raw, err := proto.Marshal(msg)
	if err != nil {
		panic(err)
	}
	fmt.Println("order bytes        ->", hex.EncodeToString(raw))
	walk(raw, "")
}

// walk prints field number, wire type and payload for every record.
func walk(b []byte, indent string) {
	for len(b) > 0 {
		num, typ, n := protowire.ConsumeTag(b)
		if n < 0 {
			fmt.Println(indent, "bad tag:", protowire.ParseError(n))
			return
		}
		b = b[n:]
		switch typ {
		case protowire.VarintType:
			v, m := protowire.ConsumeVarint(b)
			fmt.Printf("%s%d:VARINT %d\n", indent, num, v)
			b = b[m:]
		case protowire.Fixed32Type:
			v, m := protowire.ConsumeFixed32(b)
			fmt.Printf("%s%d:I32 %d\n", indent, num, v)
			b = b[m:]
		case protowire.Fixed64Type:
			v, m := protowire.ConsumeFixed64(b)
			fmt.Printf("%s%d:I64 %d\n", indent, num, v)
			b = b[m:]
		case protowire.BytesType:
			v, m := protowire.ConsumeBytes(b)
			fmt.Printf("%s%d:LEN %d bytes %q\n", indent, num, len(v), v)
			b = b[m:]
		default:
			fmt.Println(indent, "group or unknown wire type", typ)
			return
		}
	}
}
text
field 1 = 150      -> 089601
int32 -2  varint   -> feffffffffffffffff01 (10 bytes)
sint32 -2 zigzag   -> 03 (1 bytes)
tag size field 15  -> 1
tag size field 16  -> 2
order bytes        -> 08e90712045361726120e82028013a05ab0200ac02
1:VARINT 1001
2:LEN 4 bytes "Sara"
4:VARINT 4200
5:VARINT 1
7:LEN 5 bytes "\xab\x02\x00\xac\x02"

ZigZag and packed repeated fields Important ​

In plain words: a varint is cheap for small positive numbers but expensive for negative ones, because negatives look huge as unsigned numbers. ZigZag maps -1, 1, -2, 2 to 1, 2, 3, 4 so small negatives stay small. "Packed" puts a whole list of numbers in one length-prefixed record instead of one tag per number.

Common misunderstanding: "int32 is fine for a temperature delta of -2." It costs 10 bytes per value; sint32 costs 1.

Definition: "Positive integers p are encoded as 2 * p (the even numbers), while negative integers n are encoded as 2 * |n| - 1 (the odd numbers)", computed as (n << 1) ^ (n >> 31) for sint32. The proto3 guide: "In proto3, repeated fields of scalar numeric types use packed encoding by default": one LEN record containing the concatenated values. Parsers must accept both packed and unpacked forms, which "permits adding [packed=true] to existing fields in a forward- and backward-compatible way."

text
     repeated sint32 adjustments = 7;   value [-150, 0, 150]
1    zigzag: -150 -> 299, 0 -> 0, 150 -> 300
2    varints: 299 -> ab 02 ; 0 -> 00 ; 300 -> ac 02
3    packed record: 3a (field 7, LEN) 05 (5 bytes) ab 02 00 ac 02     = 7 bytes
4    unpacked would be: 38 ab 02 38 00 38 ac 02                       = 8 bytes and a tag per element

Real scenario: sensor deltas, price changes, geo coordinate offsets, time-series compression; Avro uses zigzag for every int and long (the spec: "int and long values are written using variable-length zig-zag coding").

FormatSigned integer encoding
Protobuf int32/int64Two's complement varint (10 bytes if negative)
Protobuf sint32/sint64, Avro int/long, Thrift compactZigZag varint
MessagePackType byte + 1/2/4/8 bytes (negative fixint for -32..-1)
CBORMajor type 1 stores -1 - n with the same short arguments as positives

Fix / how to use it: choose sint* for anything that is often negative; let proto3 pack scalars by default.

Unknown fields, default values and presence Must-know ​

In plain words: an old program that receives a field it has never heard of keeps the bytes and writes them back out. A field set to zero, "" or false is not written at all, so the reader cannot tell "zero" from "missing" unless the field is declared optional.

Common misunderstanding: "If the client did not send paid, I will see null." In proto3 without optional you see false: "there's no way of telling whether that field was explicitly set to the default value (for example whether a boolean was set to false) or just not set at all".

Definition: "Unknown fields are well-formed Protobuf serialized data representing fields that the parser does not recognize." "Proto3 messages preserve unknown fields and include them during parsing and in the serialized output". They are lost when you "Serialize a proto to JSON" or copy field by field. Default values: empty string, empty bytes, false, zero, first enum value (must be 0), empty repeated/map. Fields marked optional, message fields and oneofs have explicit presence (HasX()/X != nil in Go). Last one wins: "if the same field appears multiple times, the parser accepts the last value it sees", and embedded messages are merged.

text
     orders-api v2 (has field 8 coupon)   ->   audit-svc v1 (no field 8)   ->   billing v2
1    Order{id:8, coupon:"NOWRUZ"}  bytes ... 42 06 4e 4f 57 52 55 5a
2                                              unknown bytes = 42064e4f5752555a (kept)
3                                              re-marshals and forwards
4                                                                                coupon = "NOWRUZ" (preserved)
     Measured with orderpb/v1 and orderpb/v2 in evolve/main.go.

Real scenario: a proxy or audit service on an old schema forwarding new messages without loss; a feature flag bool disable_x that is "set" by every old client because false is the default; a price of 0 (free) indistinguishable from "not provided".

SituationProto3 implicit presenceProto3 optional / message field
Value equals defaultNot on the wireWritten
Reader asks "was it set?"ImpossibleHasX() / pointer not nil
JSON mapping (ProtoJSON)Field omittedField present
Old reader sees new fieldKept as unknownKept as unknown

Fix / how to use it: mark fields optional when zero is meaningful (price, quantity, toggles); keep unknown fields by using binary, not JSON, between hops; regenerate code from the same .proto in every service.

Binary formats ​

MessagePack: JSON's model in binary Important ​

In plain words: MessagePack is JSON's data model (nil, bool, int, float, string, binary, array, map) written in binary with type bytes, plus "extension types" for your own types. No schema needed.

Common misunderstanding: "MessagePack is always much smaller than JSON." With map-encoded structs it keeps every field name. Our Order is 195 bytes with vmihailenco/msgpack defaults (it writes Go int64 as a fixed 9-byte d3 int 64), 148 with UseCompactInts(true), and only 48 with array-encoded structs plus compact ints, which drops the names and couples reader and writer to field order.

Definition: "MessagePack is an object serialization specification like JSON." Each value starts with a type byte; small values are packed into it (positive fixint 0x00–0x7f, fixmap 0x80–0x8f, fixarray 0x90–0x9f, fixstr 0xa0–0xbf, nil 0xc0, false 0xc2, true 0xc3). Limits: integers "from -(2^63) upto (2^64)-1", strings and binaries up to (2^32)-1 bytes. Extension types: "Applications can assign 0 to 127 to store application-specific type information"; "-1 to -128" are reserved, and -1 is the predefined Timestamp.

text
     msgpack, map mode, compact ints (first 32 bytes of our Order)
1    87                      fixmap, 7 entries
2    a2 69 64                fixstr(2) "id"
3    cd 03 e9                uint16 1001
4    a8 63 75 73 74 6f 6d 65 72   fixstr(8) "customer"
5    a4 53 61 72 61          fixstr(4) "Sara"
6    a5 69 74 65 6d 73       fixstr(5) "items"
7    92 83 ...               fixarray(2) of fixmap(3) ...

Real scenario: Redis values from PhpRedis (Redis::SERIALIZER_MSGPACK in Laravel's Redis options); a job payload shared by a PHP producer and a Go worker without a schema; caching API responses compactly; any place JSON's model fits but its text overhead does not.

LibraryLanguageNotes
github.com/vmihailenco/msgpack/v5GoStruct tags msgpack:"...", UseCompactInts, UseArrayEncodedStructs, RegisterExt, DisallowUnknownFields
rybakit/msgpackPHP (pure)Packer/BufferUnpacker, TimestampExtension, default max depth 128
PECL msgpackPHP (C extension)msgpack_pack()/msgpack_unpack(); PhpRedis serializer
@msgpack/msgpackJavaScriptBrowser and Node

Fix / how to use it: pin encoder options in one shared helper (compact ints, map vs array mode) across services; prefer map mode unless both sides are generated from the same struct.

CBOR: RFC 8949, COSE and WebAuthn Important ​

In plain words: CBOR is an IETF-standard binary JSON with byte strings, tags (dates, big numbers, URIs) and a defined deterministic encoding, which is why security protocols use it.

Common misunderstanding: "CBOR and MessagePack are the same thing." They share the idea, but CBOR is an RFC with a tag registry, a diagnostic notation, well-formedness and validity rules, and a deterministic encoding; MessagePack has none of these.

Definition: each item's first byte holds "the major type (the high-order 3 bits ...) and additional information (the low-order 5 bits)": 0 unsigned int, 1 negative int, 2 byte string, 3 text string, 4 array, 5 map, 6 tag, 7 floats and simple values. Arguments under 24 live in the first byte; 24 to 27 mean 1, 2, 4 or 8 following bytes. Core deterministic encoding (§4.2.1): shortest arguments, no indefinite lengths, and "The keys in every map MUST be sorted in the bytewise lexicographic order of their deterministic encodings." COSE (RFC 9052) "describes how to create and process signatures, message authentication codes, and encryption using CBOR"; WebAuthn requires "All CBOR encoding performed by the members of the above conformance classes MUST be done using the CTAP2 canonical CBOR encoding form" and decoders "SHOULD reject messages with duplicate map keys."

text
     cbor.CoreDetEncOptions(), our Order (first bytes)
1    a7                  map(7)
2    62 69 64            text(2) "id"        19 03 e9   uint, 2-byte argument = 1001
3    64 70 61 69 64      text(4) "paid"      f5         true
4    65 69 74 65 6d 73   text(5) "items"     82 a3 ...  array(2) of map(3)
     keys come out id, paid, items, customer, ... : sorted by encoded bytes, so shorter keys first

Real scenario: passkeys/WebAuthn attestation objects and COSE public keys (WebAuthn §2.4 above); COSE-signed tokens and certificates; constrained IoT devices where code size matters ("extremely small code size" is an RFC 8949 design goal).

Option in fxamacker/cbor/v2Effect
CoreDetEncOptions()RFC 8949 §4.2.1 deterministic encoding
CanonicalEncOptions()RFC 7049 canonical (length-first key sort)
DecOptions{DupMapKey: DupMapKeyEnforcedAPF}Reject duplicate map keys
MaxNestedLevels, MaxArrayElements, MaxMapPairsResource limits before allocation
cbor.Diagnose(b)Diagnostic notation, e.g. {"a": 1, "b": 2}

Fix / how to use it: for anything signed, encode deterministically and decode with duplicate rejection; the safe decoding snippet does both.

Avro: the schema travels separately Must-know ​

In plain words: Avro writes only the values, in schema order, with no field numbers and no names. To read, you need the exact schema the writer used, and you may also give your own (newer or older) schema; Avro resolves the two by field name.

Common misunderstanding: "Avro is like Protobuf with JSON schemas." Protobuf bytes can be skipped and partially read without the schema; Avro bytes cannot even be split into fields without the writer schema. That is why Kafka puts a schema ID in front of every Avro message and why Avro files embed the schema.

Definition: schemas are JSON (records, enums, arrays, maps, unions, fixed, plus logical types such as decimal, timestamp-millis, uuid). Binary encoding: zigzag varints for int/long, length-prefixed strings and bytes, arrays and maps in blocks (a negative count is followed by the block's byte size), unions as a branch index. Schema resolution: "if the writer's record contains a field with a name not present in the reader's record, the writer's value for that field is ignored"; "if the reader's record schema has a field that contains a default value, and writer's schema does not have a field with the same name, then the reader should use the default value"; without a default, "an error is signalled." Single-object encoding prefixes "A two-byte marker, C3 01" and "The 8-byte little-endian CRC-64-AVRO fingerprint of the object's schema"; container files hold a header with the schema and a "16-byte, randomly-generated sync marker".

text
     Avro binary of our Order (46 bytes), decoded by hand
1    d2 0f            long id: zigzag 2002 -> 1001
2    08 53 61 72 61   string: length zigzag 8 -> 4, "Sara"
3    03 28            items block: count zigzag 3 -> -2 (negative: 2 items follow), block size 0x28 -> 20 bytes
4    0e 42..32 04 b8 17     sku "BOOK-42", qty 2, price_cents zigzag 3000 -> 1500
5    0a 50..37 14 f0 01     sku "PEN-7", qty 10, price_cents 120
6    00               end of array
7    d0 41  01  80 84 a4 92 0d      total_cents 4200, paid true, created_unix 1764000000
8    05 0a ab 02 00 ac 02 00        adjustments: count -3, 5 bytes, -150 0 150, end

Real scenario: Kafka topics with Confluent Schema Registry ("each message starts with a version byte, a 4-byte schema ID ... followed by the data"); Hadoop and Spark data files; Kafka Connect and Debezium CDC events; long-term event archives.

Avro changeOld data, new reader (backward)New data, old reader (forward)
Add field with defaultOK (default used)OK (field ignored)
Add field without defaultErrorOK
Remove field that had a defaultOKOK (old reader uses its default)
Rename fieldError unless the reader declares aliasesError unless aliases
int to longOK (promotion)Error

Fix / how to use it: always resolve with both schemas (avro.NewSchemaCompatibility().Resolve(reader, writer) in hamba/avro); reading with the wrong schema silently misreads bytes: in the lab, decoding v1 bytes with the v2 schema and no resolution produced total=-2 before failing. Give every new field a default.

Thrift, FlatBuffers and Cap'n Proto: zero-copy and friends Good to know ​

In plain words: Thrift is Protobuf's sibling (IDL, field IDs, binary and compact protocols). FlatBuffers and Cap'n Proto lay data out so you can read fields straight from the received buffer without building objects first: zero-copy.

Common misunderstanding: "Zero-copy means free." You still pay for building the buffer, larger sizes (alignment padding, offsets), and API ergonomics (accessors instead of plain structs). Cap'n Proto's own page calls its "INFINITY TIMES faster" benchmark "of course, unfair. It is only measuring the time to encode and decode a message in memory."

Definition: Thrift: an IDL with numbered fields and pluggable protocols; the compact protocol uses ZigZag varints and field-ID deltas. FlatBuffers: "Access to serialized data without parsing/unpacking", tables with vtables of offsets so fields can be added at the end. Cap'n Proto: "there is no encoding/decoding step", the encoding "is appropriate both as a data interchange format and an in-memory representation". Both need generated code.

text
     Protobuf decode                         FlatBuffers / Cap'n Proto read
1    bytes -> allocate Order, Items, strings     bytes stay as they are
2    copy every field                            order.Customer() reads offset -> slice of the buffer
3    use the struct                              only touched fields cost anything

Real scenario: game state and assets (the use FlatBuffers was created for); mobile apps loading large read-only data files via mmap; IPC between processes on one host sharing a buffer; very hot read paths where only a few fields of a large message are touched.

FormatSchemaRandom field access without full decodeEvolution
ThriftIDL, field IDsNoLike Protobuf
FlatBuffers.fbs, vtablesYesAppend fields, deprecate, never remove/reorder
Cap'n Proto.capnp, ordinal @NYesAdd fields with new ordinals
Protobuf.protoNoField numbers

Fix / how to use it: reach for zero-copy only when profiling shows decode/allocation dominates and messages are large or read partially.

BSON and ASN.1/DER Good to know ​

In plain words: BSON is MongoDB's binary JSON with extra types (ObjectId, dates, Decimal128, binary) and length prefixes for fast skipping. ASN.1 DER is the tag-length-value format inside every TLS certificate.

Common misunderstanding: "BSON is a compact JSON." Every document and string carries a length prefix and integers are fixed width (4 or 8 bytes), so it is not designed for size; it is designed for fast traversal (skip a sub-document by its length) and rich types.

Definition: BSON: "a binary format in which zero or more ordered key/value pairs are stored as a single entity. We call this entity a document." DER: the Distinguished Encoding Rules of X.690, a TLV encoding with exactly one valid encoding per value, so signatures over it are stable. See the certificate dump in the lab and TLS in Practice.

text
     openssl req -x509 ... -outform DER -out lab.der ; xxd lab.der | head -2  (run on the author's machine)
00000000: 3082 0201 3082 01a6 0209 00e3 46bf 3d56  0...0.......F.=V
00000010: b64b 4830 0a06 082a 8648 ce3d 0403 0230  .KH0...*.H.=...0
1    30 82 02 01    SEQUENCE, length in 2 bytes = 513            (Certificate)
2    30 82 01 a6    SEQUENCE, length 422                         (TBSCertificate)
3    02 09 00 e3..  INTEGER, 9 bytes                             (serial number)
4    30 0a 06 08 2a 86 48 ce 3d 04 03 02   SEQUENCE { OID 1.2.840.10045.4.3.2 }   (ecdsa-with-SHA256)

Real scenario: MongoDB documents and the driver wire protocol (see MongoDB); X.509 certificates, PKCS#8 private keys, ECDSA signatures in JWTs (DER inside JOSE is converted to raw r‖s), LDAP, SNMP.

FormatSelf-describingDeterministicWhere you meet it
BSONYesNo (field order preserved, not sorted)MongoDB storage and wire protocol
ASN.1 BERWith the ASN.1 moduleNo (several encodings per value)LDAP, SNMP
ASN.1 DERWith the ASN.1 moduleYesX.509, keys, signatures

Fix / how to use it: never hand-parse DER; use crypto/x509 in Go and openssl_x509_parse() in PHP; openssl asn1parse to inspect.

Language-native formats ​

gob, PHP serialize(), Java serialization and pickle Must-know ​

In plain words: most languages can dump their own objects to bytes. It is convenient inside one program, but the bytes can tell the decoder to build any class, and some classes run code when built or destroyed. Feeding attacker bytes into these decoders has led to remote code execution again and again.

Common misunderstanding: "allowed_classes => false makes unserialize() safe." The PHP manual says: "Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes." The same holds for Python: "The pickle module is not secure. Only unpickle data you trust."

Definition: PHP serialize() writes a type-tagged text format (a:2:{s:2:"id";i:1001;...}, objects as O:5:"Order":...); unserialize() instantiates classes and calls magic methods (__wakeup, __unserialize, later __destruct), so chains of existing classes ("gadget chains") can reach file writes or command execution. Java ObjectInputStream.readObject has the same shape; JEP 290 added filters to "Allow incoming streams of object-serialization data to be filtered in order to improve both security and robustness." Python pickle is a small stack-machine program. Go gob cannot construct arbitrary types (it only fills the Go type you pass), but its docs warn: "This package is not designed to be hardened against adversarial inputs" and "its limits are not configurable".

text
     Attacker with the APP_KEY of a Laravel 5.6.29 app (CVE-2018-15133)
1    builds a PendingBroadcast gadget chain with phpggc, serializes it
2    encrypts it with the leaked key, sends it as the X-XSRF-TOKEN header
3    Encrypter::decrypt() calls unserialize() on the decrypted value
4    __destruct of the gadget runs a command                             -> RCE
     NVD: "remote code execution might occur as a result of an unserialize call on a potentially untrusted X-XSRF-TOKEN value"

Real scenario: PHP object injection through cookies or hidden form fields; Java RMI/JMX endpoints; ML models distributed as pickle files; Redis caches written with serialize() and read by a newer app version where a class was renamed (__PHP_Incomplete_Class).

FormatBuilds arbitrary types?Safe for untrusted input?Safe use
PHP serialize()/unserialize()YesNoYour own cache/session data, HMAC-verified, allowed_classes => false
Java SerializableYesNoOnly with JEP 290 allowlist filters; prefer JSON/Protobuf
Python pickleYesNoSame-trust-domain only
Go gobNo, only the target typeNot hardened; size limits not configurableSame-program caches, Go-to-Go RPC (net/rpc)
PyYAML unsafe loader, jsonpickleYesNoUse yaml.safe_load

Fix / how to use it: JSON (or Protobuf) at every trust boundary. In Laravel, queued jobs are still PHP-serialized inside the JSON payload, which is fine because only your app writes the queue; keep APP_KEY secret and rotate it if leaked. The PHP pattern for data you wrote yourself is HMAC first, then unserialize($payload, ['allowed_classes' => false, 'max_depth' => 32]).

Per-library behaviour ​

BehaviourGo encoding/json (v1 API)Go encoding/json/v2PHP json_*JavaScript JSONPython jsonPostgreSQL jsonb
Unknown fields into a struct/classIgnored; DisallowUnknownFields() rejectsIgnored; RejectUnknownMembers optionn/a (arrays)n/an/an/a
Duplicate keysLast winsError by defaultLast winsLast winsLast winsLast wins
Integer > 2^53Exact into int64; rounded into float64/anySameExact to PHP_INT_MAX, then float or string (JSON_BIGINT_AS_STRING)RoundedExactExact
NaN / InfinityErrorErrorError (JSON_ERROR_INF_OR_NAN)null on stringifyEmitted as NaN (invalid JSON)Rejected
Invalid UTF-8Replaced with U+FFFD (v1 semantics)ErrorError unless JSON_INVALID_UTF8_*n/aErrorError
Case-insensitive key matchYes (v1 semantics)No (exact)n/an/an/an/a
Max nesting depth1000010000512 default, $depth argumentEngine stackRecursion limitConfigurable stack
[]byte / binaryBase64 stringBase64 stringMust encode yourselfn/aMust encode yourselfbytea separately

Go 1.27 made encoding/json/v2 a regular package and moved v1 onto the v2 implementation; the release notes: "The v2 package chooses stricter, more interoperable defaults than v1: it rejects invalid UTF-8 in JSON strings and rejects duplicate names within a JSON object." The v1 API keeps v1 behaviour.

Format / library (Go)Import pathKey APIs used on this page
JSONencoding/jsonMarshal, NewDecoder, UseNumber, DisallowUnknownFields, Token/More, RawMessage, SetEscapeHTML
Protobufgoogle.golang.org/protobuf/proto, .../encoding/protowireproto.Marshal, proto.Unmarshal, ProtoReflect().GetUnknown(), protowire.AppendTag, ConsumeTag
MessagePackgithub.com/vmihailenco/msgpack/v5Marshal, NewEncoder, UseCompactInts, UseArrayEncodedStructs
CBORgithub.com/fxamacker/cbor/v2CoreDetEncOptions().EncMode(), DecOptions{...}.DecMode(), Diagnose
Avrogithub.com/hamba/avro/v2MustParse, Marshal, Unmarshal, NewSchemaCompatibility().Resolve
gob, XMLencoding/gob, encoding/xmlNewEncoder(...).Encode, xml.Marshal
Format / library (PHP, Laravel 13)PackageKey APIs
JSONcore ext-jsonjson_encode/json_decode flags, JsonException
Laravelilluminate/httpJsonResource::toArray, jsonOptions(), withoutWrapping(), whenLoaded; Jsonable::toJson; response()->json()
MessagePackrybakit/msgpack or PECL msgpackPacker::pack, BufferUnpacker::unpack($maxDepth), msgpack_pack
Protobufgoogle/protobuf (+ optional C extension)serializeToString, mergeFromString, serializeToJsonString, discardUnknownFields
Redis valuesPhpRedisRedis::SERIALIZER_JSON, SERIALIZER_IGBINARY, SERIALIZER_MSGPACK

Mechanics ​

One Order, byte by byte ​

All dumps come from go run ./formats -hex <name> in docs/snippets/foundations/serialization-formats/go, on go1.27.4 darwin/arm64. The model and the Avro schema are shared:

go
// Package model holds the one Order value every format on the page encodes.
package model

import "encoding/xml"

// Item is one order line. Money is integer cents, never float.
type Item struct {
	SKU        string `json:"sku" msgpack:"sku" cbor:"sku" avro:"sku" xml:"sku"`
	Qty        int32  `json:"qty" msgpack:"qty" cbor:"qty" avro:"qty" xml:"qty"`
	PriceCents int64  `json:"price_cents" msgpack:"price_cents" cbor:"price_cents" avro:"price_cents" xml:"price_cents"`
}

// Order uses the same field names in every format so sizes are comparable.
type Order struct {
	XMLName     xml.Name `json:"-" msgpack:"-" cbor:"-" avro:"-" xml:"order"`
	ID          int64    `json:"id" msgpack:"id" cbor:"id" avro:"id" xml:"id,attr"`
	Customer    string   `json:"customer" msgpack:"customer" cbor:"customer" avro:"customer" xml:"customer"`
	Items       []Item   `json:"items" msgpack:"items" cbor:"items" avro:"items" xml:"items>item"`
	TotalCents  int64    `json:"total_cents" msgpack:"total_cents" cbor:"total_cents" avro:"total_cents" xml:"total_cents"`
	Paid        bool     `json:"paid" msgpack:"paid" cbor:"paid" avro:"paid" xml:"paid"`
	CreatedUnix int64    `json:"created_unix" msgpack:"created_unix" cbor:"created_unix" avro:"created_unix" xml:"created_unix"`
	Adjustments []int32  `json:"adjustments" msgpack:"adjustments" cbor:"adjustments" avro:"adjustments" xml:"adjustments>a"`
}

// AvroSchemaV1 is the writer schema for Order. Avro needs it to read bytes.
const AvroSchemaV1 = `{
  "type": "record", "name": "Order", "namespace": "academy.lab",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "customer", "type": "string"},
    {"name": "items", "type": {"type": "array", "items": {
      "type": "record", "name": "Item",
      "fields": [
        {"name": "sku", "type": "string"},
        {"name": "qty", "type": "int"},
        {"name": "price_cents", "type": "long"}
      ]}}},
    {"name": "total_cents", "type": "long"},
    {"name": "paid", "type": "boolean"},
    {"name": "created_unix", "type": "long"},
    {"name": "adjustments", "type": {"type": "array", "items": "int"}}
  ]
}`

// Sample returns the order used in the lab and the size table.
func Sample() Order {
	return Order{
		ID:       1001,
		Customer: "Sara",
		Items: []Item{
			{SKU: "BOOK-42", Qty: 2, PriceCents: 1500},
			{SKU: "PEN-7", Qty: 10, PriceCents: 120},
		},
		TotalCents:  4200,
		Paid:        true,
		CreatedUnix: 1764000000,
		Adjustments: []int32{-150, 0, 150},
	}
}

The two .proto versions used for Protobuf (the .pb.go files next to them are generated and committed; regenerate with protoc --go_out=. --go_opt=paths=source_relative order_v1.proto, the invocation shown in the protobuf.dev Go reference):

proto
// Version 1 of the Order message used on the serialization-formats page.
syntax = "proto3";

package academy.lab.v1;

option go_package = "academy/serialization-formats/orderpb/v1;orderv1";

message Item {
  string sku = 1;
  uint32 qty = 2;
  int64 price_cents = 3;
}

message Order {
  uint64 id = 1;
  string customer = 2;
  repeated Item items = 3;
  int64 total_cents = 4;
  bool paid = 5;
  int64 created_unix = 6;
  repeated sint32 adjustments = 7;
}
proto
// Version 2: adds an optional coupon as field 8. Bytes written by v1 still
// parse, and v1 code keeps field 8 as an unknown field.
syntax = "proto3";

package academy.lab.v2;

option go_package = "academy/serialization-formats/orderpb/v2;orderv2";

message Item {
  string sku = 1;
  uint32 qty = 2;
  int64 price_cents = 3;
}

message Order {
  uint64 id = 1;
  string customer = 2;
  repeated Item items = 3;
  int64 total_cents = 4;
  bool paid = 5;
  int64 created_unix = 6;
  repeated sint32 adjustments = 7;
  // New in v2. Explicit presence: old messages report HasCoupon() == false.
  optional string coupon = 8;
}
text
JSON (211 bytes): every name and number is text
00000000  7b 22 69 64 22 3a 31 30  30 31 2c 22 63 75 73 74  |{"id":1001,"cust|
00000010  6f 6d 65 72 22 3a 22 53  61 72 61 22 2c 22 69 74  |omer":"Sara","it|
...
000000c0  65 6e 74 73 22 3a 5b 2d  31 35 30 2c 30 2c 31 35  |ents":[-150,0,15|
000000d0  30 5d 7d                                          |0]}|

MessagePack, map mode, library defaults (195 bytes): note d3 + 8 bytes for every int64
00000000  87 a2 69 64 d3 00 00 00  00 00 00 03 e9 a8 63 75  |..id..........cu|

MessagePack, array mode + compact ints (48 bytes): no names, positional like Avro
00000000  97 cd 03 e9 a4 53 61 72  61 92 93 a7 42 4f 4f 4b  |.....Sara...BOOK|

CBOR, core deterministic (148 bytes): keys sorted by their encoded bytes
00000000  a7 62 69 64 19 03 e9 64  70 61 69 64 f5 65 69 74  |.bid...dpaid.eit|

Protobuf (56 bytes): tags and varints
00000000  08 e9 07 12 04 53 61 72  61 1a 0e 0a 07 42 4f 4f  |.....Sara....BOO|
00000010  4b 2d 34 32 10 02 18 dc  0b 1a 0b 0a 05 50 45 4e  |K-42.........PEN|
00000020  2d 37 10 0a 18 78 20 e8  20 28 01 30 80 82 92 c9  |-7...x . (.0....|
00000030  06 3a 05 ab 02 00 ac 02                           |.:......|

Avro (46 bytes): values only
00000000  d2 0f 08 53 61 72 61 03  28 0e 42 4f 4f 4b 2d 34  |...Sara.(.BOOK-4|
00000010  32 04 b8 17 0a 50 45 4e  2d 37 14 f0 01 00 d0 41  |2....PEN-7.....A|
00000020  01 80 84 a4 92 0d 05 0a  ab 02 00 ac 02 00        |..............|

Measured sizes and timings ​

go run ./formats decodes each encoding once and checks it equals the original (exit 1 otherwise), then times encode and decode with testing.Benchmark. One run on an Apple M-series laptop; your numbers will differ, the ranking rarely does:

go
// Command formats encodes one Order in eight formats, prints the size of each,
// an optional hex dump, and encode/decode timings from testing.Benchmark.
//
//	go run ./formats            # size + ns/op table
//	go run ./formats -hex json  # hex dump of one format
package main

import (
	"bytes"
	"encoding/gob"
	"encoding/hex"
	"encoding/json"
	"encoding/xml"
	"flag"
	"fmt"
	"os"
	"reflect"
	"testing"

	"academy/serialization-formats/model"
	orderv1 "academy/serialization-formats/orderpb/v1"

	"github.com/fxamacker/cbor/v2"
	"github.com/hamba/avro/v2"
	"github.com/vmihailenco/msgpack/v5"
	"google.golang.org/protobuf/proto"
)

type codec struct {
	name   string
	encode func() ([]byte, error)
	decode func([]byte) (any, error)
}

// Decoders return what they read so main can verify the round trip.
func viaModel(f func([]byte, *model.Order) error) func([]byte) (any, error) {
	return func(b []byte) (any, error) {
		var o model.Order
		err := f(b, &o)
		o.XMLName = xml.Name{} // only XML fills this field
		return o, err
	}
}

func toProto(o model.Order) *orderv1.Order {
	p := &orderv1.Order{
		Id: uint64(o.ID), Customer: o.Customer, TotalCents: o.TotalCents,
		Paid: o.Paid, CreatedUnix: o.CreatedUnix, Adjustments: o.Adjustments,
	}
	for _, it := range o.Items {
		p.Items = append(p.Items, &orderv1.Item{Sku: it.SKU, Qty: uint32(it.Qty), PriceCents: it.PriceCents})
	}
	return p
}

func codecs() []codec {
	order := model.Sample()
	pb := toProto(order)
	schema := avro.MustParse(model.AvroSchemaV1)

	// msgpack "array" mode: struct fields as a positional array, no keys.
	msgpackArray := func() ([]byte, error) {
		var buf bytes.Buffer
		enc := msgpack.NewEncoder(&buf)
		enc.UseArrayEncodedStructs(true)
		err := enc.Encode(order)
		return buf.Bytes(), err
	}
	msgpackArrayCompact := func() ([]byte, error) {
		var buf bytes.Buffer
		enc := msgpack.NewEncoder(&buf)
		enc.UseArrayEncodedStructs(true)
		enc.UseCompactInts(true)
		err := enc.Encode(order)
		return buf.Bytes(), err
	}
	// msgpack with compact ints: the library writes int64 as 9 bytes otherwise.
	msgpackCompact := func() ([]byte, error) {
		var buf bytes.Buffer
		enc := msgpack.NewEncoder(&buf)
		enc.UseCompactInts(true)
		err := enc.Encode(order)
		return buf.Bytes(), err
	}
	cborDet, _ := cbor.CoreDetEncOptions().EncMode()

	return []codec{
		{"json", func() ([]byte, error) { return json.Marshal(order) },
			viaModel(func(b []byte, o *model.Order) error { return json.Unmarshal(b, o) })},
		{"xml", func() ([]byte, error) { return xml.Marshal(order) },
			viaModel(func(b []byte, o *model.Order) error { return xml.Unmarshal(b, o) })},
		{"gob", func() ([]byte, error) {
			var buf bytes.Buffer
			err := gob.NewEncoder(&buf).Encode(order)
			return buf.Bytes(), err
		}, viaModel(func(b []byte, o *model.Order) error { return gob.NewDecoder(bytes.NewReader(b)).Decode(o) })},
		{"msgpack", func() ([]byte, error) { return msgpack.Marshal(order) },
			viaModel(func(b []byte, o *model.Order) error { return msgpack.Unmarshal(b, o) })},
		{"msgpack-compact", msgpackCompact,
			viaModel(func(b []byte, o *model.Order) error { return msgpack.Unmarshal(b, o) })},
		{"msgpack-array", msgpackArray,
			viaModel(func(b []byte, o *model.Order) error { return msgpack.Unmarshal(b, o) })},
		{"msgpack-arr-cpt", msgpackArrayCompact,
			viaModel(func(b []byte, o *model.Order) error { return msgpack.Unmarshal(b, o) })},
		{"cbor", func() ([]byte, error) { return cborDet.Marshal(order) },
			viaModel(func(b []byte, o *model.Order) error { return cbor.Unmarshal(b, o) })},
		{"protobuf", func() ([]byte, error) { return proto.Marshal(pb) },
			func(b []byte) (any, error) { o := &orderv1.Order{}; err := proto.Unmarshal(b, o); return o, err }},
		{"avro", func() ([]byte, error) { return avro.Marshal(schema, order) },
			viaModel(func(b []byte, o *model.Order) error { return avro.Unmarshal(schema, b, o) })},
	}
}

func main() {
	dump := flag.String("hex", "", "print a hex dump of one format and exit")
	flag.Parse()

	for _, c := range codecs() {
		b, err := c.encode()
		if err != nil {
			fmt.Fprintln(os.Stderr, c.name, err)
			os.Exit(1)
		}
		if *dump != "" {
			if c.name == *dump {
				fmt.Print(hex.Dump(b))
				return
			}
			continue
		}
		got, err := c.decode(b)
		if err != nil || !sameOrder(got) {
			fmt.Fprintf(os.Stderr, "%s: round trip failed: %v\n", c.name, err)
			os.Exit(1)
		}
		enc := testing.Benchmark(func(tb *testing.B) {
			tb.ReportAllocs()
			for i := 0; i < tb.N; i++ {
				_, _ = c.encode()
			}
		})
		dec := testing.Benchmark(func(tb *testing.B) {
			tb.ReportAllocs()
			for i := 0; i < tb.N; i++ {
				_, _ = c.decode(b)
			}
		})
		fmt.Printf("%-15s %4d bytes  encode %6d ns/op %3d allocs  decode %6d ns/op %3d allocs\n",
			c.name, len(b), enc.NsPerOp(), enc.AllocsPerOp(), dec.NsPerOp(), dec.AllocsPerOp())
	}
}

// sameOrder checks that a decoded value equals the sample, field by field.
func sameOrder(v any) bool {
	want := model.Sample()
	if p, ok := v.(*orderv1.Order); ok {
		return proto.Equal(p, toProto(want))
	}
	return reflect.DeepEqual(v, want)
}
text
json             211 bytes  encode    383 ns/op   3 allocs  decode    850 ns/op   6 allocs
xml              354 bytes  encode   1707 ns/op  21 allocs  decode   5792 ns/op 168 allocs
gob              327 bytes  encode   2258 ns/op  25 allocs  decode   7577 ns/op 250 allocs
msgpack          195 bytes  encode    409 ns/op   5 allocs  decode    720 ns/op  16 allocs
msgpack-compact  148 bytes  encode    408 ns/op   7 allocs  decode    697 ns/op  16 allocs
msgpack-array     95 bytes  encode    321 ns/op   6 allocs  decode    566 ns/op  19 allocs
msgpack-arr-cpt   48 bytes  encode    294 ns/op   5 allocs  decode    537 ns/op  19 allocs
cbor             148 bytes  encode    173 ns/op   2 allocs  decode    516 ns/op   9 allocs
protobuf          56 bytes  encode    122 ns/op   1 allocs  decode    201 ns/op   9 allocs
avro              46 bytes  encode    150 ns/op   2 allocs  decode    164 ns/op   4 allocs

How to read it: gob pays for writing its type description into every fresh stream (it is designed for long streams of one type, where that cost is paid once); XML pays for parsing names twice (open and close tags); the 195 vs 148 vs 95 vs 48 MessagePack rows show that library options, not the format, decided the size; Protobuf and Avro are 4 to 5 times smaller than JSON and 3 to 5 times faster to decode here. After gzip the gap narrows (see Compression); measure on your own payloads.

Streaming parsers: SAX, tokens and NDJSON ​

A DOM-style decoder builds the whole value in memory; a streaming (SAX-style, pull) parser hands you one token or element at a time, so a 5 GB export never sits in RAM.

Language / toolStreaming API
Go JSONjson.Decoder.Token(), More(), Decode() per element (see jsonpitfalls step 7); v2 jsontext.Decoder
Go XMLxml.Decoder.Token() returning StartElement/CharData/EndElement
PHP JSONPackages such as halaxa/json-machine (iterator over a big array); NDJSON line by line with SplFileObject
PHP XMLXMLReader (pull parser)
Pythonijson (iterative JSON), xml.sax, iterparse
Avro / ProtobufAvro container files are block-streamable; Protobuf has no record framing, so streams use length-delimited messages (protodelim in Go)
MessagePackBufferUnpacker::tryUnpack() (rybakit) for chunked input; msgpack.NewDecoder(r) in Go
text
     json.Decoder over [{"amount":"1.00"},{"amount":"2.50"},{"amount":"3.75"}]
1    Token()  -> json.Delim('[')
2    More()   -> true ; Decode(&row) -> {"amount":"1.00"}
3    More()   -> true ; Decode(&row) -> {"amount":"2.50"}
4    More()   -> true ; Decode(&row) -> {"amount":"3.75"}
5    More()   -> false ; Token() -> json.Delim(']')       memory: one row at a time

Error messages you will see ​

MessageWhereMeaning
json: cannot unmarshal string into Go struct field Order.id of type int64GoType mismatch: sender sends "1001"; use json:",string" or fix the contract
json: unknown field "is_admin"Go with DisallowUnknownFieldsExtra key; strict contract working as intended
invalid character 'N' looking for beginning of valueGoNaN or other non-JSON from Python or a log line
json: unsupported value: NaNGo MarshalFloat NaN/Inf cannot be JSON
http: request body too largeGo MaxBytesReaderBody exceeded the limit
JsonException: Syntax error / Malformed UTF-8 characters, possibly incorrectly encodedPHP with JSON_THROW_ON_ERRORInvalid JSON / invalid UTF-8
Maximum stack depth exceededPHP json_decodeNesting beyond $depth (512 default)
proto: cannot parse invalid wire-format dataGo protobufNot protobuf, truncated, or wrong message type
string field contains invalid UTF-8Go protobufproto3 string with non-UTF-8 bytes; use bytes
reader field channel is missing in writer schema and has no defaulthamba/avroBreaking Avro change (measured in the lab)
avro: decode union type: unknown union typehamba/avroDecoded with the wrong schema
cbor: found duplicate map key "role" at map element index 1fxamacker/cborDuplicate key rejected (measured)
__PHP_Incomplete_Class objectsPHP unserializeClass missing or not allowed; cache from an older deploy

Solving the classic problems ​

ProblemSolutionAdvantageCost
MoneyInteger minor units (total_cents) or decimal string + currencyExact everywhereConversion at the edges
64-bit IDs in browsersString in JSON (json:",string")No silent roundingClients must not do math on IDs
DatesRFC 3339 string with offset; or Unix seconds/ms as integersUnambiguousPick one per contract and document it
Binary inside JSON/XMLBase64 (or base64url) string; large blobs by referenceWorks with any text format+33% size, CPU; see Binary-to-Text Encoding
Changing schemasAdditive changes, defaults, reserved numbers, registry checksRolling deploys keep workingDiscipline and CI checks
Untrusted inputSize/depth/count limits, strict fields, no native formatsRemoves DoS and RCE classesA few lines of code

Money and decimals ​

0.1 + 0.2 in any IEEE 754 parser is 0.30000000000000004 (SQLite printed exactly that in the lab). Send money as an integer in minor units (4200 cents) or as a decimal string ("42.00") with an ISO 4217 currency code, never as a JSON float. Avro has a decimal logical type (bytes + precision + scale); Protobuf has no decimal type, so use int64 units + int32 nanos (the pattern of google.type.Money) or a string. In Go, keep cents in int64 or parse strings with a decimal library; in PHP use bcmath (bcdiv((string) $cents, '100', 2), as in OrderResource) or brick/money. The PostgreSQL side: numeric, and jsonb stores numbers as numeric, exactly.

Dates and time zones ​

RFC 3339 is the Internet profile of ISO 8601: date-time = full-date "T" full-time, with Z or a numeric offset. Always include the offset; I-JSON recommends "that the timezone be included not defaulted, and that optional trailing seconds be included even when their value is "00"". RFC 3339 also defines -00:00 for "unknown local offset", which "differs semantically from an offset of "Z" or "+00:00"". Go time.Time marshals to RFC 3339 with nanoseconds (2026-11-25T09:30:00+03:30 in jsonpitfalls); Laravel serializes Carbon dates in its own default format unless you override serializeDate() or format per resource (toRfc3339String()). For an appointment in the future, also store the IANA zone (Asia/Tehran), because offsets change by law. Protobuf uses google.protobuf.Timestamp (seconds + nanos, UTC); Avro has timestamp-millis/timestamp-micros; MessagePack has the Timestamp extension (-1); CBOR has tag 0 (text date) and tag 1 (epoch).

Binary blobs inside text formats ​

JSON and XML cannot carry raw bytes. Go's encoding/json writes []byte as standard Base64 ("3q2+7w==" in the lab); PHP needs base64_encode() explicitly; I-JSON recommends base64url. Anything over a few hundred kilobytes should travel by reference (an object-storage URL, a presigned link) rather than inside the document; for messages that is the claim-check pattern in Message Design & Schema Evolution. Binary formats (MessagePack bin, CBOR byte strings, Protobuf bytes, Avro bytes) carry them natively.

Schema evolution per format ​

writer v1old producerwriter v2new producerreader v1old consumerreader v2new consumerWho can read whose bytes?dashed: BACKWARD (new reads old)dotted: FORWARD (old reads new)BACKWARD: upgradeconsumers firstFORWARD: upgradeproducers firstFULL = both directionsProtobuf+ add field with a NEW number+ delete field, then reserve number+ rename (names not on the wire)- reuse or change a field numberold readers keep unknown fieldsnew readers see zero / not-setAvro+ add field WITH a default+ remove field that had a default+ rename via "aliases"+ promote int to long/float/double- add field without default (error)reader needs the writer schemaJSON (no schema on wire)+ add optional field only if readers ignore unknowns- rename = delete + add- change "5" to 5 (type change)strict decoders (Disallow-UnknownFields) break forwardcompatibility on purpose

Backward compatible: new readers can read data written by old writers (deploy consumers first). Forward compatible: old readers can read data written by new writers (deploy producers first). Full: both. Registries such as Confluent Schema Registry enforce a chosen mode per subject (BACKWARD, FORWARD, FULL and their _TRANSITIVE variants); that layer is covered in Message Design & Schema Evolution.

ChangeJSON (readers ignore unknown)JSON (strict decoder)ProtobufAvroMessagePack/CBOR (map mode)Array/positional modes
Add optional fieldSafeBreaks old readersSafeSafe with defaultSafeBreaks unless appended and readers tolerate extra
Remove fieldSafe if readers tolerate absenceSafeSafe; reserve the numberSafe if it had a defaultSafe if toleratedBreaks
Rename fieldBreaksBreaksSafe (wire), breaks ProtoJSONSafe with aliasesBreaksSafe
Change type (int to string)BreaksBreaksBreaks (except listed compatible pairs, e.g. int32/int64 with truncation)Breaks (except promotions)BreaksBreaks
Reorder fieldsSafeSafeSafeSafe (resolved by name)SafeBreaks
Reuse an old name/numberSilent corruptionSilent corruptionSilent corruptionSilent corruptionSilent corruptionn/a

The evolve snippet writes with one schema and reads with another, in both directions, for Protobuf and Avro:

go
// Command evolve writes bytes with an old schema and reads them with a new
// one (and the reverse) in Protobuf and Avro, then shows a breaking change.
package main

import (
	"encoding/hex"
	"fmt"

	"academy/serialization-formats/model"
	orderv1 "academy/serialization-formats/orderpb/v1"
	orderv2 "academy/serialization-formats/orderpb/v2"

	"github.com/hamba/avro/v2"
	"google.golang.org/protobuf/proto"
)

// Reader schema v2: adds "coupon" with a default, so old data still resolves.
const avroV2 = `{
  "type": "record", "name": "Order", "namespace": "academy.lab",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "customer", "type": "string"},
    {"name": "total_cents", "type": "long"},
    {"name": "coupon", "type": ["null", "string"], "default": null}
  ]
}`

// Reader schema v3: adds "channel" WITHOUT a default. Old data cannot resolve.
const avroV3 = `{
  "type": "record", "name": "Order", "namespace": "academy.lab",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "channel", "type": "string"}
  ]
}`

type orderV2 struct {
	ID         int64   `avro:"id"`
	Customer   string  `avro:"customer"`
	TotalCents int64   `avro:"total_cents"`
	Coupon     *string `avro:"coupon"`
}

func main() {
	protobufDemo()
	avroDemo()
}

func protobufDemo() {
	// Old writer, new reader: the new field reads as "not present".
	oldBytes, _ := proto.Marshal(&orderv1.Order{Id: 7, Customer: "Sara", TotalCents: 4200})
	var asV2 orderv2.Order
	if err := proto.Unmarshal(oldBytes, &asV2); err != nil {
		panic(err)
	}
	fmt.Printf("protobuf v1->v2: id=%d coupon set=%v value=%q\n", asV2.GetId(), asV2.Coupon != nil, asV2.GetCoupon())

	// New writer, old reader: field 8 becomes an unknown field and survives a round trip.
	newBytes, _ := proto.Marshal(&orderv2.Order{Id: 8, Customer: "Ali", Coupon: proto.String("NOWRUZ")})
	var asV1 orderv1.Order
	_ = proto.Unmarshal(newBytes, &asV1)
	fmt.Printf("protobuf v2->v1: id=%d unknown bytes=%s\n", asV1.GetId(), hex.EncodeToString(asV1.ProtoReflect().GetUnknown()))

	relayed, _ := proto.Marshal(&asV1) // an old service forwards the message
	var back orderv2.Order
	_ = proto.Unmarshal(relayed, &back)
	fmt.Printf("protobuf v2->v1->v2: coupon=%q (preserved)\n", back.GetCoupon())
}

func avroDemo() {
	writerV1 := avro.MustParse(model.AvroSchemaV1)
	data, _ := avro.Marshal(writerV1, model.Sample())

	// Avro bytes carry no field names: you need the writer schema to read them.
	readerV2 := avro.MustParse(avroV2)
	resolved, err := avro.NewSchemaCompatibility().Resolve(readerV2, writerV1)
	if err != nil {
		panic(err)
	}
	var o orderV2
	if err := avro.Unmarshal(resolved, data, &o); err != nil {
		panic(err)
	}
	fmt.Printf("avro v1->v2: id=%d customer=%s total=%d coupon=%v (default)\n", o.ID, o.Customer, o.TotalCents, o.Coupon)

	// Reading with the wrong schema and no resolution silently misreads bytes.
	var wrong orderV2
	err = avro.Unmarshal(readerV2, data, &wrong)
	fmt.Printf("avro without resolution: id=%d total=%d err=%v\n", wrong.ID, wrong.TotalCents, err)

	// A reader field with no default is a breaking change.
	readerV3 := avro.MustParse(avroV3)
	_, err = avro.NewSchemaCompatibility().Resolve(readerV3, writerV1)
	fmt.Println("avro v1->v3:", err)
}
text
protobuf v1->v2: id=7 coupon set=false value=""
protobuf v2->v1: id=8 unknown bytes=42064e4f5752555a
protobuf v2->v1->v2: coupon="NOWRUZ" (preserved)
avro v1->v2: id=1001 customer=Sara total=4200 coupon=<nil> (default)
avro without resolution: id=1001 total=-2 err=Coupon: avro: decode union type: unknown union type
avro v1->v3: reader field channel is missing in writer schema and has no default

Defensive decoding: limits, duplicates and deserialization attacks ​

Decoders allocate what the bytes claim: a 30-byte MessagePack header can announce a 4 GiB array; ten thousand [ characters exhaust a recursive parser's stack; XML entities expand exponentially. Rules: cap the body size before parsing, cap depth and element counts, reject duplicate keys where a decision depends on a field, reject unknown fields on commands, and never decode untrusted input with gob, unserialize(), readObject or pickle. In JavaScript, merging parsed JSON into objects can reach Object.prototype: MDN calls __proto__ "A key attack vector"; the lab's naive merge() made ({}).isAdmin return true. Use Object.create(null), Map, or schema validation that drops unknown keys.

go
// Command safedecode shows defensive decoding: size limits, strict fields,
// trailing-data checks, duplicate-key rejection, depth limits and
// deterministic (canonical) encoding for hashing and signing.
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/fxamacker/cbor/v2"
)

type CreateOrder struct {
	Customer string `json:"customer"`
	SKU      string `json:"sku"`
	Qty      int    `json:"qty"`
}

const maxBody = 1 << 20 // 1 MiB

// decodeJSON is the strict decoder every handler should share.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
	r.Body = http.MaxBytesReader(w, r.Body, maxBody)
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	if err := dec.Decode(dst); err != nil {
		var tooBig *http.MaxBytesError
		if errors.As(err, &tooBig) {
			return fmt.Errorf("body larger than %d bytes", tooBig.Limit)
		}
		return err
	}
	// Exactly one JSON value: reject `{...}{...}` and trailing garbage.
	if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
		return errors.New("body must contain a single JSON object")
	}
	return nil
}

func handler(w http.ResponseWriter, r *http.Request) {
	var in CreateOrder
	if err := decodeJSON(w, r, &in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, "ok %s x%d", in.SKU, in.Qty)
}

func main() {
	for _, body := range []string{
		`{"customer":"Sara","sku":"BOOK-42","qty":2}`,
		`{"customer":"Sara","sku":"BOOK-42","qty":2,"is_admin":true}`,
		`{"customer":"Sara","sku":"BOOK-42","qty":2}{"qty":999}`,
		`{"customer":"` + strings.Repeat("A", maxBody) + `"}`,
	} {
		rec := httptest.NewRecorder()
		handler(rec, httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(body)))
		fmt.Printf("HTTP %d %s\n", rec.Code, strings.TrimSpace(rec.Body.String()))
	}

	// CBOR: reject duplicate map keys and absurd nesting before allocating.
	dm, _ := cbor.DecOptions{
		DupMapKey:        cbor.DupMapKeyEnforcedAPF,
		MaxNestedLevels:  16,
		MaxArrayElements: 10_000,
		MaxMapPairs:      1_000,
	}.DecMode()
	dupKeys := []byte{0xa2, 0x64, 'r', 'o', 'l', 'e', 0x64, 'u', 's', 'e', 'r',
		0x64, 'r', 'o', 'l', 'e', 0x65, 'a', 'd', 'm', 'i', 'n'} // {"role":"user","role":"admin"}
	var m map[string]string
	fmt.Println("cbor duplicate keys:", dm.Unmarshal(dupKeys, &m))

	// Deterministic encoding: same value, same bytes, same hash.
	em, _ := cbor.CoreDetEncOptions().EncMode()
	a, _ := em.Marshal(map[string]int{"b": 2, "a": 1})
	b, _ := em.Marshal(map[string]int{"a": 1, "b": 2})
	ha, hb := sha256.Sum256(a), sha256.Sum256(b)
	fmt.Println("cbor deterministic:", hex.EncodeToString(a), ha == hb)
	diag, _ := cbor.Diagnose(a)
	fmt.Println("cbor diagnostic   :", diag)
}
text
HTTP 200 ok BOOK-42 x2
HTTP 400 json: unknown field "is_admin"
HTTP 400 body must contain a single JSON object
HTTP 400 body larger than 1048576 bytes
cbor duplicate keys: cbor: found duplicate map key "role" at map element index 1
cbor deterministic: a2616101616202 true
cbor diagnostic   : {"a": 1, "b": 2}

Note the tension with RFC 7493's "Must-Ignore" policy ("when an implementation encounters a protocol element that it does not recognize, it should treat the rest of the protocol transaction as if the new element simply did not appear"): strict decoding is right for commands you own (a typo like amount_typo should fail loudly), must-ignore is right for events and public APIs that evolve. Decide per contract.

Laravel: resources, flags and safe decoding ​

The public JSON shape belongs in an API Resource, not in $model->toArray(): the resource fixes names, string IDs, decimal strings and RFC 3339 dates, and jsonOptions() (a method on JsonResource whose value ResourceResponse passes as the response's JSON encoding options) keeps Persian readable:

php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * The public JSON contract for an order. The resource, not the model,
 * decides field names, types and formats, so a column rename never
 * leaks into the API.
 */
class OrderResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            // 64-bit IDs as strings: JavaScript loses precision above 2^53 - 1.
            'id' => (string) $this->id,
            'customer' => $this->customer_name,
            // Money as a decimal string plus currency, never a float.
            'total' => [
                'amount' => bcdiv((string) $this->total_cents, '100', 2),
                'currency' => $this->currency,
            ],
            'paid' => (bool) $this->paid,
            // RFC 3339 with an explicit offset, e.g. 2026-11-25T09:30:00+00:00.
            'created_at' => $this->created_at?->toRfc3339String(),
            'items' => OrderItemResource::collection($this->whenLoaded('items')),
        ];
    }

    /**
     * Flags passed to json_encode() for this resource's response.
     * Persian names stay readable instead of سا...
     */
    public function jsonOptions(): int
    {
        return JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION;
    }
}
php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class OrderItemResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'sku' => $this->sku,
            'qty' => (int) $this->qty,
            'price' => bcdiv((string) $this->price_cents, '100', 2), // needs ext-bcmath
        ];
    }
}

One codec class for every json_encode/json_decode call in the app (the Jsonable contract is just public function toJson($options = 0);, and JsonResponse calls it with its encoding options):

php
<?php

namespace App\Support;

use JsonException;

/**
 * One place for JSON flags so every service encodes and decodes the same way.
 */
final class JsonCodec
{
    public const ENCODE_FLAGS = JSON_THROW_ON_ERROR
        | JSON_UNESCAPED_UNICODE        // "سارا" instead of "سارا"
        | JSON_UNESCAPED_SLASHES        // "https://x/y" instead of "https:\/\/x\/y"
        | JSON_PRESERVE_ZERO_FRACTION;  // 10.0 stays 10.0, not 10

    public const DECODE_FLAGS = JSON_THROW_ON_ERROR
        | JSON_BIGINT_AS_STRING;        // 9223372036854775808 stays exact

    public static function encode(mixed $value): string
    {
        return json_encode($value, self::ENCODE_FLAGS);
    }

    /**
     * Decode to arrays with a nesting limit; throws on invalid JSON
     * instead of returning null (which is also a valid JSON value).
     *
     * @throws JsonException
     */
    public static function decode(string $json, int $maxDepth = 32): array
    {
        $value = json_decode($json, true, $maxDepth, self::DECODE_FLAGS);
        if (! is_array($value)) {
            throw new JsonException('Top-level JSON value must be an object or array');
        }

        return $value;
    }

    /**
     * Reject keys the contract does not know (the "must-understand" policy).
     * Use it on commands; prefer ignoring unknown keys on events.
     *
     * @param  list<string>  $allowed
     */
    public static function rejectUnknownKeys(array $payload, array $allowed): void
    {
        $unknown = array_diff(array_keys($payload), $allowed);
        if ($unknown !== []) {
            throw new JsonException('Unknown field(s): '.implode(', ', $unknown));
        }
    }
}

// json_encode(['name' => 'سارا', 'price' => 10.0])
//   default flags  -> {"name":"سارا","price":10}
//   ENCODE_FLAGS   -> {"name":"سارا","price":10.0}
// json_decode('{"a":1,"a":2}', true) -> ['a' => 2]   (last duplicate wins)
// json_decode('{"n":12345678901234567890}', true)   -> ['n' => float, digits lost]
// with JSON_BIGINT_AS_STRING                         -> ['n' => '12345678901234567890']

MessagePack and Protobuf from PHP (rybakit is pure PHP; the PECL extension is faster with the same bytes; google/protobuf has a pure-PHP runtime and an optional C extension):

php
<?php

namespace App\Support;

use Academy\Lab\V1\Item;
use Academy\Lab\V1\Order;
use MessagePack\BufferUnpacker;
use MessagePack\Packer;

/**
 * The same order in MessagePack and Protobuf from PHP.
 *
 * composer require rybakit/msgpack google/protobuf
 * protoc --php_out=generated order_v1.proto   (package academy.lab.v1 -> Academy\Lab\V1)
 */
final class BinaryCodecs
{
    public static function sample(): array
    {
        return [
            'id' => 1001,
            'customer' => 'Sara',
            'items' => [
                ['sku' => 'BOOK-42', 'qty' => 2, 'price_cents' => 1500],
                ['sku' => 'PEN-7', 'qty' => 10, 'price_cents' => 120],
            ],
            'total_cents' => 4200,
            'paid' => true,
            'created_unix' => 1764000000,
            'adjustments' => [-150, 0, 150],
        ];
    }

    /** Pure-PHP MessagePack (rybakit/msgpack). */
    public static function msgpack(): string
    {
        return (new Packer())->pack(self::sample());
    }

    /** Decode with a nesting limit (the library default is 128). */
    public static function fromMsgpack(string $bytes): array
    {
        return (new BufferUnpacker($bytes))->unpack(16);
    }

    /** The PECL msgpack extension is faster and has the same wire format. */
    public static function msgpackExtension(): string
    {
        return msgpack_pack(self::sample());
    }

    /** Protobuf: field numbers on the wire, names only in the generated class. */
    public static function protobuf(): string
    {
        $o = self::sample();
        $order = new Order();
        $order->setId($o['id']);
        $order->setCustomer($o['customer']);
        $order->setTotalCents($o['total_cents']);
        $order->setPaid($o['paid']);
        $order->setCreatedUnix($o['created_unix']);
        $order->setAdjustments($o['adjustments']);

        $items = [];
        foreach ($o['items'] as $row) {
            $item = new Item();
            $item->setSku($row['sku']);
            $item->setQty($row['qty']);
            $item->setPriceCents($row['price_cents']);
            $items[] = $item;
        }
        $order->setItems($items);

        return $order->serializeToString(); // same wire format the Go encoder writes
    }

    public static function fromProtobuf(string $bytes): Order
    {
        $order = new Order();
        $order->mergeFromString($bytes); // unknown fields are kept

        return $order;
    }
}

Untrusted input: never unserialize() it; parse XML without DTDs:

php
<?php

namespace App\Support;

use DOMDocument;
use RuntimeException;

/**
 * Deserializing untrusted bytes safely in PHP.
 */
final class SafeDecoding
{
    /**
     * NEVER: unserialize($request->input('state')).
     * Object instantiation + autoloading + magic methods (__wakeup,
     * __destruct) form gadget chains that lead to remote code execution.
     *
     * If you must read PHP-serialized data you wrote yourself (a cache,
     * a file), verify an HMAC first and still forbid objects.
     */
    public static function unserializeTrusted(string $payload, string $mac, string $key): array
    {
        if (! hash_equals(hash_hmac('sha256', $payload, $key), $mac)) {
            throw new RuntimeException('Tampered payload');
        }

        $value = unserialize($payload, ['allowed_classes' => false, 'max_depth' => 32]);
        if (! is_array($value)) {
            throw new RuntimeException('Unexpected payload type');
        }

        return $value;
    }

    /**
     * XML from outside: no DTD, no entity substitution, no network.
     * libxml >= 2.9 does not substitute entities unless LIBXML_NOENT is set.
     */
    public static function parseXml(string $xml): DOMDocument
    {
        if (stripos($xml, '<!DOCTYPE') !== false) {
            throw new RuntimeException('DOCTYPE not allowed'); // blocks XXE and billion laughs
        }

        $doc = new DOMDocument();
        $ok = $doc->loadXML($xml, LIBXML_NONET | LIBXML_COMPACT);
        if (! $ok) {
            throw new RuntimeException('Invalid XML');
        }

        return $doc;
    }
}

The PHP files were reviewed but not executed (PHP is not installed on the machine that produced this page).

Troubleshooting ​

SymptomLikely causeCheckFix
IDs end in ...992 or ...000 in the browser64-bit integer through JSON.parseCompare raw response bytes with the UI valueSend IDs as strings
Totals off by a centFloat moneyLook for float/double in the DTOCents or decimal strings
Persian text shows as س...PHP default escapingjson_encode flagsJSON_UNESCAPED_UNICODE
Persian text shows as ساراUTF-8 bytes read as Latin-1/Windows-1252xxd the bytes: d8 b3 is UTF-8 for «س»Fix the reader's charset; send charset=utf-8
New field missing in old service outputProxy decoded into a struct and re-encoded as JSONProtoJSON or struct copy drops unknown fieldsForward bytes, or use binary protobuf end to end
Consumer fails after producer deployBreaking change or strict decoderDiff schemas; registry compatibility checkAdditive change with defaults; upgrade order
Avro decode returns garbage then failsWrong reader schema, no resolutionSchema ID in the message vs schema usedFetch writer schema by ID; resolve
Signature mismatch on a webhookRe-serialized bodyVerify against $request->getContent()Hash raw bytes or use JCS
0644 became 420, NO became falseYAML 1.1 implicit typingParse with the same library as productionQuote strings; YAML 1.2 parser; or TOML
Memory spike on one requestHuge or deeply nested payloadBody size and depth in logsMaxBytesReader, depth limits, streaming parser
__PHP_Incomplete_Class after deployCached PHP-serialized objects of renamed classesCache store contentsVersion cache keys; cache arrays, not objects
Kafka consumer: "Unknown magic byte"Message not in registry wire formatFirst byte should be 0x00Use the registry serializer on both sides

Choosing a format ​

Use caseRecommendedAlso fineAvoidReason
Public REST API, webhooksJSON (UTF-8, OpenAPI)CBOR for constrained clientsProtobuf-onlyEvery client and tool speaks JSON
Browser to backendJSONProtobuf via gRPC-Web or ConnectXMLJSON.parse is native; mind 2^53
Internal RPCProtobuf (gRPC)Thrift, JSON for simple servicesLanguage-nativeTyped contracts, small and fast; see gRPC
Events on KafkaAvro or Protobuf + schema registryJSON + JSON SchemaSchema-less JSONMany consumers, long retention, enforced evolution
Config filesTOML or YAML (quoted)JSON (machine-written)YAML from usersComments, readability
LogsJSON LineslogfmtPretty-printed JSONOne record per line, grep/jq friendly
Cache valuesMessagePack, igbinary, JSONPHP serialize for own datapickle/unserialize of foreign dataSize and speed; trust boundary
Long-term storage / data lakeAvro files (schema embedded), ParquetJSON Lines + schemagob, serialize()Readers decades later
Database document columnjsonb (PostgreSQL), BSON (MongoDB)Protobuf in byteajson text for queryingIndexable, validated
Signed dataCBOR deterministic (COSE), JWS, JCSDER (X.509)Re-serialized JSONByte-stable encoding
Large read-mostly blobs, gamesFlatBuffers, Cap'n ProtoProtobufJSONZero-copy partial reads

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Serialization happens at the edges: HTTP JSON in and out, a jsonb column, cache values, queue payloads. The simplest correct setup is one JSON codec configuration for the whole app (one JsonCodec, API Resources for every response, Go's strict decodeJSON helper), money as cents, dates as RFC 3339, IDs as strings in public JSON. Everyday example: a Laravel shop's OrderResource returning "id":"1001" and "total":{"amount":"42.00","currency":"EUR"}. Production example: the same monolith caching product pages in Redis with Redis::SERIALIZER_MSGPACK and versioned cache keys (product:v3:42) so a deploy that changes the shape never reads old bytes.

Modular monolith and multiple databases ​

Modules exchange in-process objects, so serialization appears only where modules persist or publish: an orders module writes an outbox row whose payload is JSON or Protobuf bytes, and a billing module reads it. Treat that payload as a contract owned by the publishing module, versioned in its folder, with a test that decodes fixtures from previous versions. Everyday example: a catalog module storing product attributes in jsonb with a JSON Schema check in a migration. Production example: two databases (orders in PostgreSQL, search in Elasticsearch) fed by the same JSON event; a renamed field breaks indexing silently unless a contract test decodes the old fixture.

Microservices ​

Now bytes cross teams and deploy schedules. Synchronous calls use Protobuf over gRPC (schema in a shared repo, buf breaking or equivalent in CI); events use Avro or Protobuf with a registry, so every message carries 0x00 + schema ID; public edges stay JSON. Unknown-field preservation matters: a v1 audit service that decodes into a struct and re-encodes to JSON strips fields that v2 services added. Everyday example: checkout (Go) sends an OrderPlaced Protobuf event; invoices (Laravel) decodes it with mergeFromString. Production example:

text
mobile app -> api-gateway        JSON  {"id":"1001","total":{"amount":"42.00","currency":"EUR"}}
api-gateway -> orders-svc        gRPC  Protobuf orders.v2.CreateOrder (56-byte class of payloads)
orders-svc -> Kafka orders.v1    Avro  00 | 00 00 01 2c | d2 0f 08 53 61 72 61 ...   (magic, schema id 300, data)
invoices (PHP), analytics (Spark), search-indexer (Go) <- each fetches schema 300 once, resolves against its reader schema

Distributed data: replicas, caches, logs and archives ​

Stored bytes outlive code. Kafka topics with weeks of retention, compacted topics, S3 archives and caches all hold data written by old code, so readers must be backward compatible for the full retention period (registry BACKWARD_TRANSITIVE), and a rollback means new data must be readable by old code (forward). Caches shared by two app versions during a rolling deploy need either a version in the key or a self-describing, tolerant format. Replicated databases copy jsonb and BSON as-is, so a migration that rewrites JSON shape must handle both shapes until backfill finishes. Everyday example: a Redis cache warmed by v1 and read by v2 for ten minutes of a deploy. Production example: a data lake of Avro container files read by Spark jobs five years later; the embedded schema in each file header is what makes that possible.

Scaling path: 1×, 10×, 100× ​

LoadWhat changes
1x: one app, thousands of requests per minuteJSON everywhere, one codec config, strict decoding helpers, limits on body size
10x: several services, hundreds of requests per second per serviceProtobuf for internal RPC; contract tests on fixtures; compression on large JSON responses; MessagePack or igbinary for hot caches
100x: many teams, Kafka at tens of thousands of messages per secondSchema registry with enforced compatibility; Avro/Protobuf events; codegen in CI; dashboards for deserialization errors and DLQ
BeyondZero-copy formats on the hottest paths; columnar formats (Parquet) for analytics; dedicated payload-size budgets per endpoint

Lab ​

All commands ran on the author's machine (macOS, Apple Silicon, go1.27.4, jq 1.7.1, SQLite 3.54.0, Node, Ruby 2.6, LibreSSL 3.3.6). PHP, protoc and Docker were not available, so the Protobuf Go code is committed pre-generated and the PHP snippets were reviewed, not run.

  1. Encode one object in every format and compare sizes and timings.
    bash
    cd docs/snippets/foundations/serialization-formats/go
    go run ./formats            # table in "Measured sizes"
  2. Hexdump each format and annotate it with the tables in One Order, byte by byte:
    bash
    for f in json msgpack-compact cbor protobuf avro; do echo "== $f"; go run ./formats -hex $f; done
  3. Walk Protobuf bytes without the schema (what protoc --decode_raw does):
    bash
    go run ./wire
    # 1:VARINT 1001
    # 2:LEN 4 bytes "Sara"
    # 7:LEN 5 bytes "\xab\x02\x00\xac\x02"
  4. Evolve the schema (add a field) and decode old bytes with new code, and the reverse, in Protobuf and Avro: go run ./evolve (output under Schema evolution). The breaking cases are in the same output: reading v1 Avro bytes with the v2 schema and no resolution misreads total as -2 before failing, and a reader field without a default (channel) fails resolution outright. For Protobuf, the equivalent mistake (reusing a field number) is not detectable at all, which is why the guide says numbers are never reused.
  5. JSON numbers, duplicates and prototype pollution across tools:
    bash
    echo '{"id":9007199254740993}' | jq '.id + 0'                 # 9007199254740992
    echo '{"role":"user","role":"admin"}' | jq -c .               # {"role":"admin"}
    sqlite3 :memory: "select json_extract('{\"role\":\"user\",\"role\":\"admin\"}','\$.role')"   # user
    python3 -c 'import json; print(json.dumps(float("nan")))'     # NaN  (not valid JSON)
    node -e 'console.log(JSON.parse("{\"id\":9007199254740993}").id)'   # 9007199254740992
    node -e 'console.log(JSON.stringify({x:NaN}))'                # {"x":null}
  6. The Norway problem and a DER certificate:
    bash
    printf 'country: NO\nmode: 0644\nport: 22:22\n' > norway.yaml
    ruby -ryaml -e 'p YAML.load_file("norway.yaml")'   # {"country"=>false, "mode"=>420, "port"=>80520}
    openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout /dev/null \
      -subj /CN=lab -days 1 -outform DER -out lab.der
    openssl asn1parse -inform DER -in lab.der | head -5
    #     0:d=0  hl=4 l= 513 cons: SEQUENCE
    #     4:d=1  hl=4 l= 422 cons: SEQUENCE
    #     8:d=2  hl=2 l=   9 prim: INTEGER           :E346BF3D56B64B48
    Serial number and lengths change per run.

Common misconceptions ​

BeliefReality
JSON numbers are integers or floatsThey are decimal text; the parser decides, and most use IEEE doubles (exact only to 2^53)
Duplicate keys are invalid JSONThey are syntactically valid; behaviour is "unpredictable" per RFC 8259; parsers differ (first wins in SQLite, last in most)
Binary formats are secure because unreadableProtobuf and MessagePack decode without a schema in a few lines
Protobuf field names matter on the wireOnly numbers and wire types are on the wire; names matter in ProtoJSON and code
Proto3 tells you whether a field was sentOnly for optional, message and oneof fields; scalars at default are not written
Avro bytes contain the schemaSingle records do not; container files and registries supply it
MessagePack is always much smaller than JSONWith names and 9-byte ints it can be close (195 vs 211 bytes here); array mode is where it shrinks
allowed_classes => false makes unserialize() safe for user inputThe PHP manual says never pass untrusted input regardless of that option
YAML is JSON with nicer syntaxImplicit typing (NO, 0644, 22:22), anchors and unsafe loaders make it a config language, not an exchange format
json.Marshal output is canonicalStruct order, float formatting and escaping vary by language; use JCS or deterministic CBOR for signatures
Adding a field is always backward and forward compatibleNot with strict decoders, positional encodings, or Avro fields without defaults
XML is obsoleteSAML, SOAP, Office files, SVG and many B2B feeds are XML; XXE still matters

Cheat sheet ​

TopicRemember
Interoperable JSON integers[-(2^53)+1, 2^53-1]; larger as strings
JSON must-escape" \ and U+0000 to U+001F; UTF-8 only, no BOM
JSON specialsNo NaN, no Infinity, no comments, no trailing commas
Protobuf tag(field_number << 3) OR wire_type; fields 1-15 = 1-byte tag
Protobuf wire types0 VARINT, 1 I64, 2 LEN, 5 I32 (3/4 deprecated groups)
Negative ints in Protobufsint32/sint64 (zigzag), not int32 (10 bytes)
Protobuf evolutionNew numbers only; reserved deleted ones; optional for presence
Avro evolutionNew fields need defaults; renames need aliases; read with writer + reader schema
CBOR for signingCore deterministic encoding; reject duplicate keys
MessagePack sizeDepends on library options: compact ints, array mode
MoneyInteger minor units or decimal string + currency
DatesRFC 3339 with offset; store IANA zone for future local times
Bytes in JSONBase64/base64url; big blobs by reference
Never on untrusted inputunserialize(), readObject, pickle, gob, unsafe YAML loaders
Go strict JSONMaxBytesReader + DisallowUnknownFields + single-value check + UseNumber when decoding to any
PHP JSON flagsJSON_THROW_ON_ERROR, JSON_UNESCAPED_UNICODE, JSON_PRESERVE_ZERO_FRACTION, JSON_BIGINT_AS_STRING

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Go service sends {"id": 9007199254740993}. What does a React frontend show, and how do you fix the contract? Must-know ​

Answer

Answer: 9007199254740992: JSON.parse stores numbers as IEEE doubles, exact only up to 2^53. Send the ID as a string (json:"id,string" in Go, (string) $this->id in a Laravel resource). See Numbers are not integers.

2 — Decode the Protobuf bytes 08 96 01 by hand. Good to know ​

Answer

Answer: 08 = 0000 1000: field 1, wire type 0 (VARINT). 96 01: drop continuation bits, 0010110 and 0000001, reverse to 0000001 0010110 = 150. So field 1 = 150. See Varints, tags, wire types.

3 — Why does int32 adjustment = -2 cost 10 bytes in Protobuf, and what should you use? Important ​

Answer

Answer: int32 negatives are encoded as 64-bit two's complement varints, which have the top bit set and need all ten bytes. sint32 uses ZigZag: -2 becomes 3, one byte. See ZigZag and packed.

4 — An old service (v1 schema) receives a v2 Protobuf message with a new field 8, then forwards it. Is field 8 lost? What if it forwards it as JSON? Important ​

Answer

Answer: In binary it is kept as an unknown field and re-serialized (measured: coupon="NOWRUZ" (preserved)). Converting to JSON loses unknown fields, as the proto3 guide states. See Unknown fields.

5 — You add "channel": "string" (no default) to an Avro reader schema. What happens to existing data? Important ​

Answer

Answer: Schema resolution fails for every record written without that field: "reader field channel is missing in writer schema and has no default". Add a default (or a ["null","string"] union with default: null). See Avro.

6 — Two services parse {"user":"alice","user":"mallory"}. Why is this a security bug, and name two fixes. Must-know ​

Answer

Answer: Parsers disagree (SQLite first wins, Go v1/PHP/Python last wins), so an authorizer and an executor can see different users. Reject duplicates at the edge (Go encoding/json/v2, CBOR DupMapKeyEnforcedAPF, Python object_pairs_hook) and pass the parsed value, not the raw body. See Duplicate keys.

7 — Why must a webhook signature be verified against the raw body and not against json_encode(json_decode($body))? Must-know ​

Answer

Answer: Re-serialization changes bytes (key order, escaping, number format), so the hash changes. Hash the exact received bytes, or both sides use a canonical form such as RFC 8785 JCS. See Canonical JSON.

8 — Your Laravel app reads a state cookie with unserialize() after validating it is a string. Is ['allowed_classes' => false] enough? Must-know ​

Answer

Answer: No. The PHP manual: "Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes." Use JSON, or HMAC-verify data you wrote yourself before unserializing. CVE-2018-15133 is the Laravel precedent. See Language-native formats.

9 — Why did our Order take 195 bytes in MessagePack but 48 bytes in another MessagePack run? Good to know ​

Answer

Answer: Library options: vmihailenco/msgpack writes int64 as 9 bytes by default and structs as maps with names; UseCompactInts plus UseArrayEncodedStructs drops both. The format did not change; the encoder's choices did. See Measured sizes.

10 — A YAML config sets country: NO and mode: 0644. What can a YAML 1.1 parser return, and how do you prevent it? Important ​

Answer

Answer: false and 420 (Ruby Psych did exactly this in the lab). Quote strings, use a YAML 1.2 Core-schema parser, or use TOML. See YAML and TOML.

11 — Which format would you choose for Kafka events read by Go, PHP and Spark consumers for two years, and why? Important ​

Answer

Answer: Avro or Protobuf with a schema registry: compact, typed, and evolution is checked (backward transitive for the retention window). Avro files or registry IDs give readers the writer schema years later. See Choosing a format.

Glossary ​

TermMeaning
Serialization / deserializationTurning an in-memory value into bytes / rebuilding a value from bytes; also encoding/decoding, marshal/unmarshal
Wire formatThe byte layout used between processes (network, queue)
Storage formatThe byte layout used at rest (files, columns, caches)
Self-describingBytes carry field names and types; readable without a schema
Schema-basedReader needs an external schema (.proto, Avro schema, IDL, ASN.1 module)
RFC 8259The JSON standard (December 2017); UTF-8 between systems; numbers interoperable within ±(2^53-1)
I-JSON (RFC 7493)Strict JSON profile: no duplicate names, no surrogates, big numbers as strings, RFC 3339 dates, base64url bytes
JCS (RFC 8785)JSON Canonicalization Scheme: one byte form for hashing and signing JSON
JSON Lines / NDJSONOne JSON value per line, \n separated
JSON5 / JSONCHuman-edited JSON variants with comments (JSON5 also trailing commas, single quotes)
Parser differentialTwo parsers interpreting the same bytes differently (duplicate keys, numbers, UTF-8)
Duplicate keysSame name twice in one JSON object; SHOULD NOT happen, behaviour unpredictable
Canonical / deterministic encodingExactly one byte sequence per value (CBOR §4.2, DER, JCS)
XML namespacesURI-qualified element and attribute names (xmlns:prefix)
XSDXML Schema Definition: types and structure validation for XML
XXEXML External Entity injection: entities that read files or URLs during parsing
Billion laughsNested entity expansion attack on XML (and YAML aliases)
YAML anchors / aliases&name defines a node, *name reuses it
Norway problemYAML 1.1 reading NO as boolean false
TOMLConfig format with explicit types and no references
ProtobufProtocol Buffers: schema (.proto) + tag/varint wire format
VarintVariable-length integer: 7 payload bits per byte, MSB = continuation
ZigZagMaps signed to unsigned so small negatives encode small (sint32, Avro ints)
Wire typeProtobuf's 3-bit kind in each tag: VARINT, I64, LEN, SGROUP, EGROUP, I32
Field numberProtobuf's permanent identity for a field; never reuse; 1-15 cost one tag byte
Unknown fieldsProtobuf fields a reader's schema does not know; preserved in binary
Field presenceWhether a reader can tell "unset" from "default"; explicit for optional, messages, oneofs
Packed repeatedRepeated scalars in one LEN record; default in proto3
ProtoJSONProtobuf's JSON mapping; loses unknown fields; 64-bit ints as strings
MessagePackBinary JSON-like format with type bytes
Ext typesMessagePack extension types: 0-127 application, -128 to -1 reserved (-1 Timestamp)
CBOR (RFC 8949)IETF binary format: major types, tags, deterministic encoding
COSECBOR Object Signing and Encryption (RFC 9052)
WebAuthn / CTAP2 canonical CBORPasskey protocol data encoded in deterministic CBOR
AvroSchema-based binary format with writer/reader schema resolution
Writer / reader schemaSchema used to write the bytes / schema the reading code expects
Schema resolutionAvro's matching of writer and reader schemas by field name, defaults and promotions
Object Container FileAvro file with the schema in its header and sync markers between blocks
Single-object encodingAvro C3 01 + 8-byte schema fingerprint + data
Schema registryService storing schemas by ID; Confluent wire format = 0x00 + 4-byte ID + data
Backward / forward / full compatibilityNew reads old / old reads new / both
ThriftApache IDL + RPC framework with binary and compact protocols
FlatBuffers / Cap'n ProtoZero-copy formats: read fields directly from the buffer
Zero-copyAccessing serialized data without decoding into new objects
BSONMongoDB's binary document format with extra types
ASN.1 / DERAbstract syntax notation and its distinguished (unique) TLV encoding; X.509
TLVTag-length-value encoding
gobGo's self-describing stream format for Go values
PHP serialize() / unserialize()PHP-native format; unserialize can instantiate classes
Gadget chainExisting classes whose magic methods chain into code execution during deserialization
Java serialization / JEP 290ObjectInputStream; filters added in Java 9
picklePython's native format; a program that runs on load
Prototype pollutionWriting through __proto__ into JavaScript's Object.prototype
RFC 3339Internet timestamp profile: 2026-11-25T09:30:00+03:30
Base64 / base64urlBinary-to-text encoding used for bytes in JSON/XML
Streaming parser (SAX, pull)Reads tokens/elements incrementally instead of building the whole tree
json.DecoderGo stream decoder: Token, More, UseNumber, DisallowUnknownFields
RawMessageGo type holding undecoded JSON bytes for later decoding
omitempty / omitzeroGo struct tag options omitting empty or zero values
JsonResourceLaravel API Resource class shaping model JSON
JsonableLaravel contract with toJson($options = 0)
JSON_UNESCAPED_UNICODEPHP flag: write non-ASCII literally
JSON_THROW_ON_ERRORPHP flag: throw JsonException instead of returning null/false
JSON_PRESERVE_ZERO_FRACTIONPHP flag: keep 10.0 as 10.0
JSON_BIGINT_AS_STRINGPHP decode flag: integers beyond PHP_INT_MAX as strings
igbinaryPHP binary serializer, a PhpRedis serializer option

References ​

Built by Morteza Negahi