Core Concepts

Offline Write Queue

What happens to a write when the network is not there to receive it, how global and per user queues differ, how queued user writes are encrypted at rest, what happens when the server says no, how deletions fit the same model as creates and updates, and the one category of write that should never go through this system at all.

The core idea: a write is never lost, only delayed

When a channel is registered with a queueConfig, any write to it that cannot reach the server is captured and held rather than discarded. It leaves the queue in only three ways: the server accepts it, the server confirms it already has it, or the user explicitly discards it. If the server answers with an error, the write is kept and shown to the user as a failed change they can retry or discard. Your UI code for "save this note" does not need an offline branch; the same call works identically online or off.

1

Turning a channel into an offline safe write path

Add a queueConfig to any registration and every write against that channel becomes offline safe. Nothing else about the registration changes, except that you decide whether the queue is a user queue or a global queue (next step).
lib/flux.ts (excerpt)
1flux.register({
2 channel: 'notes',
3 idbKey: 'notes:mine',
4 ttl: 'medium',
5
6 ingestionType: 'COLLECTION_ALL',
7 diffBeforeUpdate: true,
8 event: 'UPDATE',
9 scope: 'user',
10 store: notesStoreAdapter,
11
12 queueConfig: {
13 storeName: 'notes_mutation_queue',
14 replayEndpoint: '/api/notes',
15 method: 'POST',
16 },
17})
replayEndpoint is where the queued write gets sent once it is safe to send. Until then, it sits captured locally — surviving a page refresh, a browser crash, and even a tab freeze, so nothing is lost between the moment the user hits save and the moment the network is actually available to hear about it.
Writes made while the device is online are sent directly and are not queued. The queue only holds writes that could not be sent.
2

Global queues and user queues

Every queued write belongs to exactly one of two kinds. The kind is decided at write time by two arguments to addQueueEntrySafe(), the scope and the userId, and it must match the scope on the channel's registration.
Global queueUser queue
Use it forPublic forms and anything with no signed in user (contact, waitlist)Anything tied to an account (settings, notes, support messages, edits)
Write call…, 'global', null…, 'user', userId
Registrationscope: 'global'scope: 'user'
Stored asReadable body + checksum, userId nullEncrypted body, readable header with the user id
ReplaysAny time the network is reachable, signed in or outOnly for that user, only while their key is unlocked
Locked keyNot applicableNew writes are refused with FluxLockedError
Cleared by logoutNeverKept sealed (encryption on) or deleted (encryption off)
Dedupe compares withGlobal entries onlyThat user's entries only
A user write:
lib/queue/queueNote.ts
1import { addQueueEntrySafe, FluxLockedError } from '@tsworldtech/flux'
2import { getActingUserId } from '@/lib/stores/authStore'
3
4// A USER queue entry: 'user' scope + a real userId.
5// This is what makes Flux encrypt it and tie it to one account.
6export async function queueNote(payload: Record<string, any>) {
7 const userId = await getActingUserId() // no network round trip
8 if (!userId) throw new Error('Sign in to save changes offline.')
9
10 try {
11 return await addQueueEntrySafe(
12 {
13 channel: 'notes',
14 storeName: 'notes_mutation_queue',
15 endpoint: '/api/notes',
16 method: 'POST',
17 payload,
18 timestamp: Date.now(),
19 dedupeKey: 'note:' + payload.id,
20 dedupeStrategy: 'replace',
21 } as any,
22 'MyApp',
23 undefined, // onStorageFallback
24 undefined, // onDuplicate
25 undefined, // mergeHandler
26 'user', // scope
27 userId // tenant
28 )
29 } catch (err) {
30 if (err instanceof FluxLockedError) {
31 // Their key is locked. Flux refuses to store plaintext instead.
32 throw new Error('Secure storage is locked. Sign in again to save changes offline.')
33 }
34 throw err
35 }
36}
A global write:
lib/queue/queueContactMessage.ts
1import { addQueueEntrySafe } from '@tsworldtech/flux'
2
3// A GLOBAL queue entry: a public form with no signed in user.
4// Not encrypted (readable body + checksum). userId is null.
5// Replays with userId: null, signed in or out.
6export async function queueContactMessage(payload: Record<string, any>) {
7 return addQueueEntrySafe(
8 {
9 channel: 'contact',
10 storeName: 'contact_queue',
11 endpoint: '/api/contact',
12 method: 'POST',
13 payload,
14 timestamp: Date.now(),
15 dedupeKey: String(payload.email).toLowerCase(),
16 dedupeStrategy: 'reject',
17 } as any,
18 'MyApp',
19 undefined,
20 undefined,
21 undefined,
22 'global', // scope
23 null // tenant: nobody
24 )
25}
Leaving off the last two arguments makes a global entry

scope defaults to 'global'. A user write that forgets to pass 'user' and the user id is stored as a global record: not encrypted, userId: null, and invisible to that user's replay. Replay then "does nothing" with no error.

typescript
1// The easiest mistake to make:
2//
3// addQueueEntrySafe(entry, 'MyApp')
4//
5// With the last two arguments left off, the scope defaults to 'global'
6// and there is no userId. The entry is stored as a GLOBAL record:
7// - readable body + checksum, NOT encrypted
8// - userId: null
9// - a signed in user's replay (userId: 'uuid') never selects it
10//
11// For anything that belongs to an account, always pass BOTH:
12// addQueueEntrySafe(entry, 'MyApp', undefined, undefined, undefined, 'user', userId)
Resolve the user without the network

Queued writes happen exactly when the network is missing, so the helper that finds the user id must never make a request. Read it from your auth store, then from the locally stored session, then from the last known user namespace Flux already renders the cached UI from. Return null only when nobody is signed in, and treat that as "cannot queue a user write", never as "queue it as global".

3

Queued user writes are encrypted at rest

With encryption configured on createFlux(), a user queue entry is sealed with AES-GCM before it is written to disk. The key comes from your own backend through a key route, so Flux itself never holds a master secret. Configure it once:
typescript
1// Turning on encryption (once, in createFlux). Full walkthrough, including
2// the key route your backend needs, is in guides/encryption_key_route.
3const flux = createFlux({
4 adapter: createSupabaseAdapter(supabase),
5 storagePrefix: 'MyApp',
6
7 encryption: {
8 keyProvider: createHttpKeyProvider({ endpoint: '/api/flux/key' }),
9 sessionKeyIdleMs: 7 * 24 * 60 * 60 * 1000, // key stays usable 7 days idle
10 queueRetentionMs: 30 * 24 * 60 * 60 * 1000, // abandoned sealed writes deleted after 30 days
11 allowLegacyPlaintext: true, // false once everyone has upgraded
12 onLocked: (userId, reason) => console.warn('[flux] locked', userId, reason),
13 },
14
15 integrity: { queueTamperAction: 'delete' }, // or 'quarantine'
16})
Here is what the two kinds look like in IndexedDB, and the quick way to tell them apart when a queue is not behaving:
typescript
1// What is actually stored in IndexedDB -> queue.
2//
3// USER entry (encrypted):
4// {
5// v: 2,
6// id: 'MyApp_notes_mutation_queue_1792051031065_ab12cd',
7// storeName: 'notes_mutation_queue',
8// userId: '8f1c0c9e-....', // readable on purpose
9// status: 'pending', // readable on purpose, bound to the tag
10// revision: 0,
11// timestamp: 1792051031065,
12// enc: { iv: '...', ct: '...', kid: '...' } // payload, endpoint, method,
13// // dedupeKey, failure record
14// }
15//
16// GLOBAL entry (checksummed, readable):
17// {
18// v: 2,
19// id: 'MyApp_contact_queue_1792051031065_ef34gh',
20// storeName: 'contact_queue',
21// userId: null,
22// status: 'pending',
23// revision: 0,
24// timestamp: 1792051031065,
25// body: { payload: { ... }, method: 'POST', endpoint: '/api/contact', ... },
26// sum: 'sha256-hex...' // detects edits, forgeable by a script
27// }
28//
29// Quick check when something is not replaying:
30// "userId: null" with body + sum -> written as global
31// "userId: uuid" with enc -> written as a user entry
The header (id, store, user, status, revision, timestamp) stays readable so your app can show "3 unsent changes" and replay can filter by user before decrypting anything. Every header field is bound into the encryption tag, so editing one in DevTools makes the record fail verification instead of changing how it behaves.
A user's key can be locked: not yet unlocked on this device, expired after the idle window, or the key route was unreachable at sign in. Here is what that does to a queue:
typescript
1// When a user's key is locked (not unlocked yet on this device, expired
2// after the idle window, or the key route was unreachable at sign in):
3//
4// QUEUEING a user write -> throws FluxLockedError. Nothing is stored.
5// Show "sign in again" instead of falling
6// back to a global entry.
7// READING the queue -> sealed entries are not returned. Their
8// readable header still lets Flux count them.
9// REPLAYING -> sealed entries are skipped, not failed,
10// not deleted. They send after unlock.
11// GLOBAL queues -> unaffected. No key involved.
12//
13// The first unlock on a device needs your key route, so it needs the
14// network. onLocked fires with:
15// 'offline-needs-login' first sign in on this device happened offline
16// 'provider-error' the key route failed or returned something invalid
17// 'unwrap-failed' the stored wrapped key could not be opened
The first unlock on a device needs the network

A user who signs in for the first time on a device while offline stays locked, because Flux has no way to ask the key route. Queue writes for them fail with FluxLockedError until they sign in online once. After that, the key is kept on the device for the idle window, so offline cold starts keep working. See guides/encryption_key_route for building the route.

Every stored record is also verified when it is read. A record that fails verification is never sent:
typescript
1// Every stored queue record is verified when it is read.
2//
3// user entry AES-GCM tag must verify (header + body bound together)
4// global entry checksum must match
5//
6// A record that fails is NEVER sent. By default it is deleted and
7// reported once to your integrity listener. With
8// integrity: { queueTamperAction: 'quarantine' } it is kept as a
9// payload-less failed row so your failed panel can show it.
10//
11// A record sealed under a key that has since been replaced can never be
12// opened. It is removed quietly and is not reported as tampering.
4

Duplicate writes are handled for you

A user submitting the same form twice — a double tap on a slow connection, a retried request after a timeout — is a normal offline scenario, not an edge case. dedupeField and dedupeStrategy let you decide what happens when that occurs while an earlier write for the same identifier is still queued.
lib/flux.ts (excerpt)
1flux.register({
2 channel: 'waitlist_signups',
3 idbKey: 'waitlist_signups:latest',
4 ttl: 'long',
5
6 ingestionType: 'COLLECTION_ALL',
7 event: 'UPDATE',
8 scope: 'global',
9 store: waitlistStoreAdapter,
10
11 queueConfig: {
12 storeName: 'waitlist_queue',
13 replayEndpoint: '/api/waitlist',
14 method: 'POST',
15
16 dedupeField: 'email',
17 dedupeStrategy: 'replace',
18 },
19})
'reject' blocks the second write outright — the first one queued wins. 'replace' merges the new payload into the still queued entry, so the most recent input wins without producing two separate requests once the connection returns.
Dedupe also applies to a write that has already failed and is waiting for the user, and it is always scoped to the tenant of the new write:
typescript
1// Dedupe also applies to a write that has already FAILED and is
2// waiting in your failed panel for the user:
3//
4// dedupeStrategy: 'replace'
5// A new write for the same dedupeKey merges into the failed entry
6// and makes it pending again. The user's newer input supersedes
7// whatever the server rejected, so the old failure is cleared and
8// the entry is sent again on the next reconnect.
9//
10// dedupeStrategy: 'reject'
11// A new write for the same dedupeKey is still rejected while the
12// failed entry is waiting. The user must retry or discard the
13// failed one first.
14//
15// Dedupe is scoped to the tenant of the NEW entry. A user's write is only
16// compared with that same user's entries, and a global write only with
17// global entries.
18//
19// A constant dedupeKey (for example one fixed key per queue) means
20// "only one entry may be waiting at a time" for that user. That includes
21// a failed one, so a leftover failed entry blocks every new write with
22// the same key until it is retried or discarded.
5

Storage is resilient across three tiers

Queued writes do not rely on a single storage mechanism succeeding. If the primary layer is not available — some private browsing modes restrict it — Flux automatically falls back to the next most durable option it has, rather than losing the write outright. You can observe this happening if you want to reflect it in your UI:
lib/flux.ts (excerpt)
1const flux = createFlux({
2 adapter: createSupabaseAdapter(supabase),
3
4 onStorageFallback: (layer, reason) => {
5 console.warn('[flux] Offline writes now backed by', layer, '—', reason)
6 },
7})
In practice this callback rarely fires — it exists for the narrow set of restrictive browser environments where the primary storage layer genuinely is not usable, not as something every app needs to handle.
typescript
1// The three storage layers, most to least durable:
2//
3// 1. IndexedDB sealed (user) or checksummed (global). Survives refresh.
4// 2. localStorage same sealed/checksummed record. Survives refresh.
5// 3. memory plain, NOT sealed. Lost on refresh.
6//
7// Memory is the last resort when both disk layers are unavailable. A
8// memory entry is not encrypted and does not survive a reload, which is
9// why onStorageFallback('memory', ...) is worth surfacing to the user.
10// Before logout, Flux tries to promote a user's memory entries to disk
11// (sealed) and reports how many it could not save.
6

Multiple open tabs never duplicate a write

If a user has your app open in two tabs and queues a write in one of them, the other tab is made aware of that queued entry without independently writing its own copy to storage. IndexedDB and localStorage are shared by every tab, so the sealed record written by the first tab is the only copy on disk. This means the queue contents — and its count, if you are displaying one — stay consistent across every open tab, and reconnecting in any one tab does not risk sending the same write twice because two tabs both thought they owned it.
Failed writes are shared the same way. A change that fails in one tab appears in the failed list of every open tab, and discarding or retrying it in one tab updates the others.
If you display a queue count, recount from storage when other tabs report a change instead of adding and subtracting one, because a removal message does not say which queue it came from:
typescript
1// Showing "N changes waiting" for one queue, correct across tabs.
2//
3// Queue events from other tabs only say "something changed".
4// QUEUE_ENTRY_REMOVED does not name a store, so a counter that does -1
5// on every removal drifts whenever a DIFFERENT queue empties. Recount
6// from storage, scoped the same way the entries were written:
7import { getQueueCount } from '@tsworldtech/flux'
8
9async function refreshCount(userId: string | null) {
10 // user queue -> pass the user id
11 // global queue -> pass null
12 const count = await getQueueCount('MyApp', 'notes_mutation_queue', userId)
13 useNotesStore.setState({ queueCount: count })
14}
15
16const channel = new BroadcastChannel('MyApp:flux:queue:sync')
17let timer: ReturnType<typeof setTimeout> | null = null
18
19channel.addEventListener('message', (event) => {
20 const type = event.data?.type
21
22 // Added messages name their store. Removals and clears do not.
23 if (type === 'QUEUE_ENTRY_ADDED' && event.data?.storeName !== 'notes_mutation_queue') return
24
25 if (type === 'QUEUE_ENTRY_ADDED' || type === 'QUEUE_ENTRY_REMOVED' || type === 'QUEUE_USER_SCOPE_CLEARED') {
26 if (timer) return
27 timer = setTimeout(async () => {
28 timer = null
29 await refreshCount(await getActingUserId())
30 }, 50)
31 }
32})
33
34// Do NOT post { type: 'QUEUE_CLEARED' } yourself. Every tab that hears it
35// clears the entire IndexedDB queue and every localStorage key under your
36// storage prefix — all queues, user and global.
7

Queuing deletions

A DELETE is a queue entry like any other — the same three layer storage, the same dedupe machinery, the same encryption for user queues, the same cross tab sync, and the same failed state if the server rejects it. The only thing that changes is the method field on the entry. Queue it with the same scope and user as the user's other writes to that record:
typescript
1// A DELETE is a queue entry exactly like a CREATE or an UPDATE — the
2// only difference is the method field. addQueueEntrySafe() accepts
3// 'POST' | 'PUT' | 'PATCH' | 'DELETE' interchangeably, and the replay
4// engine batches and sends them the same way regardless of method.
5import { addQueueEntrySafe } from '@tsworldtech/flux'
6import { getActingUserId } from '@/lib/stores/authStore'
7
8async function queueItemDelete(id: string): Promise<void> {
9 const userId = await getActingUserId()
10 if (!userId) throw new Error('Sign in to delete offline.')
11
12 await addQueueEntrySafe(
13 {
14 channel: 'items',
15 storeName: 'items_mutation_queue',
16 endpoint: '/api/items',
17 method: 'DELETE',
18 payload: { id },
19 timestamp: Date.now(),
20
21 // Deduping a delete against itself: if the user taps delete
22 // twice while offline, 'replace' keeps a single queued DELETE
23 // entry instead of two identical ones.
24 dedupeKey: `item:${id}`,
25 dedupeStrategy: 'replace',
26 } as any,
27 'MyApp',
28 undefined,
29 undefined,
30 undefined,
31 'user', // same scope and tenant as the user's other item writes
32 userId
33 )
34}
The one case that needs its own handling is a record that was also created offline and never replayed. In that situation there is nothing server side to delete yet — the correct move is to purge the still queued create rather than queue a delete for a record the server has never seen. Read the queue with the user's id, because user entries are only returned for their own user:
typescript
1// A subtler case: the record was ALSO created offline and never
2// replayed. Now there are two queued entries for the same id — a
3// pending CREATE and a pending DELETE. Left alone, replay could send
4// the CREATE, then the DELETE, and the record would still end up
5// deleted — but it is an unnecessary extra round trip against a
6// record the server would only exist for a moment.
7//
8// The correct move is to purge the pending CREATE locally and skip
9// queuing the DELETE entirely — there is nothing on the server to
10// delete yet. This also covers a CREATE that already failed and is
11// sitting in the failed panel: removing it clears it from the panel.
12import { getAllQueueEntries, removeQueueEntry } from '@tsworldtech/flux'
13import { getActingUserId } from '@/lib/stores/authStore'
14
15async function deleteItem(id: string): Promise<{ queued: boolean }> {
16 const isTempId = id.startsWith('temp_item_')
17
18 if (isTempId) {
19 const userId = await getActingUserId()
20 if (userId) {
21 // Pass the userId: user entries are only returned for their own user.
22 const entries = await getAllQueueEntries('MyApp', 'items_mutation_queue', userId)
23 for (const entry of entries) {
24 const isCreate = (entry.method ?? 'POST') !== 'DELETE'
25 if (isCreate && String(entry.payload?.id ?? '') === id) {
26 await removeQueueEntry(entry.id, 'MyApp', 'items_mutation_queue')
27 }
28 }
29 }
30 return { queued: false } // nothing to send — it never reached the server
31 }
32
33 await queueItemDelete(id)
34 return { queued: true }
35}
On the replay side, onReplaySuccess receives the entry method, so you can dispatch the right confirmation shape once a queued delete actually lands:
typescript
1// On the register() side, onReplaySuccess receives the entry that
2// just replayed — including its method — so you can branch on
3// whether this was a queued create/update or a queued delete finally
4// landing, and dispatch the right kind of confirmation frame.
5flux.register({
6 channel: 'items',
7 idbKey: 'items:all',
8 ttl: 'long',
9 ingestionType: 'COLLECTION_ALL',
10 scope: 'user',
11 store: itemsStoreAdapter,
12
13 queueConfig: {
14 storeName: 'items_mutation_queue',
15 replayEndpoint: '/api/items',
16 method: 'POST',
17 dedupeField: 'id',
18 dedupeStrategy: 'replace',
19
20 onReplaySuccess: async (responseBody, entry) => {
21 const method = (entry?.method ?? 'POST').toUpperCase()
22
23 if (method === 'DELETE') {
24 await flux.dispatchLocalUpdate('items', { op: 'DELETE', id: entry.payload?.id })
25 return
26 }
27
28 const confirmed = responseBody?.item
29 if (confirmed) await flux.dispatchLocalUpdate('items', confirmed)
30 },
31 },
32})
Dedupe a delete against itself, not against creates

Give the delete its own dedupeKey (the record id is usually enough) so a repeated tap collapses into one queued DELETE rather than two. This is independent from — and does not replace — the pending create purge above, which is about a different record lifecycle stage entirely.

8

When the server says no: failed writes

A write is failed when the server answered with an error. Flux never deletes it in response. The entry stays on the device with a record of what happened, and waits for the user to retry it or discard it. Being offline, a timed out request, or a dropped connection is not a failure — there is no answer from the server, so the write stays pending and is sent again on the next reconnect without bothering the user.
typescript
1// A queued write is always in one of two states:
2//
3// pending — never sent yet, OR a send was interrupted because there
4// was no response (device offline, request timed out,
5// connection dropped). Nothing is shown to the user.
6// It is sent again automatically on the next reconnect.
7//
8// failed — the server ANSWERED with an error (any 4xx, any 5xx,
9// 429, and 409). The write stays on the device, nothing is
10// deleted, and it waits for the user to retry or discard it.
11//
12// A write leaves the queue in exactly three ways:
13// 1. the server accepts it (2xx)
14// 2. the server says it already has it (see idempotency in api/replay)
15// 3. the user discards it
16//
17// Being offline is never a failure. A failure always has a status code.
18//
19// One more case: a write that is still SEALED because its user's key is
20// locked is neither pending-and-sent nor failed. It waits, untouched,
21// until that user unlocks.
Two callbacks on queueConfig let your app respond. onFailed tells you an entry just became failed. onRollback tells you the user gave up on one, which is your cue to revert the optimistic change in the UI:
typescript
1flux.register({
2 channel: 'notes',
3 idbKey: 'notes:mine',
4 ttl: 'medium',
5 ingestionType: 'COLLECTION_ALL',
6 scope: 'user',
7 store: notesStoreAdapter,
8
9 queueConfig: {
10 storeName: 'notes_mutation_queue',
11 replayEndpoint: '/api/notes',
12 method: 'POST',
13
14 // Fires every time an entry becomes failed, including when a
15 // manual retry fails again. The entry is already saved with its
16 // failure record by the time this runs.
17 onFailed: (entry, failure) => {
18 // failure.status -> HTTP status the server answered with
19 // failure.message -> short message from the response body, if any
20 // failure.kind -> 'rejected' | 'server' | 'auth' | 'rate_limited' | 'revalidation'
21 // failure.attempts -> how many times this entry has failed
22 // failure.retryAfterSec -> set when the server sent Retry-After on a 429
23 showToast('A change could not be saved. Review it in your unsent changes.')
24 },
25
26 // Fires ONLY when the user discards a failed entry. Revert the
27 // optimistic change here. It does not fire when a send fails,
28 // because failed entries are kept.
29 onRollback: (storeName, error) => {
30 revertOptimisticNote()
31 },
32 },
33})
onRollback no longer fires when a send fails

Earlier versions deleted a write on a 4xx response and called onRollback immediately. Failed writes are now kept, so onRollback fires only when the user discards one through discardFailed(). If you reverted optimistic UI inside onRollback before, that still works, it just happens at discard time instead of at failure time. The older onFailure callback still fires alongside onFailed, but onFailed is the one to use.

9

Building a failed changes panel

Flux provides the data and the actions; your app provides the panel. subscribeToFailedWrites() hands you the full list of failed entries on subscribe and again on every change, including changes made in other tabs and after a page reload. Each entry carries its failure record, so you can show what the server said. For a user queue, the list shows the signed in user's failed entries only.
components/FailedWritesPanel.tsx
1import { useEffect, useState } from 'react'
2import { flux } from '@/lib/flux'
3import type { QueueEntry } from '@tsworldtech/flux'
4
5export function FailedWritesPanel({ channel }: { channel: string }) {
6 const [failed, setFailed] = useState<QueueEntry[]>([])
7 const [busyId, setBusyId] = useState<string | null>(null)
8 const [notice, setNotice] = useState<string | null>(null)
9
10 // Called once on subscribe with the current list, then again on every
11 // change — including changes made in other tabs and after a reload.
12 useEffect(() => {
13 return flux.subscribeToFailedWrites(setFailed, { channel })
14 }, [channel])
15
16 if (failed.length === 0) return null
17
18 async function retry(entryId?: string) {
19 setBusyId(entryId ?? '*')
20 setNotice(null)
21 try {
22 const outcome = await flux.retryFailed(channel, entryId ? [entryId] : undefined)
23 if (outcome?.status === 'offline') {
24 setNotice("You're offline. Try again once you're connected.")
25 }
26 // Anything that fails again stays in the list automatically.
27 } finally {
28 setBusyId(null)
29 }
30 }
31
32 async function discard(entryId: string) {
33 // Removes the entry and fires onRollback so you can revert the
34 // optimistic change. refetch: true also reloads the channel's cached
35 // copy from the server (use it while online).
36 await flux.discardFailed(channel, entryId, { refetch: true })
37 }
38
39 return (
40 <section role="alert">
41 <h3>{failed.length} change{failed.length === 1 ? '' : 's'} could not be saved</h3>
42 {notice && <p>{notice}</p>}
43
44 <ul>
45 {failed.map((entry) => (
46 <li key={entry.id}>
47 <p>
48 The server answered {entry.failure?.status}
49 {entry.failure?.message ? ': ' + entry.failure.message : ''}
50 </p>
51 {entry.failure?.retryAfterSec ? (
52 <p>The server asked you to wait {entry.failure.retryAfterSec}s before retrying.</p>
53 ) : null}
54
55 <button disabled={busyId !== null} onClick={() => retry(entry.id)}>Try again</button>
56 <button disabled={busyId !== null} onClick={() => discard(entry.id)}>Discard</button>
57 </li>
58 ))}
59 </ul>
60
61 <button disabled={busyId !== null} onClick={() => retry()}>Try all again</button>
62 </section>
63 )
64}
typescript
1// One-shot reads, for when you don't want a live subscription:
2
3const failed = await flux.getFailedWrites('notes') // one channel
4const allFailed = await flux.getFailedWrites() // every channel
5
6// The failed list's length is your count. For a badge across the
7// whole app, use the summary:
8const { pending, failed: failedCount } = await flux.getQueueSummary()
discardFailed() with refetch: true also reloads that channel from the server, because the locally cached copy still contains an edit the server never accepted. Use it while online, since it clears the cached copy before the fresh one arrives.
10

How failed writes get retried

Retries are deliberately limited. There are no timers and no endless retry loops. A failed write is retried automatically only when the device reconnects, and only when the failure is the kind that could succeed later.
typescript
1// Failed entries are retried in exactly two ways.
2//
3// 1. Automatically, on a reconnect only — and only when the failure
4// could plausibly succeed later:
5// 5xx server errors, 401/403 auth, 429 rate limits (after the
6// server's Retry-After window), 408 timeouts, and handshake
7// revalidation errors.
8// A definitive rejection (400, 409, 422, ...) would fail the same way
9// again, so it waits for the user instead of hitting your server on
10// every network flap.
11//
12// 2. Manually, when the user presses your Retry button:
13// await flux.retryFailed('notes', [entry.id]) // one entry
14// await flux.retryFailed('notes') // every failed entry on the channel
15// A manual retry sends exactly what the user chose, whatever the
16// failure was.
17//
18// There is no timer, no backoff loop, and no retry on window focus.
19// A failed entry that is not retryable stays put until the user acts.
20//
21// After a page reload, failed entries are not retried automatically.
22// They reappear in your panel and wait for a reconnect or for the user.
For the full list of what triggers an automatic replay, and exactly which entries each trigger sends, see api/replay.
11

Logout and confirm before leaving

What logout does to the queue depends on whether encryption is configured. With encryption on, a signed out user's writes stay sealed on disk and replay at their next sign in; a "clear this device" sign out wipes them and destroys the key. Without encryption, signing a user out deletes their queued writes, failed ones included. Either way, check the summary first so a logout never silently loses work the user thinks is saved:
typescript
1// With encryption configured, flux.clearUserSession() clears the
2// signed-in user's cache but KEEPS their queued writes, sealed on disk.
3// They replay at that user's next sign in. Tell the user what is waiting:
4async function handleLogout() {
5 const { pending, failed } = await flux.getQueueSummary()
6
7 if (pending + failed > 0) {
8 const ok = window.confirm(
9 'You have ' + (pending + failed) + ' change(s) that have not been saved to the server. ' +
10 'They stay on this device and sync the next time you sign in.'
11 )
12 if (!ok) return
13 }
14
15 await flux.clearUserSession()
16 router.push('/login')
17}
18
19// On a shared or public computer, offer the opposite choice. This wipes
20// the cache AND the queued writes, and destroys the user's key:
21async function handleLogoutAndClearDevice() {
22 await flux.clearUserSession({ discardQueue: true })
23 router.push('/login')
24}
25
26// WITHOUT encryption configured, clearUserSession() deletes the signed-in
27// user's queued writes, pending and failed. Confirm first, so a logout
28// never silently throws away a change the user thinks is saved.
29//
30// getQueueSummary() counts the signed-in user's writes plus writes that
31// belong to no user (global queues, like a public contact form).
32// Global writes are never removed by logout.
Sign out choiceEncryption onEncryption off
clearUserSession()Cache cleared. Unsent writes stay sealed and replay at the next sign in.Cache cleared. The user's queued writes are deleted.
clearUserSession({ discardQueue: true })Cache and queue wiped, and the user's key destroyed.Same as above.
Global queue entriesNever removed by logout.Never removed by logout.
What should never go through this queue

The offline write queue is built for writes where "send it a little later" is an acceptable outcome — a saved draft, a preference change, a beneficiary added to an account. It is deliberately not built, and should never be used, for financial ledger writes: payments, wire transfers, direct debits, or any operation where a duplicate send or a delayed send against changed conditions has real financial consequences.

There is no configuration on the queue that makes this safe, and encryption does not change it: encrypting a queued payment protects it on disk, not from replaying against a balance, a rate, or an authorization that is no longer valid the moment it was queued under. A failed payment kept for a Retry button has the same problem. The correct pattern is to keep payment endpoints entirely outside the queue system and instead block the action at the UI level while the app is offline — failing fast and visibly, rather than deferring silently.

Register the channel with no queueConfig at all:
lib/flux.ts (excerpt)
1flux.register({
2 channel: 'billing_account',
3 idbKey: 'billing_account:mine',
4 ttl: 'short',
5 ingestionType: 'SNAPSHOT',
6 diffBeforeUpdate: true,
7 event: 'UPDATE',
8 store: billingStoreAdapter,
9 // No queueConfig — a failed or offline payment attempt is never
10 // silently retried later. It fails immediately and visibly.
11})
Then gate the write action itself on live connectivity, using isOnline from useFlux() — the same flag every other part of your app can read to know whether the device currently has a connection:
components/CheckoutButton.tsx
1import { useFlux } from '@tsworldtech/flux_react'
2
3export function CheckoutButton() {
4 const { isOnline } = useFlux()
5
6 if (!isOnline) {
7 return (
8 <div role="status">
9 <p>You're offline right now.</p>
10 <p>Payments cannot be made without a connection. Please reconnect to check out.</p>
11 <button disabled>Pay now</button>
12 </div>
13 )
14 }
15
16 return <button onClick={submitPayment}>Pay now</button>
17}
This pattern applies to any endpoint where the cost of a delayed or duplicated write outweighs the convenience of it happening automatically later — payment submission is the clearest example, but the same reasoning applies to any one shot, consequential action your app exposes, including an irreversible delete against a financial ledger adjacent record.

See api/replay for exactly when queued writes are sent, how global and user filters select entries, how batching and idempotency work, and the retry rules, guides/encryption_key_route for the key route that unlocks encrypted user queues, core_concepts/conflict_resolution for what happens when a queued write for a non financial record conflicts with a change made on the server while the user was offline, core_concepts/mutation_pipeline for shaping rapid fire writes — like autosave — before they ever reach the queue, and core_concepts/lib_flux_structure for a full reference lib/flux.ts file showing all of this wired together.

Powered by Flux