A tab closed mid-sentence. When it opened again the paragraph was gone, and the little "Syncing…" pill had been lying for the last two minutes.
That pattern is common enough that I now look for it before reading any offline-first code: the thing that decides what to save lives in memory, and memory is the one store a closed tab does not keep. An outbox is the fix, and it is smaller than a sync engine.
Here is the whole design: one IndexedDB store, one idempotency key per mutation, one flush loop, and a server-side dedupe table that makes a double flush harmless.
Why "sync" is the wrong word
A sync engine implies reconciliation: vector clocks, merge functions, conflict UI. Most client documents do not need that. They need a queue that outlives the tab.
Three failure modes cover almost every bug I have seen in this area:
- The write depends on a component. The save runs in an effect that unmounts, or behind a debounce that never fires because the tab died first.
- The retry is not idempotent. A timeout looks like a failure, the client retries, and the server now has two line items where the user typed one.
- The queue is not durable. A
const pending = []in a module scope is durable only until the next navigation.
All three disappear if the mutation is a row on disk before it is a request on the wire.
The outbox record
One object store, keyed by a client-generated id. The id is the idempotency key, so it is generated once and never regenerated on retry.
// outbox.ts export interface OutboxItem { id: string; // crypto.randomUUID() — also the idempotency key documentId: string; seq: number; // monotonic per document, from a durable counter baseRevision: number; // the revision the edit was made against op: "patch" | "append" | "delete"; payload: unknown; createdAt: number; // Date.now() attempts: number; nextAttemptAt: number; } seq is the part people skip. It gives the server a total order per document without asking the client's clock to be right, and it makes "which edit won" a comparison instead of a guess.
Enqueue before you send
The rule: the write to the outbox is the save. The network call is a delivery detail.
export async function enqueue(db: IDBDatabase, item: OutboxItem) { const tx = db.transaction("outbox", "readwrite", { durability: "strict" }); await request(tx.objectStore("outbox").put(item)); await done(tx); } durability: "strict" is not decoration. The default relaxed mode in Chromium can acknowledge a transaction before the data is on disk, which is exactly the window a crash needs.
After enqueue, try a flush. If the flush fails, the item stays. Either way the user's paragraph exists somewhere that survives the tab.
Flush in order, stop at the first error
Ordering matters more than parallelism. If edit 2 depends on edit 1 and you send them concurrently, the server can apply them backwards.
export async function flush(db: IDBDatabase, documentId: string) { const items = await getPending(db, documentId); // sorted by seq for (const item of items) { if (item.nextAttemptAt > Date.now()) continue; try { const res = await fetch("/api/documents/" + documentId + "/ops", { method: "POST", headers: { "content-type": "application/json", "idempotency-key": item.id }, body: JSON.stringify({ seq: item.seq, baseRevision: item.baseRevision, op: item.op, payload: item.payload }), }); if (res.status === 409) { // stale baseRevision: rebase or ask, but do not drop the item await rebase(db, item, await res.json()); continue; } if (!res.ok) throw new Error("flush failed: " + res.status); await remove(db, item.id); // only after a confirmed 2xx } catch { item.attempts += 1; item.nextAttemptAt = Date.now() + backoff(item.attempts); await put(db, item); return; // keep order; try again later } } } const backoff = (n: number) => Math.min(300_000, 1_000 * 2 ** n) + Math.random() * 500; Two details worth keeping: remove runs only after a 2xx, and a failure returns instead of continuing. Skipping ahead in the queue is how a delete lands before the create it was meant for.
Make the server tolerant of a double send
A timeout is not a failure. The client cannot tell "the server never got it" from "the server got it and the reply was lost", so the server must assume it will be told twice.
create table document_ops ( idempotency_key uuid primary key, document_id uuid not null references documents(id) on delete cascade, seq bigint not null, applied_at timestamptz not null default now(), result jsonb not null ); -- unique per document, not globally: two clients both start at seq 1 create unique index on document_ops (document_id, seq); The handler does one insert with on conflict (idempotency_key) do nothing returning id, and if nothing was returned it answers with the stored result. Same response, no second line item, no apology needed.
The (document_id, seq) unique index is the second guard: it catches the case where a bug retries with a fresh key but the same sequence number.
What about conflicts?
You need a policy before you need an algorithm. For a document with one or two editors, last-writer-wins per field, with a visible "updated by" line and a revision history, is fine and is what most users expect.
| Approach | Cost | When it is right |
|---|---|---|
| Last write wins, whole document | Lowest | One editor at a time, audit trail matters more than merge quality |
| Last write wins per field | Low | Small teams, mostly disjoint edits |
| Operational transform | High | Real-time shared text, mature team |
| CRDT | High | Offline-first collaborative text, long-lived forks |
An outbox is orthogonal to all four. It answers "will this edit reach the server", not "which edit is better". Pick the merge policy separately, and pick the cheap one until a user complains.
The tests that catch the real bugs
Three, and all three are cheap:
- Kill before flush. Block the network, type, close the tab, reopen, assert the text is there and one request goes out.
- Double send. Send the same item twice with the same key, assert one row.
- Out of order. Send seq 2 before seq 1, assert the server rejects rather than reorders.
If test one passes, you have an outbox. If test two passes, you have an idempotent API. If test three passes, you have ordering. Everything else is UI.
Checklist
- One durable store, written before any request.
- Client-generated id used as the idempotency key.
- Monotonic
seqper document, assigned from a durable counter. - Sequential flush, stop on first error, exponential backoff with jitter.
- Delete from the outbox only on a 2xx.
- Server dedupe table with a unique key and a stored result.
- A defined merge policy, written down, not implied.
- A visible signal when the queue is non-empty, because "saved" that means "queued" is a lie users eventually notice.
Elsewhere in this series
The Client Thread is about the artefacts a project runs on — proposals, contracts, change requests and invoices — and the engineering behind keeping them in one place:
- The data model behind a freelancer's client thread
- Tracked document links without an analytics stack
- An outbox, not a sync engine: offline edits that survive a closed tab
Revercue keeps proposals, contracts and invoices on one client thread, and the offline editor is built on exactly this queue. Have a look if you want to see the outbox in a real document.

