# Offline sync explained: retries, duplicate writes, and conflicts

Suppose a device sends a check-in, the server commits it, and the response never reaches the device. The device cannot tell whether the write succeeded. Retrying is necessary—but retrying carelessly can turn one admission into two.

Offline applications must answer three separate questions: how to preserve work locally, how to recognize a retry, and how to handle two legitimate changes that disagree. Loomup's sync protocol treats these as separate responsibilities. Its current v1 implementation is an opt-in preview, with explicit version conflicts rather than a universal automatic merge policy.

## Keep the pending work with the local state

A responsive screen is only part of offline behavior. The application also needs to retain enough state to retry work after a page reload or process restart.

Loomup's browser offline package manages a SQLite/WASM database whose binary snapshot is persisted in IndexedDB. The lower-level `SyncStore` can use other persistence adapters. Its default in-memory adapter is useful for tests and server code, but it cannot preserve pending work across process restarts.

```ts
import { createOfflineClient } from "@loomup/offline";

const offline = await createOfflineClient({
  url: "http://127.0.0.1:3000",
  database: "checkin-demo.sqlite",
  resources: ["attendees", "checkins"],
});

offline.subscribe((status) => {
  console.log(status.phase, status.pending);
});
```

The resources must already exist and allow the current user to read and write the relevant records. The [Fieldday tutorial](/blog/offline-event-check-in-astro-sqlite) supplies a runnable demo.

Local browser persistence has limits: clearing site data, storage eviction, or losing a device can lose unsent work. A local write is not proof of a server commit. Make that distinction visible in the product with a pending indicator and a clear recovery path.

## Give a retry the same identity

A record ID identifies a row. A mutation ID identifies a particular attempt to change application state. They solve different problems.

Loomup assigns stable identities to queued offline mutations and retains server receipts for idempotent replay. An exact retry of the same mutation returns its existing receipt instead of applying the application write again. Changing the identity on every HTTP attempt defeats that mechanism.

Consider the lost-response case:

1. The device persists mutation A locally.
2. It uploads A; the server commits the check-in and its sync receipt.
3. The network drops before the device sees the response.
4. The device uploads the same A again.
5. The server recognizes A and returns the recorded result.

The practical property is safe replay of the same mutation within the protocol's receipt rules. It is not a claim that the network delivers every message once. Keep retries inside the SDK's queue instead of implementing a second queue that creates a new mutation for every failed HTTP request.

## A business duplicate is a different problem

If North Gate and South Gate each admit the same attendee, they have produced two different observations. They receive different mutation IDs. Idempotency must not erase one merely because the attendee ID matches.

Fieldday stores admissions as individual events and reports repeated attendee IDs on the central dashboard. That preserves evidence for an operator to review. An alternative application might reject the second admission centrally, but a disconnected device still cannot know the other device's latest decision before reconnecting.

Decide whether your domain should reject, retain, merge, or flag conflicting observations. A transport retry policy cannot choose that business rule for you.

## Detect a stale edit before overwriting data

Editing an existing record introduces another conflict. Two devices can start from the same version and make different changes.

Loomup sync updates and deletes carry the cached record's `base_sequence`. If the server record has moved to another sequence, the server returns an explicit `version_conflict`. `SyncStore` retains the optimistic local state and exposes the conflict so the application can resolve it.

| Situation | Application decision |
| --- | --- |
| The server version is correct | Discard the local conflict and bootstrap canonical state |
| Both edits contain useful information | Show both versions, produce a deliberate merge, then retry against the current sequence |
| The record was deleted elsewhere | Decide whether the user's work belongs in a new record or should be discarded |

The lower-level store exposes `resolveConflict(id, "discard")` and `resolveConflict(id, "retry", mergedData)`. Use the conflict identifier supplied by the store. A retry should reflect a resolved decision, not an endless loop that silently overwrites another user's work. See the [sync conflict contract](/docs/sync#conflicts) for details.

## Treat authentication failures and resets differently

An expired token is not evidence that the local database is stale. On `401`, refresh authentication and retry the same operation. Do not erase a pending queue simply because a session expired.

A `reset_required` response means the sync context must be rebuilt. This can happen when the server has compacted past an old cursor or the schema or authorization context has changed. Loomup re-bootstraps authorized state and reapplies still-pending optimistic mutations. Those writes remain subject to current permissions and conflict checks.

Persisted sync state is isolated by project URL, identity, and resource set. This matters on shared devices: a new user must not inherit another user's cached rows. Review the [authentication and reset behavior](/docs/sync) when designing sign-out and account-switching flows.

## Test the boundaries that fail in practice

A successful online demo does not verify offline recovery. Exercise these scenarios against your application:

- Queue a write, reload, then reconnect. Check both the persisted queue and the final server row.
- Drop a response after the server commits. Retry the same mutation and check that the business write was not duplicated.
- Edit one record on two disconnected devices. Reconnect in both orders and inspect the visible conflict.
- Edit on one device and delete on the other. Make the recovery decision explicit.
- Expire a session with pending work. Verify that reauthentication preserves the queue.
- Switch users on the same browser. Check that the previous user's rows are no longer visible.

For a concrete starting point, [run Fieldday](/blog/offline-event-check-in-astro-sqlite). Watch the local queue and central dashboard separately. That separation makes the difference between “recorded here” and “accepted by the server” tangible.
