Lesson 5 · Mobile and offline architecture

Offline-first architecture

Local-first data, caching strategies and what to do when the network lies.

About 30 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

"Works offline" usually gets built as a cache bolted onto an online app: requests fail, a fallback kicks in, and the UI has two modes and twice the bugs. Offline-first inverts it. The device's local store is the source of truth for the UI, every read is local, every write lands locally first, and the network is a background channel that syncs when it can. This lesson covers the architecture, the browser machinery (service workers, Cache Storage, IndexedDB), what background execution you can and can't count on per platform, and the outbox pattern that makes writes survive bad networks.

Three levels of "offline"

LevelReadsWritesTypical tools
Offline-tolerantCached app shell and maybe the last responsesFail, or are blocked with "you're offline"Service worker with a cache strategy
Offline-capableLocal copy of the user's dataQueued and retriedIndexedDB or SQLite, an outbox
Local-firstAlways local, network never on the read pathAlways local, synced in the background, merged across devicesLocal database + sync engine + conflict resolution

The cost of moving down the table is mostly in sync: once two devices can write while disconnected, you need a merge strategy (the next lesson). The payoff is that latency and connectivity stop being UI states. A tap shows its result in the next frame whether the server is 20 ms or 20 minutes away.

The network lies

navigator.onLine === true only means the device has a network interface that's up. A captive portal, a congested cell tower, a dead upstream or a VPN with no route all report "online". false is somewhat more trustworthy, but it isn't a guarantee either. Design for the failure modes you'll actually meet:

  • Lie-fi: connected, but requests stall for tens of seconds. Every network call needs a timeout (AbortSignal.timeout(ms) with fetch), or a stalled request will hold your UI hostage.
  • Lost responses: the server processed the request but the response never arrived. The client can't tell this apart from "never sent". Retrying must be safe, which means writes must be idempotent.
  • Partial sync: a batch got halfway. Work in units that commit atomically on the server.

Treat online/offline events as hints that it's a good moment to try, never as the decision of whether to try.

Question

Quick check

navigator.onLine is true and a fetch to your API has been pending for 25 seconds. What does that tell you?
Pick an answer.

Service worker lifecycle

A service worker is a script the browser runs separately from your pages, which can intercept their network requests. It needs a secure context (HTTPS, or localhost in development). Its lifecycle determines when new code takes effect:

Step by step

How a service worker version takes over

Register

The page calls navigator.serviceWorker.register('/sw.js'). The scope defaults to the script's directory: /sw.js controls the whole origin, /app/sw.js only /app/.

1 / 6
// sw.js
const VERSION = '2026-11-25'
const SHELL = ['/', '/app.js', '/app.css', '/offline.html']

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(`shell-${VERSION}`).then((cache) => cache.addAll(SHELL)))
})

self.addEventListener('activate', (event) => {
  event.waitUntil(
    (async () => {
      const keys = await caches.keys()
      await Promise.all(keys.filter((k) => k !== `shell-${VERSION}`).map((k) => caches.delete(k)))
      await self.clients.claim()
    })()
  )
})

self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url)
  if (url.origin === location.origin && SHELL.includes(url.pathname)) {
    event.respondWith(caches.match(event.request).then((hit) => hit ?? fetch(event.request)))
  }
})

Caching strategies

Pick a strategy per kind of resource, based on how stale it may be and how much the user needs it offline:

  • Cache-first for versioned, immutable assets (app.3f9a2c.js, fonts, icons). The URL changes when the content does, so a cache hit is always right.
  • Network-first with a timeout for HTML and data where freshness matters but a stale copy beats an error. Without a short timeout, lie-fi makes this strategy slower than having no service worker.
  • Stale-while-revalidate for content that can be a little old (avatars, a feed): answer from cache immediately, update the cache in the background for next time.
  • Network-only for things that must never be stale or must not be cached: payments, auth endpoints.

Lab

Caching strategy simulator

A service worker decides where each response comes from. Pick a strategy and a network, then send requests.

Strategy

Answers from the cache when it can; only uses the network on a miss. Fast and offline-proof, but can serve old copies forever unless the cache is versioned.

Network
Server has
v1
Cache holds
nothing
Requests

Send a request to see where the response comes from.

Timings are illustrative, not measured.

In a local-first app, notice how small this layer becomes. The service worker caches the app. The user's data doesn't go through HTTP caching at all: it lives in a database the UI reads directly.

Storing data: IndexedDB and quotas

Cache Storage holds Request/Response pairs. For structured data use IndexedDB (in native apps, SQLite). Both share the origin's storage quota, which is generous but finite and differs by browser: read navigator.storage.estimate() rather than assuming.

Storage is best-effort by default: under storage pressure the browser may evict an origin's data entirely. navigator.storage.persist() requests persistent storage; browsers decide by their own rules (Chromium grants it based on engagement, such as an installed app; Firefox asks the user). Safari also deletes all script-writable storage for a site after seven days of browser use without the user interacting with it; Home Screen web apps are counted separately, by their own use. A local-first web app must therefore treat the server as the durable backup and be able to rebuild from it.

IndexedDB's sharpest edge is transaction lifetime. A transaction stays active only while it has pending requests; when your code returns to the event loop with none queued, it commits automatically.

const tx = db.transaction('notes', 'readwrite')
const store = tx.objectStore('notes')
const note = await promisify(store.get(id)) // fine: an IDB request keeps it alive
const tags = await fetch('/api/tags').then((r) => r.json()) // the transaction commits here
store.put({ ...note, tags }) // throws TransactionInactiveError

Do the network (or any other non-IndexedDB async work) before opening the transaction, then do all the reads and writes inside it. A thin wrapper like idb makes the promise plumbing bearable without hiding this rule.

Background execution: what you can count on

You can't assume code runs when the app isn't in front of the user. The realities:

PlatformWhat existsWhat it means for sync
Web, Chromium (Android, desktop)Background Sync: registration.sync.register('outbox') fires a sync event in the service worker when connectivity returns, even after the tab closes. Periodic Background Sync exists for installed apps, at intervals the browser chooses.Useful bonus for retrying an outbox
Web, Safari/iOS and FirefoxNo Background Sync. No web code runs once the page is gone.Flush on launch, on online, and when the page becomes visible
iOS nativeBGTaskScheduler (BGAppRefreshTask for short refreshes, BGProcessingTask for longer work): the system decides when, based on usage, battery and network, and may never run it. Background URLSession transfers continue in a system process while your app is suspended.Hand uploads to a background URLSession; treat scheduled tasks as opportunistic
Android nativeWorkManager with constraints (NetworkType.CONNECTED): persisted, survives reboots, eventually runs, deferred by Doze and App Standby bucketsThe reliable way to drain an outbox in the background

The design consequence is the same everywhere: the outbox must be correct if it's only ever flushed while the app is open, and background mechanisms just make it faster.

Writes: optimistic UI and the outbox

Optimistic UI means applying the user's change to local state immediately, showing it as done (optionally marked pending), and syncing afterwards. The outbox is how you make "afterwards" reliable:

  1. In one local transaction, apply the change to the local database and append a mutation record to the outbox table. Either both happen or neither does.
  2. Give each mutation a client-generated unique id. The server stores ids it has applied and ignores repeats, so retries are idempotent: delivery is at-least-once, effect is exactly-once.
  3. A sender drains the outbox in order. Network errors, timeouts, 5xx, 408 and 429 are retryable: keep the mutation, stop, and retry later with exponential backoff and jitter. Other 4xx are permanent: the server will never accept it. Move it to a failed list, roll back or flag the local change, and tell the user.
  4. Only one sender runs at a time, or two flushes will send the same mutation concurrently.
  5. Remove a mutation only after the server acknowledges it.

Strict FIFO across the whole outbox means one stuck mutation blocks everything behind it (head-of-line blocking). Many apps keep order per entity instead: changes to note A stay ordered, but needn't wait for note B.

Challenge

Build an outbox

Implement createOutbox(send). send(mutation) returns a promise: it rejects on a network failure, or resolves to { ok, status }. The returned object needs:

  • enqueue(mutation): add { id, ... } to the end of the queue.
  • flush(): send queued mutations one at a time, in order. Remove a mutation when the response is ok. On a network error or a retryable status (5xx, 408, 429), keep it and stop. On any other status, move it to the failed list and carry on. Resolve (never reject) when done, and if a flush is already running, return that same promise.
  • pending(): ids still queued, in order. failed(): the permanently rejected mutations.

The fake network takes a script of outcomes, one per request: 'ok', 'offline' (rejects), 'lost-ack' (the server applies it, then the response is lost), 'unavailable' (503) and 'reject' (422). The preview has no IndexedDB (it runs in a sandboxed frame), so the queue lives in memory here. In an app, it's a table written in the same transaction as the change.

Console
  1. Nothing logged yet.
  • Changes are delivered in order and leave the queue
  • A network failure keeps the change, stops the flush, and a later flush finishes the job
  • A lost acknowledgement is retried with the same id, and applied only once
  • 4xx responses are moved to failed; 5xx responses are kept for retry
  • Calling flush() twice at once doesn't send anything twice

What the exercise leaves out, and production needs: persistence (the queue is a table, written in the same transaction as the local change), backoff with jitter between attempts (min(cap, base * 2 ** attempt) * Math.random() is a common shape) so a thousand clients coming back online don't hammer the server in lockstep, a timeout on every send, and triggers to flush: app start, online, visibilitychange to visible, after each enqueue, and Background Sync or WorkManager where they exist.

Reconciling with the server

When the server acknowledges a mutation it may return the canonical record (server-assigned fields, normalized values, the result of merging someone else's concurrent edit). Apply that to the local store, but only if no newer local mutation for the same record is still pending, or you'll briefly revert the user's latest edit. The simplest rule: local state = server state + pending mutations replayed on top. Many sync engines implement exactly that: they keep the last server snapshot and rebase pending local mutations onto each new snapshot.

Recap

  • Local-first: the UI reads and writes a local database; the network only syncs. Connectivity stops being a UI state.
  • navigator.onLine is a hint. Put timeouts on every request and assume responses can be lost.
  • Service workers install, wait, activate and get killed when idle; version them, avoid careless skipWaiting(), and keep state in Cache Storage or IndexedDB.
  • Choose caching per resource (cache-first for hashed assets, network-first with timeout or stale-while-revalidate for content), and don't run IndexedDB transactions across non-IDB awaits.
  • An outbox with client-generated ids, in-order single-flight sending, and retryable vs permanent error handling makes writes survive any network; background sync is a bonus, not a foundation.

Finished this lesson?

Mark it complete to track your progress on this device.