FlatBuffers

On this page 7

FlatBuffers is an open-source, schema-based binary serialization format that stores structured data so that a program can read it directly from the buffer without parsing or unpacking it first. Among data formats, it belongs to the family of compact binary encodings next to Protocol Buffers, Apache Avro and MessagePack, but its defining property is zero-copy access: a field is located through offsets and read in place.

The format was created at Google, originally for game development and other performance-critical software, and it is now widely used where latency and memory matter more than payload size, for example in mobile applications and in the TensorFlow Lite model file format. Its design trades some encoding convenience and wire compactness for near-instant access to individual fields.

How FlatBuffers stores data for zero-copy access

FlatBuffers achieves zero-copy reads by laying out data in memory exactly as it will be consumed, using relative offsets instead of pointers. A reader receives a byte array, follows a root offset at the start of the buffer to the root table, and then navigates to any nested object by adding stored offsets to the current position.

Each table carries a reference to a vtable, a small lookup structure that lists where each field sits inside the table. When a field is absent from the vtable, the reader returns the default value declared in the schema, so defaults cost no space in the buffer. Identical vtables are shared between tables, which keeps the overhead low for large collections of similar records.

Scalars are stored in little-endian byte order and aligned to their natural size, so on common hardware a value can be read with a single memory load. Buffers are typically built back to front by a builder object, because child objects must exist before the parent that refers to them can record their offsets.

The following table summarizes the building blocks of a FlatBuffers buffer and what each contributes.

ElementPurposeKey property
Root offsetPoints to the root tableFirst 4 bytes of the buffer
File identifierOptional 4-character type markerPlaced after the root offset
TableRecord with optional fieldsFields located through a vtable
VtableField position indexShared between identical layouts
StructFixed, inline group of scalarsNo vtable, cannot evolve
Vector and stringLength-prefixed sequencesStrings are UTF-8 and null-terminated
Core structural elements of a FlatBuffers buffer

Schema language and code generation

Every FlatBuffers format is described in a schema file with the .fbs extension, written in an interface definition language that resembles Protocol Buffers. The flatc compiler reads the schema and generates accessor code for languages such as C++, C#, Go, Java, Kotlin, Python, Rust, Swift and TypeScript, so that applications read fields through typed methods rather than manual byte arithmetic.

The schema distinguishes several type categories, and choosing between them is the main modeling decision a developer makes. The table below lists the categories and when each is appropriate.

Type categoryTypical useEvolution behavior
tableRecords that may change over timeFields can be added and deprecated
structSmall fixed groups such as a 3D vectorLayout frozen once published
enumNamed integer constantsNew values can be appended
unionOne of several table typesNew member types can be appended
vectorArrays of scalars, structs or tablesElement type must stay the same
Schema type categories and their typical use

The compiler can also convert between JSON and binary buffers using the same schema, which helps with debugging, configuration files and test fixtures. A companion format, FlexBuffers, offers schemaless binary encoding with similar in-place access for cases where no schema is available.

FlatBuffers compared with other binary formats

FlatBuffers differs from its neighbors mainly in when the cost of decoding is paid. Protocol Buffers and Apache Avro require a parsing step that copies values into language objects, while FlatBuffers defers that work to the moment a field is accessed, and then the cost is close to a memory read.

FormatSchemaRead modelTypical strength
FlatBuffersRequired (.fbs)In-place, zero-copyLowest access latency
Protocol BuffersRequired (.proto)Full parse into objectsCompact messages and RPC
Apache AvroRequired, often embeddedFull parse with schema resolutionData pipelines and files
MessagePackNoneFull parseDrop-in binary JSON
Cap’n ProtoRequiredIn-place, zero-copyRPC with capability model
FlatBuffers next to related binary serialization formats

The usual trade-off is size versus access speed. FlatBuffers buffers are often somewhat larger than equivalent Protocol Buffers messages because of alignment padding, offsets and vtables, although general-purpose compression narrows that gap. For analytical workloads over many rows, columnar formats such as Parquet or Apache Arrow are a better fit, because FlatBuffers is row-oriented and object-centric.

Schema evolution and compatibility rules

FlatBuffers supports forward and backward compatibility as long as schema changes follow a small set of rules. Because field positions are resolved through the vtable by field index, the order of fields in a table effectively becomes part of the binary contract.

  • Add new fields only at the end of a table, or assign explicit id attributes to control their index.
  • Never remove a field; mark it deprecated so that its slot remains reserved.
  • Never change the type or default value of an existing field, because old buffers omit fields equal to the old default.
  • Treat structs as frozen: any change to a struct breaks every buffer that contains it.

Readers built with an older schema simply ignore unknown fields, and readers built with a newer schema see missing fields as defaults. This makes FlatBuffers suitable for long-lived file formats and for clients and servers that upgrade at different times.

Limitations, risks and common mistakes

The zero-copy design creates specific constraints that teams discover in production. The most important is security with untrusted input: since offsets are followed blindly, a malformed buffer can cause out-of-bounds reads, so data from networks or files must pass the generated verifier before access.

ProblemCauseRemedy
Crash on corrupt inputOffsets followed without checksRun the verifier on untrusted buffers
Buffer size limit reached32-bit offsets cap buffers near 2 GBSplit data or use 64-bit offset support
Field silently missingValue equal to default is not storedUse optional scalars or force defaults
Hard in-place updatesOnly existing fixed-size values are mutableRebuild the buffer or use the object API
Broken compatibilityField reordered or struct changedAppend fields and deprecate instead
Frequent problems with FlatBuffers and how to address them

Building buffers is also less ergonomic than parsing: the builder API requires creating strings and child tables before their parent, which feels unnatural compared with filling an object tree. The generated object API restores convenience at the cost of copying, which removes the main advantage when used on hot paths.

In simple terms

Most data formats work like a sealed package: before anything inside can be used, the whole box must be opened and every item taken out. FlatBuffers works more like a well-labeled filing cabinet. The labels say exactly which drawer holds each item, so a program can reach straight for the one piece it needs without unpacking everything else.

The price is that the cabinet takes a little more room and has to be arranged carefully when it is filled. In exchange, reading becomes almost instant, which matters for games, phones and other software that must react quickly.

A practical example

A mobile game studio stores its level definitions, covering terrain tiles, enemy positions and item tables, in large configuration files. With JSON, loading a level on a mid-range phone took roughly a second of parsing and briefly doubled memory use, because the text had to be converted into thousands of objects.

The team defined a .fbs schema, converted the existing JSON files with flatc, and shipped the levels as binary buffers mapped directly from storage. The game now reads only the tiles near the player, and level loading dropped to a few tens of milliseconds with no temporary object allocation. Because the files arrive through an update server, the client runs the verifier once per downloaded file before using it, which protects against corrupted or tampered downloads.