Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Offline and Background Sync

The Offline Outbox Pattern

Build reliable offline writes: optimistic UI, a durable outbox, idempotency keys, ordering, retries and conflict resolution with runnable simulations.

Reading data offline is the easy half of an offline app. The hard half is writing: the user edits a note on a train, closes the laptop, and expects the change to appear on their phone tomorrow. The outbox pattern is the standard answer. Every change is first stored locally in a durable queue, the UI updates immediately, and a separate process delivers the queue to the server whenever it can.

You already have the pieces: IndexedDB for storage and Background Sync for waking up later. This lesson shows how to put them together without losing, duplicating or reordering changes.

The shape of the pattern

flowchart LR
  U["User action"] --> L["Write to local store"]
  L --> O["Append to outbox"]
  L --> UI["Update the screen (optimistic)"]
  O --> W["Worker / sync loop"]
  W -->|"POST with idempotency key"| S["Server"]
  S -->|"200 OK"| D["Remove from outbox"]
  S -->|"5xx / network error"| R["Keep and retry later"]

The screen never waits for the network. The outbox is the source of truth for what is still unsent.

Two stores are involved: a notes store with the current data, and an outbox store with pending operations. Writing to both should happen in one IndexedDB transaction, so you can never have a saved note with no queued operation or the other way around.

What an outbox record contains

Store operations (what the user did), not just snapshots:

JavaScript
{
  seq: 17,                       // auto-increment: defines the order
  id: "9f1c-...-b2",             // idempotency key, generated on the client
  type: "note.update",
  noteId: "n42",
  payload: { title: "Plan", body: "..." },
  baseVersion: 5,                // version the edit was based on
  createdAt: 1734000000000,
  attempts: 0
}

The id is the most important field. Create it with crypto.randomUUID() when the user acts, and send it to the server with the request (for example in an Idempotency-Key header). If the first attempt succeeded but the response was lost, the retry carries the same key, and the server recognizes it and returns the earlier result instead of creating a second note.

Try it: idempotency keys

This stand-in server remembers the keys it has seen. The "network" loses the first response, which is the classic cause of duplicates.

JS Retries without duplicates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without the key check the server would hold two notes after the second attempt. With it, retrying is always safe.

Order matters

Operations on the same record depend on each other: create, then update, then delete. Deliver them in seq order and stop at the first failure for that record. If "create" fails and you still send "update", the server answers 404 and you drop a valid edit.

Two simple policies:

  • Strict queue: one worker sends operations one at a time in order. Easy to reason about, slower.
  • Per-record queues: order is kept within one record but different records go in parallel.

You can also compact the queue before sending: three updates to the same note while offline can be merged into one, and a create followed by a delete can be removed entirely.

JS Compacting an outbox

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Conflicts

Offline apps create a new kind of bug: two devices edit the same record while disconnected. When both reach the server, one change must win, or both must be combined. Common strategies, from simplest to richest:

Strategy How it works Good for
Last write wins The newest timestamp replaces the record. Settings, toggles, low-value data
Version check Client sends baseVersion. Server rejects stale edits with 409. Documents where losing data is not acceptable
Field-level merge Merge changed fields separately. Forms with independent fields
CRDTs or operational transforms Mathematically merge concurrent edits. Collaborative text

The version check is the best default. The server compares baseVersion with the stored version. A mismatch returns 409 Conflict with the current record, and the client then either merges automatically or asks the user.

JS Detecting a conflict with versions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Showing the state honestly

Optimistic UI means the user sees their change at once, but they should still be able to tell what is unsynced. Small touches help: a "Saved on this device" label, a clock icon next to pending items, a count of queued changes in the header, and a clear error row with a Retry button when an operation is rejected for good (for example a validation error from the server). Never silently discard an operation that failed permanently.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the local data write and the outbox append happen in one transaction?

    A single transaction commits both or neither, keeping the local state and the pending queue consistent.
  2. 2. What does the idempotency key protect against?

    The server returns the original result for a key it has already processed, so retries are safe.
  3. 3. A note was created and then deleted while offline. What should compaction do?

    The record never reached the server, so both operations can be dropped.
  4. 4. What does a 409 response to a versioned update mean?

    baseVersion did not match the stored version, so someone else changed the record first.

Summary

  • Write locally first, queue an operation in the same transaction, update the UI optimistically.
  • Give every operation a client-generated idempotency key so retries are safe.
  • Deliver in order, compact the queue, and stop a record's queue at its first failure.
  • Detect conflicts with a version number and decide how to merge.
  • Show pending and failed states; never drop failed operations silently.

Next: Push Notifications: The Big Picture