Skip to content

    Frontend System Design

    Offline Queues and Background Sync

    Build a safe offline write queue: persist it, drain it on triggers, retry by status, use idempotency keys, keep order, and see what Background Sync promises.

    By Published 13 min read

    • frontend-system-design
    • offline-first
    • outbox
    • background-sync
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Offline-First Sync and Conflict Resolution

    What you'll learn: By the end of this lesson you will be able to design an outbox for an offline-first app: persist the queue, decide when to drain it, classify each reply into retry, conflict or give-up, back off with jitter, make retries safe with idempotency keys, keep order where it matters, coalesce repeated edits, and say exactly what the Background Synchronization API does and does not promise.

    Think of a post box. You drop a letter in and walk away. The collector comes later, may come more than once, and if the same letter is collected twice because a receipt was lost, the recipient should be able to tell it is the same letter. An outbox is that box for the changes a user makes without a connection, and the engineering is everything between the drop and the delivery.

    The running example is a shopping list app whose user taps "add" and "change quantity" on a train. The lab's queue holds made-up operations such as add-line, set-qty and place-order.

    The core idea

    1. Write locally and queue first, send later. Every change is saved to the queue before any request is made, so a closed tab or a dead network loses nothing.
    2. A queue is a delivery protocol, not a list. It needs rules for when to try, how to read each answer, how long to wait, what must stay in order, and what to do when an answer never arrives.
    3. Background Sync is a hint to retry, not a guarantee. It is one of several triggers for draining the queue and, at the time of writing, is not available in every browser.

    Conflicts are covered in Offline-First Sync and Conflict Resolution; here a "conflict" answer is a reply to hold for that logic, not something a queue can fix.

    The queue and its entries

    An entry is a description of a change, not a callback. The lab's Entry holds what is needed to send it again after a reload:

    Field Purpose
    id, type, payload What to send
    orderKey Entries with the same key go in order, one at a time (for example a record id)
    coalesceKey A never-sent entry with the same key is replaced by a newer one
    idempotencyKey Sent with every attempt so the server can recognise a repeat
    attempts, nextAt, state, note Retry bookkeeping: queued, inflight, conflict or dead

    The queue is saved on every change. IndexedDB is the usual home for a real one (see IndexedDB and Storage Quotas); the lab uses a one-string in-memory store to keep the logic pure. On restore, an entry that was inflight goes back to queued: the page died before the answer, so its outcome is unknown, and the only safe move is to send it again with the same key.

    Figure 1. What feeds a drain

    Several triggers start a drain; the outbox sends one entry at a time and reads each replyScreen to Outbox (enqueue); Outbox to Drain (due entries); Drain to Server (request); Triggers to Drain (start)Screen: writes locallyScreenwrites locallyOutbox: saved queueOutboxsaved queueDrain: send, read replyDrainsend, read replyServer: applies onceServerapplies onceTriggers: load, online, timerTriggersload, online,timerenqueuedue entriesrequeststart

    How to read this: the screen only ever talks to the outbox. What starts a drain is a separate decision from how the drain behaves.

    When to drain

    The sensible triggers are: the app starts, the page becomes visible again, the browser says the network is back, a retry timer fires, and, where available, a background sync event arrives. Treat the connectivity signal as a prompt to try, not as proof. MDN calls navigator.onLine inherently unreliable and says the online event should not be used to decide whether a particular website is reachable, so a drain must expect to fail even when it is told "online".

    Reading a reply

    The lab's rule is a design choice, summarised in one function:

    Reply Decision Why
    2xx Delivered, remove Done
    No answer, 408, 429, 5xx Retry later The request may succeed later
    409, 412 Hold for conflict handling The server disagrees about the data; retrying will not help
    Other 4xx Park as dead The server will keep refusing; show the user

    RFC 6585 describes 429 Too Many Requests as rate limiting, and says the response may include a Retry-After header telling the client how long to wait. The lab lets that hint lengthen the wait, never shorten it. CouchDB shows the 409 reading in practice: a stale revision is rejected with 409 Conflict. The retry mathematics (exponential growth, a cap, jitter) are covered in Client Retries, Exponential Backoff and Jitter; here the lab uses "full jitter": a random wait up to min(cap, base * 2^(attempts-1)), at least one millisecond, and a limit of attempts after which the entry is parked, not retried forever.

    Figure 2. What happens to an entry

    stateDiagram-v2 accTitle: Life of an outbox entry accDescr: An entry starts queued. A drain moves it to in flight. A success removes it. A retryable failure returns it to queued with a later time. A conflict answer moves it to conflict, where it blocks later entries of the same key until the app resolves it. A refusal, or too many attempts, moves it to dead, which does not block later entries but is shown to the user. A page that dies while an entry is in flight restores it as queued. [*] --> Queued Queued --> InFlight: drain InFlight --> [*]: delivered InFlight --> Queued: retry later InFlight --> Conflict: 409 or 412 InFlight --> Dead: refused or too many tries InFlight --> Queued: page died, restored Conflict --> [*]: resolved Dead --> [*]: discarded

    How to read this: only the Queued state is ever sent. Conflict and Dead are not retried, and both stay visible until someone deals with them.

    Making a retry safe

    The hard case is the lost answer. The server applied the change, the connection dropped, and the client saw no reply. Retrying a plain create applies it twice.

    RFC 9110 defines a method as idempotent when the intended effect of multiple identical requests is the same as for one; PUT, DELETE and safe methods are idempotent, and POST is not in that list. A client may automatically resend an idempotent request after a dropped connection, but should not do so for a non-idempotent one unless it knows the request is safe to repeat. For the rest, the usual answer is an idempotency key: the client sends a unique key with each logical operation, the server remembers it, and a repeat gets the first result. An IETF Internet-Draft, not a standard, specifies an Idempotency-Key request header for this: a retry after completion should get a response consistent with the request having completed, a retry while the original is still running should get 409, and reusing a key with a different payload should get 422.

    That last rule is why the lab gives a coalesced entry a new key: one key must always mean one payload.

    Figure 3. A lost answer, with and without a key

    sequenceDiagram accTitle: Lost answer and a safe retry accDescr: The client sends place-order with key K. The server creates the order and replies, but the reply is lost. The client sees no answer, waits, and sends the same request with the same key K. A server that honours keys recognises K and returns the first result without creating a second order. A server that ignores keys creates a second order. participant C as Outbox participant S as Server C->>S: place-order (key K) S->>S: create order 1 S--xC: reply lost Note over C: no answer: retry later C->>S: place-order (key K, again) alt server honours keys S-->>C: first result, no new order else server ignores keys S->>S: create order 2 S-->>C: 200 end

    How to read this: the client cannot tell "never arrived" from "arrived, answer lost". The key is what lets the server tell them apart.

    Order and coalescing

    Changes to different records can go in any order, but two changes to one record must keep the user's order: you cannot add an item to a list that has not been created. The lab holds back every later entry of an orderKey while an earlier one is queued, in flight or in conflict, and lets other keys go on. A dead entry does not block, because waiting on something that will never succeed would freeze the key.

    Coalescing reduces the number of requests: five taps on "set quantity" while offline become one entry with the last value. It is only safe before the entry has been sent, since after a send the server may already have applied the old payload.

    Background Synchronization

    The Background Synchronization API, as MDN describes it, lets a web app defer tasks so that they run in a service worker once the user has a stable network connection. A page calls registration.sync.register(tag); MDN documents that register() resolves to undefined, throws InvalidStateError if the service worker is not active, and NotAllowedError if the user disabled background sync. The service worker then receives a sync event with that tag, and the handler passes its work to event.waitUntil().

    Three caveats matter for design. MDN marks the feature as limited availability, not Baseline, because it does not work in some of the most widely used browsers; it is also only available in secure contexts. The WICG specification leaves timing to the user agent: it should fire a sync event for pending registrations when the device goes online, a failed event may be retried "at a time of its choosing", and SyncEvent.lastChance is true when the user agent will make no further attempts after the current one. And a registration is per tag: registering again while one is pending does not create a second one.

    So Background Sync is a good way to get one more chance at a drain after the page is closed where it exists, and it must never be the only way: the app keeps its own triggers and its own saved queue.

    Trade-offs

    Choice Gain Cost
    Persist every enqueue Survives reload and crash A write per change; storage may be evicted
    Retry with jitter and a cap Avoids a thundering herd; gives up eventually A change can sit unsent for a long time
    Idempotency keys Safe retries for non-idempotent calls Server must store keys; the contract is still a draft
    Per-key ordering Correct dependent changes One failing entry holds up its key
    Coalescing Fewer requests Loses intermediate values; unsafe after a send
    Background Sync A retry with the page closed Limited availability; the browser sets the timing

    Build it: an outbox you can drive

    Goal. Run a model of an outbox through eight situations: a reload, reply classification, backoff, a Retry-After hint, a lost answer with and without keys, coalescing, ordering, and a model of the Background Sync rules.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no browser, no service worker, no real network or storage.

    cd examples/frontend/labs/offline-outbox
    pnpm test           # 21 tests
    node src/demo.ts

    Steps.

    1. Run the tests and the demo. Sections 1 and 2 show a queue restored after a "reload" and how each status is read.
    2. In the output below, check section 3: five 503 replies give a growing, jittered wait, and the fifth failure parks the entry as dead.
    3. In section 5, compare the two servers: the same lost answer creates one order with keys and two without.
    4. In section 8, follow the Background Sync model: the registration is made twice but exists once, and the third failed attempt carries lastChance.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01; sections 3 to 8 of the demo):

    === 3. Backoff with full jitter (base 1000 ms, cap 30000 ms, 5 attempts, random = 0.9 0.5 0.7 0.3 0.8)
    attempt 1 at t=0: queued, next at 900 (retry after 503)
    attempt 2 at t=900: queued, next at 1900 (retry after 503)
    attempt 3 at t=1900: queued, next at 4700 (retry after 503)
    attempt 4 at t=4700: queued, next at 7100 (retry after 503)
    attempt 5 at t=7100: dead, next at 7100 (gave up after 5 attempts (last: 503))
    requests the server saw: 5; dead entries kept for the user: 1
    
    === 4. A Retry-After hint longer than the backoff wins (429 with 30000 ms, backoff would be at most 1000 ms)
    after the 429 at t=0: next attempt not before t=30000
    drain at t=0 sends 0 request(s), 1 entry waiting until t=30000
    
    === 5. The answer is lost after the server applied the change; the client retries
    server honours idempotency keys: requests=2, orders created=1, queue=(empty)
    server ignores  idempotency keys: requests=2, orders created=2, queue=(empty)
    
    === 6. Coalescing: five edits of one quantity while offline
    not coalesced: requests=5, last quantity applied=5
    coalesced:      requests=1, last quantity applied=5
    
    === 7. Order: one key waits behind its failed head, other keys go on
    first drain: sent=2 delivered=1 retrying=1; server saw create-list:list-1, create-list:list-2
    queue: create-list:list-1[queued, 1 tries] add-item:list-1[queued]
    second drain at t=500: sent=2 delivered=2; server saw create-list:list-1, create-list:list-2, create-list:list-1, add-item:list-1
    
    === 8. Background sync model (3 attempts, retry delays 5000 then 20000 ms; the numbers are this lab's, not a browser's)
    registered twice, registrations: 1 (pending)
    t=0     offline -> nothing fires
    t=1000  online  -> outbox: failed on attempt 1, waiting until t=6000
    t=3000  online  -> nothing fires
    t=6000  online  -> outbox: failed on attempt 2, waiting until t=26000
    t=30000 online  -> outbox: failed on attempt 3 (lastChance), registration removed
    t=40000 online  -> nothing fires
    events handled: outbox lastChance=false | outbox lastChance=false | outbox lastChance=true
    state afterwards: none; the queue itself is still in the outbox for the next page load

    What the lab does not show. It is a model, not a browser: no service worker, no real sync event, no real network, no real clock. The retry rule, the delays and the number of attempts in section 8 are this lab's choices, not any browser's or standard's; real browsers decide when a device is online and when to retry. The idempotency behaviour follows the draft's ideas but is not an implementation of it. Parallel sends and server-side key storage limits are not modelled.

    Break it. In src/outbox.ts, delete && e.attempts === 0 from the findIndex in enqueue. The test "does not replace an entry that has been tried or is in flight" fails, because a sent payload can now be swapped under its old key. Restore it.

    In practice: an order button that charged twice

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A grocery app lets users tap "Place order" on a weak connection. The app retries on any failure with a fixed 2 second delay and no key. Support sees a few customers with two identical orders minutes apart.

    Starting architecture

    Figure 4. Starting point: blind retries of a non-idempotent call

    Starting architecture: the app retries a create request after every failure with no keyApp to Orders API (POST /orders); Orders API to Orders table (insert); Orders API to App (reply lost)App: retries every 2 sAppretries every 2 sOrders API: POST, no keyOrders APIPOST, no keyOrders table: one row per callOrders tableone row per callPOST /ordersinsertreply lost

    How to read this: when the reply is lost the app cannot tell whether the order exists, so it sends it again and the server creates another.

    Options considered

    Option What it fixes What it costs Risk
    Idempotency key per order, stored by the server A retry returns the first result Server storage and a rule for key reuse Keys must be generated once per logical order, not per attempt
    Check "does my order exist" before retrying No server change A read per retry and a race window Needs a stable client-side identifier

    The decision

    Field Decision record
    Context A retried create can run twice because a lost answer looks the same as a lost request.
    Decision Generate one key when the user taps, save it in the outbox entry, send it with every attempt, and have the server return the first result for a repeated key. Use jittered backoff with an attempt limit.
    Consequences, good Retries become safe; duplicate orders stop.
    Consequences, bad The server stores keys for some period, and a changed payload under a used key needs an error answer.
    Revisit when A standard Idempotency-Key contract is published and the gateway can enforce it.

    Rollout and verification

    1. Add the key to the entry and the request, with the server ignoring it, and log repeats that would have been caught.
    2. Turn on key handling on the server for the order endpoint only and watch the duplicate count.
    3. Test the lost answer in the app's tests: apply on the server, drop the reply, and assert one order exists after the retry.

    The 2 a.m. failure

    Duplicates fall but do not vanish. Support finds orders created twice by users who edited the basket after a failed tap: the app made a new key for the changed order, because the payload changed, and the first (successful, answer lost) order still exists (illustrative). A retry of an order that was already created is a different logical operation from a new order.

    First three checks: (1) pair the two orders by user and time; (2) check which key each carried; (3) check whether the app lets users edit an order that is still in the outbox. Mitigation: block edits to an entry that has been sent, or turn the edit into a separate change that waits behind it. Follow-up: add a test for "edit after a lost answer", and show the user "order pending" so they do not place it again.

    Architect's notes

    • Save before you send. The queue is the source of truth for unsent work.
    • One logical operation, one key. A key per attempt defeats the purpose.
    • Never retry forever. Park the entry and show it to the user.
    • Keep Background Sync optional. It is a bonus trigger, not the plan.

    Common mistakes

    • Retrying every status, including 400s that will never succeed.
    • A new idempotency key on each attempt.
    • Treating the online event as proof that the server is reachable.
    • Coalescing after a send.
    • Relying on Background Sync in browsers that do not support it.

    Key takeaways

    • An outbox saves each change before sending and replays it after a reload.
    • Read the reply: retry on no answer, 408, 429 and 5xx; hold 409 and 412; park other 4xx.
    • Back off with jitter, honour Retry-After, and cap the attempts.
    • A lost answer is the hard case: use an idempotency key, or only retry idempotent methods.
    • Order within a key, coalesce only unsent entries.
    • Background Sync adds a retry when the page is closed; it has limited availability and the browser sets the timing.

    Practice exercises

    Exercise 1 — Starter (45 min): Run the demo and write, for the replies 200, 408, 409, 400 and "no answer", what the outbox does next and whether the entry stays visible.

    Exercise 2 — Intermediate (2 hours): Add a rule that an entry older than 24 hours (an injected clock) is parked as dead. Write tests for an entry that is one minute under and one minute over.

    Exercise 3 — Advanced (half day): Let drain send up to three different order keys at once while still keeping order within a key. Write the test that fails if two entries of one key are ever in flight together.

    In this course:

    The course's service worker lessons cover registering and updating the worker that receives a sync event.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments