Draft a service worker resilience map specifying offline fallbacks, cache partitioning,…
- User
Draft a service worker resilience map specifying offline fallbacks, cache partitioning, and background sync policies for a cross-device planner app.
- Assistant
Service Worker Resilience Map
Overview
This resilience map outlines the Service Worker (SW) strategies for a cross-device planner app (e.g., task lists, calendars, and reminders syncing across devices). The app uses IndexedDB for local data persistence, a REST API for server sync, and Push Notifications for real-time updates.
Goals:
- Ensure core planner functionality (viewing/editing tasks) works offline.
- Minimize stale data with intelligent caching.
- Queue offline changes for background sync.
- Partition caches by user/device for privacy and performance (leveraging Cache Partitioning API where supported).
SW Registration: Single SW at
/sw.js, versioned viaself.__WB_MANIFESTfor precaching updates.Storage Backend:
- Precaches: Static assets (app shell, icons).
- Runtime Caches: Dynamic API responses, user data.
- IndexedDB: Local task store (
plannerDBwith stores:tasks,syncQueue). - Cache Names: Partitioned by origin + user ID (e.g.,
v1::tasks::user123).
1. Cache Partitioning
Caches are partitioned using a namespace strategy:
{version}::{type}::{userId?}::{deviceId?}. Fallback to unpartitioned if Partitioned Cache API unsupported. Total cache quota: 50MB per partition.Cache Name Prefix Contents Size Limit Update Policy Access Strategy v1::shellApp shell (HTML, CSS, JS bundles, manifest, icons) 10MB Precaches on install Cache-first v1::assets::{userId}Images, user-uploaded attachments 5MB/partition Runtime cache Cache-first (with 7d TTL) v1::api-staticStatic API responses (e.g., categories, templates) 2MB Runtime cache Stale-while-revalidate (bg fetch) v1::tasks::{userId}User tasks/calendar data (JSON from /api/tasks)20MB/partition Runtime cache Network-first (cache on success) v1::offline-uiOffline fallback UI (e.g., "Syncing..." screens) 1MB Precaches Cache-first v1::sync-queue::{deviceId}Background sync stubs (queued ops) 5MB/partition IndexedDB mirror N/A (read-only from IDB) Partitioning Logic (in SW
fetchhandler):const userId = request.headers.get('X-User-ID') || 'anon'; const deviceId = request.headers.get('X-Device-ID') || 'default'; const cacheName = `v1::tasks::${userId}`;- Expiration: Plugins like
workbox-expirationwithmaxEntries: 200per cache. - Cleanup: On
activate, delete old partitions (v0::*).
2. Offline Fallbacks
All routes default to network-first for freshness, with offline UI fallbacks. App shell enables SPA navigation offline.
Route/Path Online Behavior Offline Fallback Rationale /(App Shell)Network-first → Cache Cached shell + IndexedDB tasks Instant load; show local planner. /planner/*(Tasks/Calendar)Network-first → Cache + IDB Stale IndexedDB data + offline banner View/edit local tasks; queue changes. /api/tasks(CRUD)Network-first → Cache Return IndexedDB mirror + queue mutation Seamless UX; no data loss. /api/syncNetwork-first Custom response: {status: 'offline', queued: N}Inform UI of pending syncs. /assets/*Cache-first 404 → Generic offline image Fast static loads. Any other Network-first /offline.html(fromv1::offline-ui)Graceful failure. Implementation Snippets (Workbox-inspired):
// App shell workbox.routing.registerRoute( ({request}) => request.destination === 'document', new workbox.strategies.NetworkFirst({ cacheName: 'v1::shell', plugins: [new workbox.cacheableResponse.CacheableResponsePlugin({statusCodes: [0, 200]})] }) ); // Tasks: Network-first with IDB fallback registerRoute( /\/api\/tasks/, async ({event}) => { try { const netResp = await fetch(event.request); updateIDB(netResp.clone()); // Mirror to local return netResp; } catch { return getFromIDB(event.request.url); // Or offline stub } } );Offline Indicators:
- UI polls
navigator.onLine+ SW message channel. - Show queued count from IDB
syncQueue.
3. Background Sync Policies
Queue offline mutations (add/edit/delete tasks) in IndexedDB
syncQueuestore. Register sync onsyncevent.Operation Queue Event Sync Payload Retry Policy Success Handling POST /api/tasks(Add)beforefetch fail{op: 'create', data: task, timestamp}3 retries, 2x backoff (1m → 30m) Remove from queue; update cache/IDB; notify UI. PUT /api/tasks/:id(Edit)beforefetch fail{op: 'update', id, data: changes}Same as above Merge IDB; invalidate v1::tasks::*cache.DELETE /api/tasks/:idbeforefetch fail{op: 'delete', id}Same as above Remove from IDB; cache purge. Bulk Sync Periodic (every 5m offline) All queued ops in timestamp order Max 100 ops/batch Partial success: retry failures only. SW Sync Handler:
self.addEventListener('sync', event => { if (event.tag === 'sync-tasks') { event.waitUntil(syncQueue()); } }); async function syncQueue() { const queue = await getQueuedOps(); // From IDB for (const op of queue) { try { await fetch(`/api/sync/${op.op}`, {method: 'POST', body: op.data}); await removeFromQueue(op.id); self.clients.matchAll().then(clients => clients.forEach(c => c.postMessage({type: 'SYNC_SUCCESS', op}))); } catch (e) { // Retry logic: reschedule sync tag self.registration.sync.register('sync-tasks'); break; // Partial sync } } }Queueing in App:
- On mutation fail:
idb.add('syncQueue', op); registration.sync.register('sync-tasks');. - Cross-device conflict resolution: Server-side (timestamp + deviceId wins; UI merge conflicts).
Edge Cases:
- Quota Exceeded: Prioritize recent ops; evict oldest.
- Uninstall SW: Export queue to
postMessagebefore delete. - Cross-Device Sync: DeviceId partitions prevent overwrites; server merges.
Monitoring & Testing
- Logs: SW
console.logto DevTools; report to Sentry. - Lighthouse Audit: Target 100% PWA score.
- Test Matrix: Chrome/FF/Safari offline, low battery, network throttling.
- Version Rollout: Blue-green via precache manifest hashing.
This map is version 1.0; review quarterly or post-major features. Implement with Workbox for brevity.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.