# Upload payload & ingest endpoint

> The JSON envelope Beekon POSTs to your backend (root fields, locations, geofence events, encoding rules) and a working ingest endpoint with the status codes the SDK acts on.

Source: https://docs.getbeekon.com/guide/payload/

Once [sync is on](https://docs.getbeekon.com/guide/sync/), Beekon POSTs batches of stored history to your `url`. This page describes the format your server receives and how to build the endpoint that accepts it.

**On this topic:** [Turn on sync](https://docs.getbeekon.com/guide/sync/) · Upload payload & ingest endpoint (this page) · [Auth & token refresh](https://docs.getbeekon.com/guide/sync-auth/)

## The upload payload

Each upload is one JSON object at `schema_version: 1`. New fields arrive only as additions, so your endpoint must ignore fields it doesn’t know. Locations travel in **identity segments**: each segment carries the `user_id` that was set when its rows were recorded, so an account switch while offline never attributes one user’s locations to another.

```json
{
  "schema_version": 1,
  "batch_id": "0190d4e2-7b1a-7c3e-9f10-2a4b6c8d0e1f",
  "session_id": "0190d4e0-1234-7000-8000-aabbccddeeff",
  "sent_at": "2026-06-15T12:34:56.789Z",
  "device": {
    "install_id": "0190c1a4-aaaa-7bbb-8ccc-ddddeeeeffff",
    "platform": "ios",
    "sdk_version": "0.6.0",
    "model": "iPhone15,3"
  },
  "extras": {"trip": "morning-commute"},
  "segments": [
    {
      "user_id": "app-user-123",
      "locations": [
        {
          "id": "0190d4e2-7b1a-7c3e-9f10-2a4b6c8d0e20",
          "timestamp": "2026-06-15T12:34:10.000Z",
          "trigger": "interval",
          "motion": "moving",
          "is_mock": false,
          "latitude": 37.7749,
          "longitude": -122.4194,
          "accuracy": 5.2,
          "speed": 2.5,
          "bearing": 180,
          "altitude": 14.3,
          "activity": "walking",
          "battery_percent": 87,
          "is_charging": false,
          "power_save_mode": false
        }
      ],
      "geofence_events": [
        {
          "id": "0190d4e2-7b1a-7c3e-9f10-2a4b6c8d0e21",
          "type": "exit",
          "geofence_id": "home",
          "timestamp": "2026-06-15T12:34:05.000Z"
        }
      ]
    }
  ]
}
```

### Root fields

| Field            | Type            | Always present | Meaning                                                                                                                                                                                                             |
| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `schema_version` | integer         | yes            | `1` for this format. Branch on it.                                                                                                                                                                                  |
| `batch_id`       | string (UUIDv7) | yes            | New for each POST attempt. **For tracing only: never dedupe on it.** A retried batch may be rebuilt with a new `batch_id`. Dedupe on each location’s and event’s `id`.                                              |
| `session_id`     | string          | yes            | One tracking run, from `start()` to `stop()`, stable across a relaunch. Group a trip’s locations by it.                                                                                                             |
| `sent_at`        | string          | yes            | When the device built the batch (new for each attempt).                                                                                                                                                             |
| `device`         | object          | yes            | Constant per install.                                                                                                                                                                                               |
| `extras`         | object          | **no**         | Your opaque `string → string` map from `setExtras(...)`. Omitted when empty. Never carries identity.                                                                                                                |
| `reported_state` | object          | **no**         | Cloud-mode device health and config report. A custom backend can ignore it.                                                                                                                                         |
| `segments`       | array           | yes            | Identity segments in time order. Each is `{user_id?, locations[], geofence_events[]}`. A segment without `user_id` is anonymous: attribute it to `device.install_id`. Consecutive segments never share an identity. |

`device` carries `install_id` (UUIDv7, stable per app install), `platform` (`"android"` / `"ios"`), `sdk_version`, and `model` (omitted when blank).

The SDK mints `batch_id`, `install_id` and each location `id` as UUIDv7. Treat them as opaque strings: Beekon’s own API accepts any text as an `install_id` and any UUID version as a location `id`.

### `segments[].locations[]`

| Field                   | Type            | Always | Meaning                                                                                                                                  |
| ----------------------- | --------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                    | string (UUIDv7) | yes    | Location id. **The dedup key.**                                                                                                          |
| `timestamp`             | string          | yes    | When the location was recorded.                                                                                                          |
| `trigger`               | string          | yes    | `interval` · `motion` · `check_in` · `geofence` · `manual`                                                                               |
| `motion`                | string          | yes    | `moving` · `stationary` · `unknown`                                                                                                      |
| `is_mock`               | boolean         | yes    | OS flagged the location as mock.                                                                                                         |
| `latitude`, `longitude` | number          | yes    | Degrees.                                                                                                                                 |
| `accuracy`              | number          | no     | Horizontal accuracy, metres. Omitted when absent.                                                                                        |
| `speed`                 | number          | no     | Metres/second. Omitted when absent.                                                                                                      |
| `bearing`               | number          | no     | Course, degrees. Omitted when absent.                                                                                                    |
| `altitude`              | number          | no     | Metres. Omitted when absent.                                                                                                             |
| `activity`              | string          | no     | `stationary` · `walking` · `running` · `cycling` · `automotive` · `unknown`. Omitted when [activity detection](https://docs.getbeekon.com/guide/activity/) is off. |
| `quality`               | string          | no     | `low_accuracy` · `implausible_speed`. Omitted when the location has no quality flag.                                                     |
| `battery_percent`       | integer         | no     | Battery level when the location was recorded. Omitted when unknown.                                                                      |
| `is_charging`           | boolean         | no     | Charging at record time. Omitted when unknown.                                                                                           |
| `power_save_mode`       | boolean         | no     | OS power saver active at record time. Omitted when unknown.                                                                              |

### `segments[].geofence_events[]`

| Field         | Type            | Meaning                                          |
| ------------- | --------------- | ------------------------------------------------ |
| `id`          | string (UUIDv7) | Event id. Dedupe on it.                          |
| `geofence_id` | string          | The geofence that fired (your id).               |
| `type`        | string          | `enter` or `exit`.                               |
| `timestamp`   | string          | When the crossing occurred, on the device clock. |

A geofence event carries no position. When the device records a location at the crossing, that location travels separately in `locations[]` with `trigger: geofence`. Don’t reject a batch because of an event’s `type` or `geofence_id`: store or skip an event you don’t recognise and still return `2xx`. A `400` would make the device delete the whole batch, its locations included.

### Encoding rules

* **Transport:** `POST`, `Content-Type: application/json`, `Content-Encoding: gzip`. The body is always gzipped.
* **Timestamps:** ISO-8601 UTC with exactly three fractional digits and a literal `Z`: `YYYY-MM-DDTHH:MM:SS.mmmZ`.
* **Enums:** always lowercase `snake_case` (`check_in`, `low_accuracy`).
* **Numbers:** a whole number has no decimal point (`180`, not `180.0`).
* **Optional fields are omitted, never null.** A missing `accuracy`, `speed`, `bearing` or `altitude` means the OS didn’t report it. Treat it as unknown, never as `0`.
* **Bad locations are removed on the device.** A location with a non-finite `latitude` or `longitude` is dropped before sending; the rest of the batch still arrives.

Note

Identity is the segment’s `user_id`: the value of `setUserId(...)` when each location was recorded. `extras` is your own map with no reserved keys, and the SDK never reads identity from it. A self-managed backend can use the segment `user_id` or ignore it; [Beekon Cloud](https://docs.getbeekon.com/cloud/) counts monthly active users (MAU) from it.

## Build your ingest endpoint

Your endpoint receives the upload at the exact `url` in `SyncConfig` (Beekon follows no redirect), over HTTPS for any non-loopback URL, and answers with a status code that tells the SDK what to do with the batch. Every Beekon backend does four things:

1. **Gunzip and parse** the body (`Content-Encoding: gzip`, JSON inside).
2. **Dedupe on each location’s and event’s `id`** (`INSERT … ON CONFLICT DO NOTHING`) so retries do no harm. Never dedupe on `batch_id`: it is for tracing and may change on a retry.
3. **Store** each segment’s locations and geofence events with its `user_id`.
4. **Answer with the right status code.** `2xx` means the data is durably stored and the device can delete its copy. An empty `2xx` body is a complete answer. Return `400` or `422` only for a payload that will never be accepted, and `5xx` to ask for a retry.

### A complete receiver

```js
import express from 'express';
import zlib from 'node:zlib';


const app = express();


// Beekon sends gzipped JSON. Take the raw bytes; don't let a JSON body-parser
// touch them.
app.use('/ingest', express.raw({ type: '*/*', limit: '12mb' }));


// Stand-in for your database. In production use a table with a UNIQUE index
// on each location id, and INSERT ... ON CONFLICT DO NOTHING. The location id
// is the dedup key (batch_id is for tracing and may change on a retry).
const received = new Map(); // id -> row


app.post('/ingest', (req, res) => {
  // 1. Gunzip + parse.
  let envelope;
  try {
    const raw = req.headers['content-encoding'] === 'gzip'
      ? zlib.gunzipSync(req.body)
      : req.body;
    envelope = JSON.parse(raw.toString('utf8'));
  } catch {
    // unparseable: the SDK deletes the batch and doesn't retry
    return res.sendStatus(400);
  }


  // 2. (Optional) authenticate. Return 401 to make the SDK refresh its token
  //    and retry.
  //    if (!authorized(req)) return res.sendStatus(401);


  // 3. Idempotent ingest: dedupe on each row's id, so a replay changes nothing.
  for (const segment of envelope.segments ?? []) {
    for (const loc of segment.locations ?? []) {
      if (received.has(loc.id)) continue;
      received.set(loc.id, {
        ...loc,
        sessionId: envelope.session_id,
        installId: envelope.device.install_id,
        userId: segment.user_id ?? null, // record-time identity
      });
    }
    // ...store segment.geofence_events the same way (dedupe on their id too)...
  }


  // 4. Acknowledge, only after the data is durably written.
  return res.sendStatus(200);
});


app.listen(8080, () => console.log('ingest listening on :8080'));
```

### What your status code means

The SDK reads your HTTP status and acts on the batch. It deletes the batch from the device only on `2xx`, or on `400` and `422`, which say the payload will never be accepted:

| You return                      | SDK treats it as | What the SDK does                                                                                                                             |
| ------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| **2xx**                         | accepted         | Deletes the batch.                                                                                                                            |
| **400, 422**                    | rejected         | Deletes the batch and doesn’t retry. Use only for a payload that will never be accepted.                                                      |
| **401, 403**                    | auth             | Keeps the batch, [refreshes the token](https://docs.getbeekon.com/guide/sync-auth/#how-it-behaves) (if configured), retries once.                                       |
| **408, 429**                    | transient        | Keeps the batch, backs off, retries. `Retry-After` is honoured on 429.                                                                        |
| **5xx**, timeout, network error | transient        | Keeps the batch, retries with backoff. `Retry-After` is honoured on 503.                                                                      |
| **413**                         | too large        | Keeps the batch, halves it and retries, down to a single location or event. One that still gets `413` is deleted so it can’t block the queue. |
| **404, 3xx, any other 4xx**     | permanent        | Keeps the batch. Fix the endpoint.                                                                                                            |

Caution

Three rules on the SDK side to design around:

* **The body is always gzipped** (`Content-Encoding: gzip`). Your app can’t change this.
* **Redirects are refused.** A `3xx` is never followed, because following it would send the `Authorization` header to another origin. Serve `/ingest` directly, with no `301` or `302` to a CDN or a trailing-slash variant.
* **Requests time out at 30 s.** Store quickly, or queue the batch durably, return `2xx`, and process it afterwards.

A `2xx` that never reaches the device (a dropped connection, or a timeout after you committed) looks like a failed upload to the SDK. It sends the same locations and events again, possibly regrouped under a new `batch_id`. Dedupe on each `id` and a replay, even of a partial write, is safe.

### The optional response body

Your `2xx` may carry a JSON body. Every field is optional and unknown fields are ignored. Beekon Cloud uses this body to send data back to the device (a `config_revision` signal, a `geofence_halo` slice, pending device `commands`). A custom backend can implement any of it, and most implement none: a bare `200` with no body is a complete answer. A malformed body never undoes the upload: the batch stays deleted on the device.

Next: protect the endpoint with a rotating token on [Auth & token refresh](https://docs.getbeekon.com/guide/sync-auth/), and check uploads end to end with [`syncStatus`](https://docs.getbeekon.com/guide/sync/#observing-sync).
