# Turn on sync

> Turn on server sync with a SyncConfig, understand the upload triggers and batching, observe sync progress, run local-only, and check your backend against the list.

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

Beekon stores every location on the device. **Sync** sends those locations to a backend you run: Beekon batches the stored history, POSTs it as a small JSON envelope, and deletes the locations your server acknowledges. Sync is off until you pass a `SyncConfig` with a `url`. Without one, nothing leaves the device ([local-only mode](#local-only-mode)).

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

## Turn on sync

Add a `sync` block to your config. The only required field is `url`.

* Android

  ```kotlin
  Beekon.configure(
    BeekonConfig.Custom(
      sync = SyncConfig(
        url = "https://api.example.com/locations",
        headers = mapOf("Authorization" to "Bearer <static-token>"), // optional
        intervalSeconds = 300,
        batchSize = 100,
      ),
    ),
  )
  ```

* iOS

  ```swift
  try await Beekon.shared.configure(
    BeekonConfig.custom(
      sync: SyncConfig(
        url: URL(string: "https://api.example.com/locations")!,
        headers: ["Authorization": "Bearer <static-token>"], // optional
        intervalSeconds: 300,
        batchSize: 100
      )
    )
  )
  ```

* Flutter

  ```dart
  await Beekon.instance.configure(
    BeekonConfig.custom(
      sync: SyncConfig(
        url: 'https://api.example.com/locations',
        headers: {'Authorization': 'Bearer <static-token>'}, // optional
        intervalSeconds: 300,
        batchSize: 100,
      ),
    ),
  );
  ```

* React Native

  ```ts
  await Beekon.configure({
    mode: 'custom',
    sync: {
      url: 'https://api.example.com/locations',
      headers: { Authorization: 'Bearer <static-token>' }, // optional
      intervalSeconds: 300,
      batchSize: 100,
    },
  });
  ```

Beekon uses `url` as given and adds no path. Put static credentials, such as an API key, in `headers`. For rotating bearer tokens, use [`auth`](https://docs.getbeekon.com/guide/sync-auth/#configure-declarative-refresh) instead: the SDK then refreshes the token itself, in the background too.

### When uploads happen

With a `SyncConfig` set, these triggers start an upload. The first one to fire uploads, and they all feed the same batched queue:

| Trigger                                             | When it fires                                                        |
| --------------------------------------------------- | -------------------------------------------------------------------- |
| A geofence event is recorded                        | Immediately. Geofence events are rare and worth sending at once.     |
| A session stops with locations pending              | Immediately, so the end of the trip is sent.                         |
| Every `intervalSeconds` (with a per-platform floor) | On the schedule, so nothing waits longer than the interval.          |
| `sync()` is called                                  | Immediately                                                          |
| A regular location is persisted                     | Only when `syncThreshold: N ≥ 1` **and** ≥ `N` locations are pending |

The first four always apply. `syncThreshold` controls only the last: an early upload of regular locations while moving. At `0`, the default, regular locations wait for the `intervalSeconds` schedule.

A batch carries exactly one **session**: one run of tracking between `start()` and `stop()`, named by the envelope’s `session_id`. Beekon sends the oldest pending session first, oldest locations first, so your server can rebuild each tracking run.

### SyncConfig

| Field             | Default    | What it does                                                                                                                 |
| ----------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `url`             | (required) | Your ingest endpoint, used verbatim.                                                                                         |
| `headers`         | `{}`       | Static headers on every POST, such as a fixed API key. When `auth` is set, its `Authorization` header replaces a static one. |
| `intervalSeconds` | `300`      | Seconds between scheduled uploads, with a 60 s floor. See [Upload interval](#upload-interval) below.                         |
| `batchSize`       | `100`      | Most locations per POST, clamped to `1…1000`. A triggered upload still sends in `batchSize` chunks.                          |
| `syncThreshold`   | `0`        | Pending-location count that triggers an early upload of regular locations. `0` disables it.                                  |

Pick `syncThreshold` for how fresh the server must be:

| Goal                                                                      | Config                                 |
| ------------------------------------------------------------------------- | -------------------------------------- |
| Default: scheduled batches, geofence events and session ends sent at once | `syncThreshold: 0`                     |
| Live map / fleet tracking                                                 | `syncThreshold: 10`                    |
| Every location as soon as it’s stored                                     | `syncThreshold: 1`                     |
| Backend accepts one location per request                                  | `batchSize: 1` (pair with a threshold) |

### Upload interval

`intervalSeconds` limits how old the newest upload can get; `syncThreshold` limits how far behind the server is while the device moves, at most `N` regular locations.

* **Android, tracking session running:** every `intervalSeconds`, no more often than every 60 seconds, on screen or not. The upload loop lives with the tracking foreground service.
* **Android, no session:** through WorkManager, no more often than about every 15 minutes. `syncThreshold` isn’t bound by this floor.
* **iOS:** every `intervalSeconds` while the app process runs. A suspended app uploads when the system runs its [background refresh task](#background-uploads-on-ios).

A shorter `intervalSeconds` is accepted but has no further effect. To get locations sooner, set `syncThreshold`. Geofence events and the end of a session always upload at once.

### Background uploads on iOS

When iOS suspends the app (for example, while location updates are paused at a stop, or after tracking stops), Beekon uploads from a `BGTaskScheduler` refresh task. Without the task, a suspended app uploads nothing until it runs again. The task needs the `fetch` background mode, the `com.getbeekon.sdk.sync` identifier and a `Beekon.registerBackgroundTasks()` call at launch, all set out in [iOS: background tasks](https://docs.getbeekon.com/start/setup/#ios-background-tasks). iOS decides when it runs: every 15 minutes or so for an app in daily use, hours apart or not at all for one that is rarely opened.

### Observing sync

The `syncStatus` stream reports the health of the upload queue. It has three states, and Failed carries a reason:

| State                     | Meaning                                                                                                                                            |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Idle                      | Everything is uploaded, or sync is not configured.                                                                                                 |
| Pending                   | An upload is running, or a transient failure (`5xx`, `408`, `429`, a timeout, no network) is being retried. Retries are normal and need no action. |
| Failed, reason `auth`     | The server answered `401` or `403` and a token refresh didn’t fix it. Supply new credentials.                                                      |
| Failed, reason `rejected` | The server answered `400` or `422`. The batch was deleted; fix the payload handling on your server.                                                |

There is no separate success state: a finished upload goes back to Idle, or stays Pending while more locations wait. Failed clears on its own once the cause is fixed, for example after a refreshed token.

The names follow each platform: Android `SyncStatus.Idle`, `Pending`, `Failed(SyncFailure.Auth | Rejected)`; iOS `.idle`, `.pending`, `.failed(.auth | .rejected)`; Flutter `SyncIdle`, `SyncPending`, `SyncFailed(SyncFailure.auth | rejected)`; React Native `{ kind: 'idle' | 'pending' }` or `{ kind: 'failed', reason: 'auth' | 'rejected' }` from `onSyncStatus`. New failure reasons may arrive in a minor release, so keep a default branch.

Call `pendingUploadCount()` for the number of locations still waiting, and `sync()` to start an upload now.

Tip

`setExtras({ ... })` attaches your own metadata to each batch, such as a trip tag. The map travels in the envelope’s `extras` on the next upload and is left out when empty. For a stable per-user id, use `setUserId(...)`. Beekon binds it to each location when the location is recorded and sends it as the segment’s `user_id`. [Beekon Cloud](https://docs.getbeekon.com/cloud/) counts monthly active users (MAU) from it.

## Local-only mode

With no `sync` block, Beekon is **local-only**. It tracks, stores locations and geofence events on the device, and serves history reads and geofencing, but makes no network request. Nothing leaves the device.

Local-only mode also deletes locations older than 7 days. With `sync` set, there is no age limit: the whole backlog is kept, up to the 100,000-location cap, so a device that was offline for a long time can upload everything when it reconnects.

## Backend checklist

Your endpoint accepts `POST` at the exact `url` (no redirect), over HTTPS for any non-loopback URL. It gunzips the body, dedupes on each location’s and event’s `id`, stores the data with each segment’s `user_id`, and answers `2xx` once the data is durable. The steps and a working receiver are on [Build your ingest endpoint](https://docs.getbeekon.com/guide/payload/#build-your-ingest-endpoint).

Next: the format your endpoint receives and a working receiver, on [Upload payload & ingest endpoint](https://docs.getbeekon.com/guide/payload/).
