> ## Documentation Index
> Fetch the complete documentation index at: https://docs.technicallyfit.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Offline batching

> Queue events while your code cannot reach the API, and send each one once when it can.

`OfflineQueue` keeps events while your code cannot reach TechnicallyFit (a gym floor
system that syncs at night, a service behind an unreliable link) and sends them in order
when you call `flush`. Streams reach the API as summaries rather than raw sample lists:
reduce streaming device samples into summary observations before queuing them, or stream
the workout over [Real-time](https://docs.technicallyfit.com/guides/real-time.md) when connected so its folded summaries
arrive as ordinary readings when the session ends.

* **Checked when queued.** An invalid event fails when you add it, and nothing is queued.
* **Keys fixed when queued.** Each event gets its idempotency key (or keeps its
  `source.record_id`) when it is added, and the queue saves it through your storage. A
  flush after a crash sends the same keys, so the API answers `duplicate` instead of
  storing anything twice.
* **One flush at a time.** A second `flush` waits for the first and then sends only what
  is left, so each event is sent once.
* **In order.** Events are sent oldest first through `POST /v1/events:bulk`, in requests
  within the API's limits, and the API decides each teammate's events in that order.
* **Removed when answered.** `accepted` and `duplicate` events leave the queue. A
  `rejected` event leaves it too and is reported in the result, because sending the same
  copy again gets the same answer. A request that fails as a whole leaves its events, and
  every later one, in the queue.

The bulk endpoint takes an organization key, so the queue runs where your key is: your
servers or a sync service, never an app on a person's device.

## Storage

Give the queue a storage with `load` and `save`. It saves the whole queue after every
change. `MemoryStorage` keeps it in memory, for tests.

```ts theme={null}
import { readFile, writeFile } from 'node:fs/promises';
import { OfflineQueue, createClient, event } from '@technicallyfit/sdk';
import type { BulkEvent, OfflineStorage } from '@technicallyfit/sdk';

const file = './technicallyfit-queue.json';
const storage: OfflineStorage = {
  load: async () => {
    try {
      return JSON.parse(await readFile(file, 'utf8')) as BulkEvent[];
    } catch {
      return [];
    }
  },
  save: (events) => writeFile(file, JSON.stringify(events)),
};

const tf = createClient({ credential: process.env.TF_API_KEY ?? '', baseUrl: process.env.TF_API_BASE });
const queue = new OfflineQueue({ client: tf, storage });

await queue.add(
  'member-1042',
  event.loggedSet({
    at: '2026-11-17T15:02:00Z',
    route: 'org-floor',
    recordId: 'org-floor:set:91a7',
    movement: { name: 'Back squat' },
    set: { number: 1, reps: 5, load: { value: 100, unit: 'kg' } },
  }),
);

const result = await queue.flush();
console.log(result.accepted, result.duplicate);
for (const { event: rejected, reason } of result.rejected) console.log(rejected.teammate, reason?.code);
```

```python theme={null}
import json
import os
from pathlib import Path

from technicallyfit import Client, OfflineQueue, event


class FileStorage:
    def __init__(self, path: Path) -> None:
        self.path = path

    def load(self) -> list[dict]:
        return json.loads(self.path.read_text()) if self.path.exists() else []

    def save(self, events: list[dict]) -> None:
        self.path.write_text(json.dumps(events))


tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))
queue = OfflineQueue(tf, FileStorage(Path("technicallyfit-queue.json")))

queue.add(
    "member-1042",
    event.logged_set(
        at="2026-11-17T15:02:00Z",
        route="org-floor",
        record_id="org-floor:set:91a7",
        movement={"name": "Back squat"},
        number=1,
        reps=5,
        load={"value": 100, "unit": "kg"},
    ),
)

result = queue.flush()
print(result.accepted, result.duplicate)
for item in result.rejected:
    print(item["event"]["teammate"], item["reason"]["code"])
```

A flush retries a rate limit or a temporary failure the way every SDK call does. When it
still fails, it throws (or raises) and keeps the events: call `flush` again later.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.