Sitemap

WTF is per-node layout polymorphism?

Or: how to combine the best of Protocol Buffers and FlatBuffers in one format — and take one dependency out of your project.

--

Press enter or click to view image in full size

The world: two formats, two philosophies

Protocol Buffers and FlatBuffers are two different binary serialization formats with two different goals.

Protocol Buffers was designed for gRPC; its primary goal is to pack data compactly so it can be sent over the wire. I have to say the general design is very elegant in its simplicity. A message is just a list of key–value pairs, where the key is the field’s id plus 3 bits of metadata. To represent an array, you repeat the same key with different values, and the reader collects them. To represent an associated type, you associate multiple keys with the same field, so that ideally there is a single value across the range of keys — or you just take the last one as the field’s actual value. The idea is elegant, but it makes decoding expensive: to hand a single field to the consumer, you have to consume the whole buffer. It does not help that the key–value pairs are not sorted by key and can arrive in any order.

FlatBuffers’ main goal is the opposite: a zero-copy, fast-to-decode buffer that lets you randomly access a field in a large buffer without materializing it. To achieve that, a FlatBuffers message — a table — has a vtable that stores the relative offset of each field. Arrays are their own type, with a prefixed size and a known element width, so a consumer can randomly access any element by index. A variable-size value like a string, a blob, or another table is referenced by a relative offset that is always 4 bytes wide — which conveniently enables deduplication and DAG support, since one element can be referenced by different offsets from different parts of the buffer. And to keep deserialization cheap, every value is stored aligned to its width, so you never pay for an unaligned load. The trade-off: the resulting binary can be much bigger than the equivalent Protobuf message, unless deduplication happens to bail you out.

The problem: you make one bet, for your whole schema

Each format is a bet. Protobuf bets on compactness and pays for it at decode time. FlatBuffers bets on random access and pays for it in size. Neither bet is wrong — but you place it once, for your entire schema, and every node has to live with it.

The trouble is that real data is not uniform. In one application you might have a chatty little message you want as compact as possible, a large record you want to random-access without materializing, and a fixed value like a coordinate you touch a million times. These want different bets. So what do people actually do? They reach for more than one tool — Protobuf here, FlatBuffers there — each with its own schema language, its own compiler, its own generated runtime and dependency. You end up maintaining two (or three) serialization stacks and gluing them together at the seams.

That is the problem Dagr set out to remove.

The solution: pick the layout per node

This is the per-node layout polymorphism the title promised. In a Dagr schema, when you define a node you set `packed=True` to serialize it with the Protobuf strategy; the default is the FlatBuffers strategy. The choice is per node, in one schema, in one format — a compact packed node and a random-access regular node can sit side by side in the same graph.

The most extreme version of this is mixing strategies within a single graph: a regular node pointing at a packed subtree, or the other way around. But you often will not need to go that far. You can just as well keep one compact packed graph for a streaming use case and one random-access regular graph for another. The point is not the mixing — it is that both live in the same tool, behind the same mental model, and the generated libraries carry zero third-party dependencies. You are no longer wiring Protobuf and FlatBuffers, and their two toolchains, into the same project just to cover two kinds of data.

The rest of this post is the details: what I changed in each strategy to make it a good building block, and what happens when the two meet.

The details

Adapting Protocol Buffers

A careful reader might have expected me to object to the random key order — and I do. Dagr insists on monotonic order: fields are stored in ascending order of their id (their index in the node). A second small adjustment: in Protobuf the root message is not prefixed with its total byte size (only a field value that is itself a message gets a size prefix). Dagr insists that every node serialized with the Protobuf strategy is byte-size prefixed.

These two modifications buy us a lot. A reader knows exactly what to expect: it scans through the buffer reading the fields it knows, and when it hits a field key larger than anything it recognizes, it assumes the buffer was written by a newer version — so it stops and jumps to the end using the total size. Conversely, if it reaches the byte-size boundary before reading fields it still expects, it exits early.

Get Maxim Zaks’s stories in your inbox

Join Medium for free to get updates from this writer.

Because all unknown fields sit in a skippable region, we can also shrink the metadata from 3 bits to 1. That may not sound like much, but it means a field with an id < 64 fits in a 1-byte key in Dagr, whereas in Protobuf only a field with id < 16 gets a 1-byte key — everything else takes 2 bytes or more.

This scannable, monotonic layout also buys us something Protobuf cannot offer: reads on demand. Because we can walk the buffer in field order and stop as soon as we reach the field we care about, we do not have to eagerly deserialize the whole message into objects. Dagr supports eager deserialization when you want it, but it can just as well scan to a position and read a single value with minimal memory allocation — no need to materialize everything around it. (This too is a topic for a different blog post.)

Arrays and unions are stored differently, too. Arrays are size-prefixed and keep all their values in one place, which gives us data locality. Unions carry a tag that allows any value type in the case — we even support recursive union types. Together these decisions give us data locality and region safety: a buffer serialized with the Protobuf strategy can be viewed as a tree in which every subtree can be extracted as a plain slice of the buffer. That is enormously useful in networking, where a subtree of the payload needs to be routed to another service — with Dagr we can do that very efficiently, with no re-serialization.

Adapting FlatBuffers

I have a long-standing beef with FlatBuffers, and it is about cyclic references. Technically they are possible, but they introduce real challenges, and although I proposed supporting them properly about a decade ago, the idea was refused. So, as you can imagine, Dagr allows cyclic references and makes sure they are handled safely and correctly. (I will write a separate post going into the details.)

Another limitation — which is also a strength — is FlatBuffers’ fixed 4-byte width for special values like string/array counts and relative offsets, along with its strict alignment. A couple of years ago the `offset64` and `vector64` markers were introduced to selectively allow larger arrays and pointers, but overall a FlatBuffers payload tends to be bigger, and it does not compress well either. In Dagr the counts and offsets are variable length, and we do not insist on alignment for every field and value. We do allow explicit alignment modifiers on fields, specified in bytes, aimed at the case where you want to read an array of numeric values straight into SIMD, or hand it off to a GPU, without paying for an unaligned copy. Unaligned reads of single values are not that expensive on modern x86 anyway. On top of that, union types in Dagr are far more powerful than in FlatBuffers, and we support arrays of optional values out of the box.

What happens when the strategies meet

Suppose we have a regular node (FlatBuffers strategy) that references a node marked `packed`. The field on the regular node holds a pointer to a region of the buffer where the child is stored in packed form — meaning the child does not participate in the graph, it is stored as an inline tree. (And if your data actually formed a cyclic reference that now needs to be stored as a tree, the serializer raises a handleable exception.)

Now the reverse: a node marked `packed=True` that references a node not marked packed. The child is still stored packed. The `packed` modifier is contagious! Why? Because a subtree has to live in a single region to remain sliceable.

There is, however, an escape hatch. You can mark a field with a non-packed type as `raw`, and then the child — together with its subgraph — is serialized in place as a self-contained graph: it holds no references back out to parent nodes, and it will replicate any shared nodes that happen to be reachable from it.

One more thing: freeze any node

Everything so far has been one axis — Protobuf strategy or FlatBuffers strategy. Frozen is a second, orthogonal axis that crosses with the first: any node, packed or regular, can also be frozen, which is where the four shapes come from (regular, packed, frozen, frozen+packed).

With the FlatBuffers strategy we have a vtable to locate the fields; with the Protobuf strategy we have a field key that carries the field’s id and metadata. That metadata exists to support node evolution. But what if we don’t want to evolve a node — what if we have a type that will never change, like `Vector3D` or `GPSCoordinate`?

For that, Dagr lets you set `frozen=True` in the node’s schema definition. The code generator then guarantees the node’s shape never changes, and because it is frozen the access pattern is known at compile time — so we can drop almost all of the metadata. The only thing we keep is a presence bitset for the optional fields, and if every field in the node is required, there is no presence bitset at all.

If you are a seasoned FlatBuffers user you might say, “ah, so this is just a `struct`.” Only partially. A FlatBuffers struct is very limited — it allows only fixed-size field types. A frozen node in Dagr, packed or regular, has the same composition properties and serialization strategies as a non-frozen one; the only difference is that we drop the field metadata to save a bit of space and, in some cases, read faster.

And if what you actually want is fixed-size data with in-place mutation, we have something else for you — it is called a SharedBuffer. But that is a topic for a different post, so stay tuned.

The real win

Per-node layout polymorphism is a neat trick, but the trick is not the point. The point is that a whole family of data-shape problems — compact wire messages, random-access records, types you never evolve, and (posts for another day) streaming logs and shared-memory buffers — now live behind a single schema, a single format, and zero-dependency generated code. That is the same one-stop-solution instinct I keep coming back to: composable building blocks beat premature simplicity, because premature simplicity is exactly what makes you pull a second serialization library into your project in the first place.

PS: docs, examples, and interactive demos live at https://dagr.one/.

--

--

Maxim Zaks
Maxim Zaks

Written by Maxim Zaks

Tells computers how to waste electricity. Hopefully in efficient, or at least useful way.