In a gradebook web app open in several tabs, how would you design the offline write queue's ordering and idempotent replay, and which tab replays it?
answer
- durable before the screen says saved
- order per target, not per app
- key minted once, reused on every resend
- one named lock, the rest skip
- the page replays; the worker is a bonus
basics
~20 sStore each write durably before showing it, ordered per target, carrying an idempotency key minted at creation; one context replays under a named Web Lock, triggered from the page whether or not Background Sync exists.
solid answer
~50 sEach attendance mark or grade becomes a queue entry in IndexedDB before the screen shows it as saved: a client-generated id that doubles as the **idempotency key**, the teacher, the target (lesson and pupil, or assessment and pupil), the payload, the revision it was based on and a sequence number. Order matters per target, a mark then its correction, so replay sends entries in sequence and parks a target's later entries behind any entry the server rejected, while other pupils carry on. Resends reuse the same key, so a request whose response was lost is not applied twice. Replay runs under one named **Web Lock** requested with `ifAvailable`: whichever tab or worker gets it drains the queue, and the others skip. Any tab triggers a drain on reconnect, on becoming visible and after each new entry; where Background Sync exists, its event is one more trigger taking the same lock.
code
javascript · 37 lines// Any tab, or the service worker, may call this; only one drains at a time.
function drainOutbox(teacherId) {
return navigator.locks.request('gradebook-outbox', { ifAvailable: true }, async (lock) => {
if (lock === null) return 'busy'; // another tab or the worker is replaying
const parkedTargets = new Set();
for (const entry of await readPendingInSeqOrder(teacherId)) {
if (parkedTargets.has(entry.target)) continue; // keep per-target order
const timeout = new AbortController();
const timer = setTimeout(() => timeout.abort(), 10000);
let res;
try {
res = await fetch(entry.url, {
method: entry.method,
signal: timeout.signal,
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': entry.id,
...(entry.baseRevision ? { 'If-Match': entry.baseRevision } : {}),
},
body: JSON.stringify(entry.payload),
});
} catch {
return 'unreachable'; // network failure or timeout: try again later
} finally {
clearTimeout(timer);
}
if (res.ok) await markSent(entry, await res.text());
else if (res.status === 401) return 'reauthenticate';
else if (res.status >= 500 || res.status === 429) return 'retry-later';
else {
await park(entry, res.status, await res.text()); // conflict or validation error
parkedTargets.add(entry.target);
}
}
return 'drained';
});
}go deeper
Recall that writes made offline are stored and sent later, and that sending one twice must not apply it twice.
Explain the entry's fields, why the key is minted at creation, and why order matters only between writes to the same record.
Show why idempotency does not fix reordering, how one named lock picks the replayer, and how parked entries block only their own target.
Decide the server contract the queue relies on, keys honoured and revisions checked, and who owns that contract across the client and API teams.
## What the queue is for An **offline write queue** (often called an outbox) holds every change the user made that the server has not yet confirmed. In a school gradebook those changes are attendance marks, corrections and grades with comments, made on patchy Wi-Fi, often with the gradebook open in two or three tabs. The queue has to survive a closed tab, send each change exactly once in effect, keep changes to the same record in order, and never be replayed by two tabs at the same time. ## The entry Each entry is written to **IndexedDB** (the browser's transactional object store) *before* the interface shows the change as saved. A change held only in memory is lost when the tab closes. | Field | Purpose | |---|---| | `id` | Client-generated unique id; also the **idempotency key** | | `teacherId` | Only the signed-in teacher's entries are ever replayed | | `target` | The record changed, e.g. lesson and pupil | | `seq` | Monotonic number giving creation order | | `baseRevision` | The version of the record the teacher saw | | `payload` | The change itself | | `status` | pending, sending, sent or needs-attention | ## Ordering: per target, not per app Order matters between entries that touch **the same record**: a pupil marked absent then corrected to late must reach the server in that order, or the correction is overwritten by the mark it corrected. Order across unrelated pupils usually does not matter; the exception is a record created offline, such as a new assessment, whose grades must wait for it. The design: 1. Read pending entries in `seq` order. 2. Send each; on success, mark it sent and update the cached record from the response. 3. On a network failure or a server error, stop and retry later with backoff and jitter. 4. On a rejection (a conflict, a validation error), **park** the entry and skip every later entry for the same target; carry on with other targets. Device clocks are not an ordering source: a shared laptop's clock can be wrong, and a sequence number is assigned locally without one. ## Idempotent replay A request can reach the server and its response be lost on the way back. Replaying it then creates a duplicate comment or a second grade. The cure is an **idempotency key**: the server remembers each key with its result and answers a repeat with the same result instead of applying it again. The key must be minted **when the entry is created** and reused on every resend; a fresh key per attempt defeats it. Records created offline, such as a new assessment, get client-generated ids too, so later entries that reference them can be queued before the server has seen them. ## One replaying tab Idempotency stops duplicates; it does **not** stop reordering. If two tabs replay together, one can send the correction while the other is still sending the original mark, and the mark lands last. So exactly one context replays at a time, using the **Web Locks API**: while one tab or worker holds a named lock, no other script of the same origin can acquire it. Requesting it with `ifAvailable` makes a busy lock return immediately, so the other tabs simply skip that drain. The lock is released when the callback's work finishes. Triggers, from any tab: - the window's `online` event, as a cue to try; - the tab becoming visible again; - a new entry being added; - a timer while the tab is visible; - where the browser supports **Background Sync**, its `sync` event in the service worker, which takes the same lock. Background Sync is not available in some of the most widely used browsers, so it can only ever be an extra trigger; the page-driven drain is the design. ## Durability limits Browser storage is **best-effort** by default: when the device runs short of space, the browser may delete an origin's data without asking, all of it at once. Unsent marks die with it. On a teacher's own phone the app can request persistent storage, which the browser may or may not grant; on any device the real defences are draining promptly and showing the unsent count, so nobody treats queued work as filed. ## What it costs - **A server contract**: idempotency keys stored and honoured, revisions checked on write. - **Parked entries need a home in the interface**, or they silently block a pupil's later changes. - **Testing**: lost responses, two tabs, closed tabs and eviction are all cases to exercise deliberately.
- Why isn't the idempotency key enough without the lock?The key stops the server applying one entry twice, but it says nothing about order. Two tabs replaying at once can send a pupil's correction from one tab while the other is still sending the original mark; if the mark lands last, the record ends wrong and both requests were legitimately new. One replaying context keeps per-target order intact.
- What happens to the queue if the browser evicts the origin's storage?Best-effort data is deleted without asking, and an origin's data goes all at once, so every unsent mark vanishes with the cached rosters. Request persistent storage on a teacher's own device, though the browser may refuse; drain promptly; and keep the unsent count visible so the teacher knows which work is not yet safe.
- Should a correction replace the earlier unsent mark instead of queueing behind it?Coalescing is valid when the server only needs the final state: it halves the requests and removes the ordering risk for that pair. But if the school keeps an audit trail of attendance changes, both entries carry meaning and must be sent in order. Decide it with the API contract, per kind of write, not as a queue-wide rule.
- Replay from every open tab; idempotency keys make that safe.
- Mint a fresh idempotency key for each retry attempt.
- Background Sync will replay the queue, so the page need not.
- Keep the queue in memory; it only has to last until Wi-Fi returns.
- Order replayed writes by the device clock's timestamps.