• entries
437
1000
• views
336723

# FlatBuffers in .NET

6188 views

I've been tinkering with Google's new FlatBuffers protocol and have an experimental port of it running in .NET (C#).

FlatBuffers is interesting and there's a couple of other alternatives in the form of ProtoBuf, Cap'n Proto, Simple Binary Encoding (SBE) and, to a lesser extent, JSON, XML and YAML. These protocols all share the same thing in common, to serialize your data into a format that's portable between applications - be it as an on disk format (save game, level, etc) or as a wire object for communicating with network services.

JSON is really the go-to choice now for people who use web services a lot and works well as a configuration file format too. However I've recently been noticing a trend towards binary encoded data, especially in the arena of game (client/server, especially); the reasoning behind this is often due to performance of both encode/decode and that the text-based formats take up more network bandwidth.

One issue with binary protocols has always been that it can be extremely easy to change the schema and render the existing data invalid.

Take the simple object:class Vector3{public: float X; float Y; float Z;}class Monster{public: int Health; Vector3 Position;}
We would probably serialize out with something like this:void SerializeMonster(std::ostream &stream, const Monster &monster){ stream << monster.Health; SerializeVector3(stream, monster.Position);}void SerializeVector3(std::ostream &stream, const Vector3 &vector){ stream << vector.X << vector.Y << vector.Z; // Quantized floats omitted for simplicity}
And deserialization would be something like this:Monster* DeserializeMonster(std::istream &stream){ auto monster = new Monster(); stream >> monster.Health; monster.Position = DeserializeVector3(stream); return monster;}Vector3* DeserializeVector3(std::istream &stream){ auto vector = new Vector3(); stream >> vector.X; stream >> vector.Y; stream >> vector.Z; return vector;}
If I wanted to add additional fields to the Monster class (Mana, Color, Weapons carried, etc), I would have to be very careful to keep my functions in sync, and moreover if I change the serialization order of anything all my stored data is useless.

This problem gets even bigger if you start talking outside of a single application, such as sending data from your client to a network server that might have been written in .NET, Java or any other language.

A few years ago Google released V2 of their Protobuf format which aims to bring a bit of sanity to this problem. They defined their serialization objects in a simple IDL (interface definition language). The IDL used by Protobuf has a formal native type format and then your data is defined as "messages". Protobuf has a "compiler" which then generates your C++ (and other languages) serialization code from the IDL.message Vector3 { required float x = 1; required float y = 2; required float x = 3;}message Monster { required int32 health = 1; required Vector3 position = 2;}
A key thing to note here is the numbering used; this defines the serialization order of the field. Protobuf mandates that if you want to maintain backwards compatibility, you must not change the ordering of existing items, new items are appended with a higher sequence and they are added as "optional" or with a default value. Anyone interested should look here for more details on this.

Protobuf does some clever encoding of the data to minimize the size; things such as packing numeric types and omitting null values.

Projects like FlatBuffers (and the others mentioned above) cite that the encoding/decoding step of Protobuf is expensive - both in terms of processing power and memory allocation. This can be especially true if done frequently - such as if your network server is communicating in protobuf format. In some of the online services I've worked on, serialization to/from the wire format to an internal format has been an area to focus optimization on.

FlatBuffers, Cap'n proto and SBE take the stance that the data belonging to the object is laid out the same in memory as it is on disk/during transport, thus bypassing the encoding and object allocation steps entirely. This strategy becomes an enabler of allowing simple mmap() use or streaming of this data, at the expense of the data size. I'm not going to go in the pro/cons here, as the Cap'n Proto FAQ does a better job. However, all of these in-memory binary data formats all acknowledge that having a "schema" which can be modified and retain backwards compatibility is a good thing. Basically, they want the benefits of Protobuf, with less overhead.

So back to the topic of this post; how does .NET fit into this? Given that engines such as Unity provide C# support and XNA / MonoGame / FNA are all managed frameworks capable of targeting multiple platforms, FlatBuffers in .NET has a couple of obvious use cases:

• Data exchange between native code and C# editors/tools
• Game data files with a smaller footprint than JSON/XML/YAML
• Wire data exchange between Flatbuffer enabled client/servers (to a lesser extent, due to bandwidth concerns, but viable in the same datacentre)
• Interprocess communication between .NET and native services (same box scenarios)

I started porting the Flatbuffers protocol to .NET and hit a slight dilemma; should we treat Flatbuffers as a serialization format, or should it also be the "memory" format too?

In Marc Gravell's Protobuf-net project he explicitly took the stance that "r[color=rgb(0,0,0)][font=arial]

### ather than being "a protocol buffers implementation that happens to be on .NET", it is a ".NET serializer that happens to use protocol buffers" - the emphasis is on being familiar to .NET users (for example, working on mutable, code-first classes if you want)."

[/font][/color]

[color=rgb(0,0,0)][font=arial]

### Right now, I'm facing a similar question. What is more important for .NET users? Is it the ability to code first and serialize, or to be able to access Flatbuffer data without serializing?

[/font][/color]

[color=rgb(0,0,0)][font=arial]

### Here's an example of the code-first approach:

[/font][/color][FlatBuffersContract(ObjectType.Struct)]public class Vector3{ public float X { get; set; } public float Y { get; set; } public float Z { get; set; }}[FlatBuffersContract(ObjectType.Object)]public class Monster{ public int Health { get; set; } public Vector3 Position { get; set; }}var someBufferStream = ...;var monster = FlatBuffers.Serializer.Deserialize(someBufferStream);
We declared our various classes and used an attribute to annotate them. Then we explicitly take data from the stream to create a new Monster (and Vector3) object. From here, we can discard the buffer as we have our .NET objects to work with.

Serialization would be the opposite: create your objects in .NET and call a Serialize() method to fill a Flatbuffer.

The benefits of this are that is it is very .NET centric; we are used to code-first approaches and serializing to/from our entity classes. Conversely, we now have to either manually synch our IDL files, or write a tool to generate them. We also begin allocating many objects - especially if the buffer is large and has a lot of depth.

An alternative approach is the accessor pattern which the FlatBuffers Java port takes. Here, we effectively pass a reference to the data in Flatbuffer format and use a accessor methods to read what we need. The accessor classes would be generated by the IDL parser tool.public class MonsterAccessor{ public MonsterAccessor(FlatBufferStream flatBuffer, int objectOffset) { .. } public int Health { get { flatBuffer.ReadInt(... objectOffset + offset of health ...); } } public Vector3Accessor Position { get { return new Vector3Accessor(flatBuffer, flatBuffer.ReadOffset(... objectOffset + offset of position ...)); } }}public class Vector3Accessor{ public Vector3Accessor(FlatBufferStream flatBuffer, int objectOffset) { .. } public float X { get { flatBuffer.ReadInt(... objectOffset + offset of x ...); } } public float Y { get { flatBuffer.ReadOffset(... objectOffset + offset of y ...); } } // etc }var someBufferStream = ...;var offset = ...;var monsterAccessor = new MonsterAccessor(someBufferStream, offset);var monsterHealth = monsterAccessor.Health;var vector3Accessor = monsterAccessor.Position;// etc
In addition to the Reads, we would also supply "Write" methods to populate the buffer structures.

The benefit of this approach is that the buffer access becomes lightweight; we are no longer deserializing whole objects if we don't need to - we're not allocating memory (except for things like strings). We also get direct sync with the IDL version.
The downside of this is that working like this feels quite alien in the .NET world; the code to handle buffer access is very manual and in the case of the position access, very clunky. It's likely that we will end up creating lots of accessors - unless we rely on everything being static. Which also becomes pretty... nasty.

This latter approach is more akin to a "port" of Flatbuffers, rather than treating it like a serialization type.

So - with these approaches in mind; what would YOUR favoured access method for FlatBuffers be in .NET? Would you focus primarily on FlatBuffers as a serialization format, much like Marc Gravell did with protobuf-net? Or would you look at a true port? Or maybe there's some hybrid approach?

What would your use cases be?

## 1 Comment

The second approach. If you don't actually require the performance characteristics that FlatBuffers provides, then you might as well just stick with something more flexible like JSON or ProtoBuf.

## Create an account

Register a new account