PWA Offline-First Architecture Deep Dive
Design offline-first PWAs with background sync, conflict resolution, and local data persistence.
What you'll learn
- Offline-first design philosophy and UX patterns
- IndexedDB for local data persistence
- Background Sync API for deferred requests
- Conflict resolution: last-write-wins vs CRDT
Concept
PWA Offline-First Architecture Deep Dive
Offline-first means the app works fully offline and syncs when online, providing better UX on flaky networks.
Design Philosophy
Assume the network is unreliable. All writes go to local storage (IndexedDB) first, then sync. Reads always come from local storage. UI shows local data immediately with sync status.
IndexedDB
Browser's local database: transactional, supports indexes, handles large data. Unlike localStorage (5MB, sync), IndexedDB can store gigabytes asynchronously. Use idb or Dexie for Promise API.
Background Sync
The Background Sync API defers network requests until connectivity. When offline, register a sync event. When online, the SW fires sync to replay queued requests with exponential backoff retry.
Conflict Resolution
When syncing, conflicts occur if data was modified on two devices. Strategies: last-write-wins (timestamps), CRDT (mathematically guaranteed to converge), custom merge (domain-specific).
Example
async function addTodo(text) {
const todo = {id: Date.now(), text, synced: false};
const db = await new Promise((res) => { const r = indexedDB.open('app', 1); r.onupgradeneeded = e => e.target.result.createObjectStore('todos', {keyPath:'id'}); r.onsuccess = e => res(e.target.result); });
db.transaction('todos', 'readwrite').objectStore('todos').put(todo);
console.log('Saved locally:', todo);
if ('SyncManager' in window) { const reg = await navigator.serviceWorker.ready; await reg.sync.register('sync-todos'); console.log('Sync registered'); }
}
self.addEventListener('sync', e => { if (e.tag === 'sync-todos') e.waitUntil(console.log('Syncing in background...')); });
console.log('Offline-first defined');
addTodo saves to IndexedDB and registers background sync. SW sync event fires when online, replaying unsynced items.
Try it
- JSON Formatter
Offline data is stored as JSON in IndexedDB - format for debugging.
Common mistakes
The mistake
Not handling sync failures, leaving items unsynced forever.
The fix
Track sync attempts and show failed items with retry button. Don't silently drop data.
The mistake
Using localStorage instead of IndexedDB for large data.
The fix
localStorage is limited to 5MB and blocks main thread. Use IndexedDB for significant data.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.