# FlatBuffers payloads

URL: https://docs.folkways.io/docs/realtime-api/payloads/flatbuffers

Define a FlatBuffers schema for your events, encode and decode it in TypeScript and Python, and publish it.

FlatBuffers is a schema-based binary format whose readers access fields without unpacking the whole buffer. Your app
owns the schema, the generated code and the compatibility rules; Folkways carries the bytes unchanged. This schema is
yours and has nothing to do with the protocol's own.

## Define a schema [#define-a-schema]

Save as location.fbs:

```text
namespace Fleet;

table Location {
  vehicle_id:string;
  latitude:double;
  longitude:double;
  timestamp_ms:ulong;
}
root_type Location;
file_identifier "FLOC";
```

## Generate bindings [#generate-bindings]

Install the compiler and the matching runtime from the [FlatBuffers project](https://flatbuffers.dev/), 24.3.25 in
this example:

```bash
flatc --ts -o generated location.fbs
flatc --python -o generated-python location.fbs
npm install flatbuffers@24.3.25
```

The TypeScript module lands in `generated/fleet/location.ts`.

## Encode and decode in TypeScript [#encode-and-decode-in-typescript]

```ts
import * as flatbuffers from 'flatbuffers';
import { Location } from './generated/fleet/location.js';

export function encodeLocation(id: string, latitude: number, longitude: number, timestamp: bigint) {
  const b = new flatbuffers.Builder(128);
  const vehicle = b.createString(id);
  Location.startLocation(b);
  Location.addVehicleId(b, vehicle);
  Location.addLatitude(b, latitude);
  Location.addLongitude(b, longitude);
  Location.addTimestampMs(b, timestamp);
  b.finish(Location.endLocation(b), 'FLOC');
  return Uint8Array.from(b.asUint8Array());
}

export function decodeLocation(bytes: Uint8Array) {
  if (bytes.length < 8 || String.fromCharCode(...bytes.subarray(4, 8)) !== 'FLOC') {
    throw new Error('Unexpected payload');
  }
  const value = Location.getRootAsLocation(new flatbuffers.ByteBuffer(bytes));
  return {
    vehicleId: value.vehicleId(),
    latitude: value.latitude(),
    longitude: value.longitude(),
    timestampMs: value.timestampMs(),
  };
}
```

The file identifier is a format hint, not a verifier. Treat received bytes as untrusted: check lengths and ranges
before acting on them, and never trust an ID in a payload for authorization; the event's `publisher` is the verified
sender.

## Publish and receive [#publish-and-receive]

With a KV rule for `tracking/*` and a connected [JavaScript client](/docs/js-sdk):

```ts
const trip = client.topic('tracking/trip-42');

trip.subscribe((message) => {
  if (message.name !== 'location' || message.deleted || message.contentType !== 4) return;
  try {
    show(decodeLocation(message.payload));
  } catch {
    console.warn('Ignoring an invalid location');
  }
});

await trip.publish('location', encodeLocation('vehicle-42', 24.8, 67.1, BigInt(Date.now())), {
  delivery: 'kv',
  contentType: 'flatbuffers',
  ttlMs: 30_000,
});
```

`contentType: 4` is FlatBuffers; see [content types](/docs/realtime-api/payloads#content-types).

## Decode in another language [#decode-in-another-language]

A Python service can read the same bytes with the generated Python module:

```python
from Fleet.Location import Location

def decode_location(payload: bytes):
    if len(payload) < 8 or payload[4:8] != b"FLOC":
        raise ValueError("Unexpected payload")
    location = Location.GetRootAs(payload, 0)
    return {
        "vehicleId": location.VehicleId().decode("utf-8"),
        "latitude": location.Latitude(),
        "longitude": location.Longitude(),
        "timestampMs": location.TimestampMs(),
    }
```

Test the same fixture bytes in every language you use. The docs repository's `examples/payloads` folder has a
round trip between TypeScript and Python. When the schema changes, append fields, keep existing fields and defaults,
and never reuse a retired field; see [Schemas](/docs/realtime-api/payloads/schemas).
