I'm building a PWA with a network-first caching strategy. I need custom BackgroundSync…
- User
I'm building a PWA with a network-first caching strategy. I need custom BackgroundSync logic that queues POST requests like "Like" actions to IndexedDB when offline and replays them when back online, handling any 409 conflict errors that might come up.
Assistant
This is a great question about building a robust offline-capable PWA with sophisticated background sync and conflict handling. I'll provide a comprehensive solution that covers:
- IndexedDB schema for queuing requests
- Service Worker setup with network-first strategy
- Background Sync API with fallback
- Conflict detection and handling (409 errors)
- Retry logic with exponential backoff
- Request replay with idempotency keys
Let me structure this with:
- IndexedDB manager
- Service Worker registration and setup
- Background sync handler
- Conflict resolution strategy
- Full example usage
This is a production-ready solution.
PWA with Network-First Strategy & Custom Background Sync
Here's a complete solution with conflict handling:
1. IndexedDB Manager
// db/syncQueue.ts interface QueuedRequest { id: string; action: string; resourceId: string; payload: Record<string, any>; timestamp: number; retryCount: number; maxRetries: number; idempotencyKey: string; metadata?: { originalState?: any; conflictVersion?: number; }; } interface ConflictRecord { id: string; queuedRequestId: string; localVersion: number; serverVersion: number; resolutionStrategy: 'server-wins' | 'client-wins' | 'merge'; resolved: boolean; resolvedAt?: number; } export class SyncQueueDB { private db: IDBDatabase | null = null; private readonly dbName = 'offline-sync-db'; private readonly version = 1; async init(): Promise<void> { return new Promise((resolve, reject) => { const request = indexedDB.open(this.dbName, this.version); request.onerror = () => reject(request.error); request.onsuccess = () => { this.db = request.result; resolve(); }; request.onupgradeneeded = (event) => { const db = (event.target as IDBOpenDBRequest).result; // Queue store if (!db.objectStoreNames.contains('queue')) { const queueStore = db.createObjectStore('queue', { keyPath: 'id' }); queueStore.createIndex('timestamp', 'timestamp'); queueStore.createIndex('resourceId', 'resourceId'); queueStore.createIndex('status', 'status'); } // Conflict tracking if (!db.objectStoreNames.contains('conflicts')) { const conflictStore = db.createObjectStore('conflicts', { keyPath: 'id' }); conflictStore.createIndex('queuedRequestId', 'queuedRequestId'); conflictStore.createIndex('resolved', 'resolved'); } // Local state snapshots if (!db.objectStoreNames.contains('snapshots')) { db.createObjectStore('snapshots', { keyPath: 'resourceId' }); } }; }); } async addRequest( action: string, resourceId: string, payload: Record<string, any>, options: { maxRetries?: number; resolutionStrategy?: string } = {} ): Promise<string> { const id = this.generateId(); const idempotencyKey = `${resourceId}-${Date.now()}-${Math.random()}`; const request: QueuedRequest = { id, action, resourceId, payload, timestamp: Date.now(), retryCount: 0, maxRetries: options.maxRetries ?? 3, idempotencyKey, metadata: { resolutionStrategy: options.resolutionStrategy ?? 'server-wins', }, }; return new Promise((resolve, reject) => { const tx = this.db!.transaction(['queue', 'snapshots'], 'readwrite'); const queueStore = tx.objectStore('queue'); queueStore.add(request); // Save local state snapshot const snapshotStore = tx.objectStore('snapshots'); snapshotStore.put({ resourceId, state: payload, timestamp: Date.now(), }); tx.oncomplete = () => resolve(id); tx.onerror = () => reject(tx.error); }); } async getQueue(): Promise<QueuedRequest[]> { return new Promise((resolve, reject) => { const tx = this.db!.transaction(['queue'], 'readonly'); const store = tx.objectStore('queue'); store.getAll().onsuccess = (event) => { resolve((event.target as any).result); }; store.getAll().onerror = () => reject(tx.error); }); } async updateRequest( id: string, updates: Partial<QueuedRequest> ): Promise<void> { return new Promise((resolve, reject) => { const tx = this.db!.transaction(['queue'], 'readwrite'); const store = tx.objectStore('queue'); store.get(id).onsuccess = (event) => { const request = (event.target as any).result; if (request) { store.put({ ...request, ...updates }); } }; tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); }); } async removeRequest(id: string): Promise<void> { return new Promise((resolve, reject) => { const tx = this.db!.transaction(['queue'], 'readwrite'); const store = tx.objectStore('queue'); store.delete(id); tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); }); } async recordConflict( queuedRequestId: string, localVersion: number, serverVersion: number, resolutionStrategy: string ): Promise<string> { return new Promise((resolve, reject) => { const tx = this.db!.transaction(['conflicts'], 'readwrite'); const store = tx.objectStore('conflicts'); const conflict: ConflictRecord = { id: this.generateId(), queuedRequestId, localVersion, serverVersion, resolutionStrategy: resolutionStrategy as any, resolved: false, }; store.add(conflict); tx.oncomplete = () => resolve(conflict.id); tx.onerror = () => reject(tx.error); }); } async resolveConflict(conflictId: string, strategy: string): Promise<void> { return new Promise((resolve, reject) => { const tx = this.db!.transaction(['conflicts'], 'readwrite'); const store = tx.objectStore('conflicts'); store.get(conflictId).onsuccess = (event) => { const conflict = (event.target as any).result; if (conflict) { store.put({ ...conflict, resolved: true, resolutionStrategy: strategy, resolvedAt: Date.now(), }); } }; tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); }); } async getSnapshot(resourceId: string): Promise<any> { return new Promise((resolve) => { const tx = this.db!.transaction(['snapshots'], 'readonly'); const store = tx.objectStore('snapshots'); store.get(resourceId).onsuccess = (event) => { const result = (event.target as any).result; resolve(result?.state ?? null); }; }); } private generateId(): string { return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } } export const syncQueue = new SyncQueueDB();2. Service Worker Setup
// sw.ts import { syncQueue } from './db/syncQueue'; declare const self: ServiceWorkerGlobalScope; const CACHE_NAME = 'api-cache-v1'; const API_BASE = 'https://api.example.com'; // Network-first strategy with caching async function networkFirstFetch( request: Request ): Promise<Response> { try { // Try network first const networkResponse = await fetch(request.clone()); if (networkResponse.ok) { // Cache successful responses const cache = await caches.open(CACHE_NAME); cache.put(request, networkResponse.clone()); } return networkResponse; } catch (error) { // Fall back to cache on network error const cachedResponse = await caches.match(request); if (cachedResponse) { return cachedResponse; } throw error; } } // Intercept fetch requests self.addEventListener('fetch', (event: FetchEvent) => { const url = new URL(event.request.url); // Only handle same-origin requests if (url.origin !== self.location.origin) { return; } // Network-first for API calls if (event.request.url.includes(`${API_BASE}/api/`)) { event.respondWith( networkFirstFetch(event.request).catch(() => { // If offline and no cache, queue POST requests if (event.request.method === 'POST') { return handleOfflinePost(event.request); } return new Response('Offline - No cached data', { status: 503 }); }) ); } else { // Cache-first for other resources event.respondWith( caches.match(event.request).then((cached) => { return ( cached || fetch(event.request).then((response) => { caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, response.clone()); }); return response; }) ); }) ); } }); async function handleOfflinePost( request: Request ): Promise<Response> { try { const payload = await request.clone().json(); const resourceId = extractResourceId(request.url); await syncQueue.addRequest( 'POST', resourceId, payload, { maxRetries: 3, resolutionStrategy: 'server-wins' } ); return new Response( JSON.stringify({ success: true, queued: true, message: 'Request queued for sync when online', }), { status: 202, headers: { 'Content-Type': 'application/json' }, } ); } catch (error) { return new Response(JSON.stringify({ error: 'Queue failed' }), { status: 500, headers: { 'Content-Type': 'application/json' }, }); } } function extractResourceId(url: string): string { const match = url.match(/\/api\/(\w+)\/(\d+)/); return match ? `${match[1]}-${match[2]}` : url; } // Background Sync self.addEventListener('sync', (event: any) => { if (event.tag === 'sync-queue') { event.waitUntil(syncPendingRequests()); } }); // Periodic Sync (fallback if Background Sync not supported) self.addEventListener('message', (event) => { if (event.data.type === 'SYNC_QUEUE') { syncPendingRequests(); } });3. Sync Manager with Conflict Handling
// sync/syncManager.ts import { syncQueue, SyncQueueDB } from '../db/syncQueue'; interface SyncOptions { maxConcurrent?: number; exponentialBackoff?: boolean; conflictResolution?: (local: any, server: any) => any; } export class SyncManager { private isProcessing = false; private syncOptions: SyncOptions; constructor(options: SyncOptions = {}) { this.syncOptions = { maxConcurrent: 2, exponentialBackoff: true, ...options, }; } async syncPendingRequests(): Promise<{ successful: number; failed: number; conflicts: number; }> { if (this.isProcessing) return { successful: 0, failed: 0, conflicts: 0 }; this.isProcessing = true; const stats = { successful: 0, failed: 0, conflicts: 0 }; try { const queue = await syncQueue.getQueue(); // Process in batches const batches = this.createBatches( queue, this.syncOptions.maxConcurrent || 2 ); for (const batch of batches) { const results = await Promise.allSettled( batch.map((req) => this.processRequest(req)) ); results.forEach((result) => { if (result.status === 'fulfilled') { if (result.value.status === 'conflict') { stats.conflicts++; } else if (result.value.status === 'success') { stats.successful++; } else { stats.failed++; } } else { stats.failed++; } }); } } finally { this.isProcessing = false; } return stats; } private async processRequest( request: any ): Promise<{ status: 'success' | 'failed' | 'conflict'; data?: any }> { try { const response = await this.executeRequest(request); if (response.status === 409) { return this.handleConflict(request, response); } if (!response.ok) { return this.handleRetry(request); } // Success - remove from queue await syncQueue.removeRequest(request.id); return { status: 'success', data: await response.json() }; } catch (error) { return this.handleRetry(request); } } private async executeRequest(request: any): Promise<Response> { const url = `${this.getApiBase()}${this.buildEndpoint(request)}`; const fetchOptions: RequestInit = { method: request.action, headers: { 'Content-Type': 'application/json', 'X-Idempotency-Key': request.idempotencyKey, 'X-Retry-Count': request.retryCount.toString(), }, body: JSON.stringify(request.payload), }; return fetch(url, fetchOptions); } private async handleConflict( request: any, response: Response ): Promise<{ status: 'conflict'; data?: any }> { const conflictData = await response.json(); // Record conflict in DB const conflictId = await syncQueue.recordConflict( request.id, request.payload.version || 0, conflictData.version || 0, request.metadata?.resolutionStrategy || 'server-wins' ); const strategy = request.metadata?.resolutionStrategy || 'server-wins'; switch (strategy) { case 'server-wins': // Discard local changes await syncQueue.removeRequest(request.id); await syncQueue.resolveConflict(conflictId, 'server-wins'); break; case 'client-wins': // Retry with force flag await syncQueue.updateRequest(request.id, { retryCount: request.retryCount + 1, payload: { ...request.payload, _force: true, _version: conflictData.version, }, }); await syncQueue.resolveConflict(conflictId, 'client-wins'); break; case 'merge': // Custom merge logic if (this.syncOptions.conflictResolution) { const mergedPayload = this.syncOptions.conflictResolution( request.payload, conflictData.current ); await syncQueue.updateRequest(request.id, { retryCount: request.retryCount + 1, payload: mergedPayload, }); } await syncQueue.resolveConflict(conflictId, 'merge'); break; } return { status: 'conflict', data: conflictData }; } private async handleRetry(request: any): Promise<{ status: string }> { const backoffDelay = this.syncOptions.exponentialBackoff ? Math.pow(2, request.retryCount) * 1000 : 5000; if (request.retryCount < request.maxRetries) { await syncQueue.updateRequest(request.id, { retryCount: request.retryCount + 1, timestamp: Date.now() + backoffDelay, }); return { status: 'retrying' }; } // Max retries exceeded - keep in queue for manual review await syncQueue.updateRequest(request.id, { metadata: { ...request.metadata, failed: true, lastError: 'Max retries exceeded', }, }); return { status: 'failed' }; } private buildEndpoint(request: any): string { if (request.action === 'POST' && request.resourceId) { const [resource, id] = request.resourceId.split('-'); return `/api/${resource}/${id}/like`; } return '/api/default'; } private getApiBase(): string { return 'https://api.example.com'; } private createBatches<T>(items: T[], batchSize: number): T[][] { const batches: T[][] = []; for (let i = 0; i < items.length; i += batchSize) { batches.push(items.slice(i, i + batchSize)); } return batches; } } // Export singleton export const syncManager = new SyncManager({ maxConcurrent: 2, exponentialBackoff: true, conflictResolution: (local: any, server: any) => ({ ...server, userComment: local.userComment || server.userComment, }), }); // Make syncPendingRequests available to SW export async function syncPendingRequests() { return syncManager.syncPendingRequests(); }4. Main App Integration
// app/offlineManager.ts import { syncQueue } from '../db/syncQueue'; import { syncManager } from '../sync/syncManager'; export class OfflineManager { private isOnline = navigator.onLine; private registrationPromise: Promise<ServiceWorkerRegistration | null>; private syncIntervalId: NodeJS.Timer | null = null; constructor() { this.registrationPromise = this.registerServiceWorker(); this.setupOnlineListeners(); } private async registerServiceWorker(): Promise<ServiceWorkerRegistration | null> { if (!('serviceWorker' in navigator)) return null; try { const registration = await navigator.serviceWorker.register('/sw.js'); // Request Background Sync permission if ('SyncManager' in window && 'Permissions' in window) { const permission = await ( navigator.permissions as any ).query({ name: 'background-sync' }); if (permission.state === 'granted') { await registration.sync.register('sync-queue'); } } return registration; } catch (error) { console.error('SW registration failed:', error); // Fall back to periodic sync this.startPeriodicSync(); return null; } } private startPeriodicSync(): void { if (this.syncIntervalId) clearInterval(this.syncIntervalId); // Sync every 5 minutes when online this.syncIntervalId = setInterval(() => { if (this.isOnline) { this.triggerSync(); } }, 5 * 60 * 1000); } private setupOnlineListeners(): void { window.addEventListener('online', () => { this.isOnline = true; console.log('Online - starting sync'); this.triggerSync(); }); window.addEventListener('offline', () => { this.isOnline = false; console.log('Offline - queuing requests'); }); } private async triggerSync(): Promise<void> { try { const registration = await this.registrationPromise; if (registration?.sync) { await registration.sync.register('sync-queue'); } else { // Fallback if Background Sync not available await syncManager.syncPendingRequests(); } } catch (error) { console.error('Sync trigger failed:', error); } } async likePost(postId: string, userId: string): Promise<any> { const payload = { postId, userId, timestamp: Date.now(), version: 1, }; try { const response = await fetch(`/api/posts/${postId}/like`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Idempotency-Key': `${postId}-${userId}-${Date.now()}`, }, body: JSON.stringify(payload), }); if (response.status === 409) { // Handle conflict in app const conflict = await response.json(); console.warn('Conflict detected:', conflict); } return response.json(); } catch (error) { // Queue for later console.log('Request offline, queuing...'); await syncQueue.addRequest('POST', `posts-${postId}`, payload, { maxRetries: 3, resolutionStrategy: 'server-wins', }); return { queued: true, message: 'Will sync when online', }; } } async getSyncStats(): Promise<any> { const queue = await syncQueue.getQueue(); const pending = queue.filter((req) => !req.metadata?.failed); const failed = queue.filter((req) => req.metadata?.failed); return { pending: pending.length, failed: failed.length, totalQueued: queue.length, }; } destroy(): void { if (this.syncIntervalId) { clearInterval(this.syncIntervalId); } } } export const offlineManager = new OfflineManager();5. React Component Example
// components/LikeButton.tsx import { useState, useEffect } from 'react'; import { offlineManager } from '../app/offlineManager'; interface LikeButtonProps { postId: string; userId: string; onLikeChange?: (liked: boolean) => void; } export function LikeButton({ postId, userId, onLikeChange, }: LikeButtonProps) { const [isLiked, setIsLiked] = useState(false); const [isLoading, setIsLoading] = useState(false); const [isQueued, setIsQueued] = useState(false); const [syncStats, setSyncStats] = useState({ pending: 0, failed: 0 }); useEffect(() => { const interval = setInterval(async () => { const stats = await offlineManager.getSyncStats(); setSyncStats(stats); }, 5000); return () => clearInterval(interval); }, []); const handleLike = async () => { setIsLoading(true); try { const result = await offlineManager.likePost(postId, userId); if (result.queued) { setIsQueued(true); setIsLiked(true); } else if (result.success || !result.error) { setIsLiked(true); setIsQueued(false); } onLikeChange?.(true); } catch (error) { console.error('Like failed:', error); setIsQueued(true); } finally { setIsLoading(true); } }; return ( <div className="like-button-group"> <button onClick={handleLike} disabled={isLoading} className={`like-button ${isLiked ? 'liked' : ''} ${ isQueued ? 'queued' : '' }`} > {isLoading ? '...' : isLiked ? '❤️' : '🤍'} Like </button> {isQueued && ( <span className="queued-indicator" title="Will sync when online"> ⏱️ Queued </span> )} {syncStats.pending > 0 && ( <span className="sync-status"> {syncStats.pending} pending {syncStats.failed > 0 && ` · ${syncStats.failed} failed`} </span> )} </div> ); }6. CSS Styling
/* LikeButton.module.css */ .like-button-group { display: flex; align-items: center; gap: 8px; } .like-button { padding: 8px 12px; border: 2px solid #e0e0e0; background: white; border-radius: 20px; cursor: pointer; transition: all 0.2s ease; font-weight: 600; } .like-button:hover:not(:disabled) { border-color: #ff4458; color: #ff4458; } .like-button.liked { border-color: #ff4458; color: #ff4458; background: #ffe5ea; } .like-button.queued { opacity: 0.7; border-style: dashed; } .like-button:disabled { cursor: not-allowed; opacity: 0.6; } .queued-indicator { font-size: 12px; color: #ff9800; animation: pulse 1s infinite; } .sync-status { font-size: 11px; color: #999; padding: 4px 8px; background: #f5f5f5; border-radius: 4px; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }Key Features:
✅ Network-first strategy with intelligent fallbacks
✅ IndexedDB queuing with metadata tracking
✅ Conflict detection (409 errors) with resolution strategies
✅ Exponential backoff for retries
✅ Idempotency keys to prevent duplicates
✅ Background Sync API with polling fallback
✅ Batch processing to optimize requests
✅ Snapshot tracking for merge conflicts
✅ Stats & monitoring for debuggingThis solution handles real-world offline scenarios with proper error recovery and conflict resolution!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.