Skip to content
TheChatArchiveThe Chat Archive
Grok 4.1 Fast· xaiHugging Face Frontier Reasoning Traces

Draft a service worker resilience map specifying offline fallbacks, cache partitioning,…

  1. User

    Draft a service worker resilience map specifying offline fallbacks, cache partitioning, and background sync policies for a cross-device planner app.

  2. 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 via self.__WB_MANIFEST for precaching updates.

    Storage Backend:

    • Precaches: Static assets (app shell, icons).
    • Runtime Caches: Dynamic API responses, user data.
    • IndexedDB: Local task store (plannerDB with 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 PrefixContentsSize LimitUpdate PolicyAccess Strategy
    v1::shellApp shell (HTML, CSS, JS bundles, manifest, icons)10MBPrecaches on installCache-first
    v1::assets::{userId}Images, user-uploaded attachments5MB/partitionRuntime cacheCache-first (with 7d TTL)
    v1::api-staticStatic API responses (e.g., categories, templates)2MBRuntime cacheStale-while-revalidate (bg fetch)
    v1::tasks::{userId}User tasks/calendar data (JSON from /api/tasks)20MB/partitionRuntime cacheNetwork-first (cache on success)
    v1::offline-uiOffline fallback UI (e.g., "Syncing..." screens)1MBPrecachesCache-first
    v1::sync-queue::{deviceId}Background sync stubs (queued ops)5MB/partitionIndexedDB mirrorN/A (read-only from IDB)

    Partitioning Logic (in SW fetch handler):

    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-expiration with maxEntries: 200 per 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/PathOnline BehaviorOffline FallbackRationale
    / (App Shell)Network-first → CacheCached shell + IndexedDB tasksInstant load; show local planner.
    /planner/* (Tasks/Calendar)Network-first → Cache + IDBStale IndexedDB data + offline bannerView/edit local tasks; queue changes.
    /api/tasks (CRUD)Network-first → CacheReturn IndexedDB mirror + queue mutationSeamless UX; no data loss.
    /api/syncNetwork-firstCustom response: {status: 'offline', queued: N}Inform UI of pending syncs.
    /assets/*Cache-first404 → Generic offline imageFast static loads.
    Any otherNetwork-first/offline.html (from v1::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 syncQueue store. Register sync on sync event.

    OperationQueue EventSync PayloadRetry PolicySuccess Handling
    POST /api/tasks (Add)before fetch 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)before fetch fail{op: 'update', id, data: changes}Same as aboveMerge IDB; invalidate v1::tasks::* cache.
    DELETE /api/tasks/:idbefore fetch fail{op: 'delete', id}Same as aboveRemove from IDB; cache purge.
    Bulk SyncPeriodic (every 5m offline)All queued ops in timestamp orderMax 100 ops/batchPartial 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 postMessage before delete.
    • Cross-Device Sync: DeviceId partitions prevent overwrites; server merges.

    Monitoring & Testing

    • Logs: SW console.log to 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.