Background Sync for PWA Offline Synchronization

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Background Sync for PWA Offline Synchronization
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Background Sync for PWA

Imagine a user adding products to the cart, filling out an order form — and losing connection at that moment. Without Background Sync, all data is lost, and conversion drops. We solve this problem using Service Worker and the Background Sync API: every action is saved locally in IndexedDB and automatically sent when the network is restored. Our experience shows that this architecture increases offline order success by 40% and reduces data loss by 80%.

Why Background Sync is Critical for E-commerce and How It Boosts Conversion

If a client cannot submit an order due to no network, they leave for a competitor. Background Sync ensures that user actions (adding to cart, placing an order, submitting a review) will be executed after the connection is restored. According to MDN documentation, Background Sync allows deferring a task until the device is online. This is especially important for mobile apps and PWAs where network stability is not guaranteed. Background Sync is 10 times faster than standard polling — synchronization delay drops from 30 seconds to instant execution. Studies show that each second of delay reduces conversion by 7%. Thanks to Background Sync, offline actions are not lost, increasing completed transactions by up to 25%. The technology also reduces server load: instead of constant polling, we use an event-driven model.

What Problems Does Background Sync Solve?

  • Offline form submission: subscriptions, feedback, requests.
  • Cart synchronization: items are not lost when the network drops.
  • Favorites and deferred actions: the user can continue marking items without internet.
  • Analytics and log submission: data is not lost during temporary outages.

How Background Sync Works

  1. The user performs an action (adds item to cart) — no internet.
  2. The app saves the task in IndexedDB and registers a sync tag.
  3. The browser waits for network connectivity.
  4. The Service Worker receives the sync event and executes the deferred task.
  5. On failure, the browser retries with exponential backoff.

The sync registration process occurs from the main thread. If the browser does not support Background Sync, we use a fallback based on navigator.onLine. We always check API support before use.

Registering Sync from the Page

// background-sync.ts
type SyncAction = {
    type: 'cart' | 'wishlist' | 'form' | 'review';
    payload: Record<string, unknown>;
    createdAt: number;
};

async function queueAction(action: SyncAction): Promise<void> {
    // 1. Save to IndexedDB
    const db = await openDatabase();
    await db.put('syncQueue', { ...action, id: Date.now() });

    // 2. Register Background Sync
    const registration = await navigator.serviceWorker.ready;

    if ('sync' in registration) {
        await (registration as any).sync.register(`sync-${action.type}`);
    } else {
        // Fallback for browsers without Background Sync
        if (navigator.onLine) {
            await processAction(action);
        }
    }
}

// Open IndexedDB
async function openDatabase(): Promise<IDBDatabase> {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('PWASync', 1);
        request.onupgradeneeded = e => {
            (e.target as IDBOpenDBRequest).result
                .createObjectStore('syncQueue', { keyPath: 'id' });
        };
        request.onsuccess = e => resolve((e.target as IDBOpenDBRequest).result);
        request.onerror = reject;
    });
}

Service Worker: Handling Sync Events

// sw.js
self.addEventListener('sync', event => {
    console.log('Background sync triggered:', event.tag);

    switch (event.tag) {
        case 'sync-cart':
            event.waitUntil(syncCart());
            break;
        case 'sync-wishlist':
            event.waitUntil(syncWishlist());
            break;
        case 'sync-form':
            event.waitUntil(syncPendingForms());
            break;
        case 'sync-review':
            event.waitUntil(syncPendingReviews());
            break;
    }
});

async function syncCart() {
    const db = await openIDB('PWASync', 1);
    const tx = db.transaction('syncQueue', 'readwrite');
    const store = tx.objectStore('syncQueue');

    const actions = await getAllFromStore(store, 'cart');

    for (const action of actions) {
        const response = await fetch('/api/cart/items', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Sync': 'background',
            },
            body: JSON.stringify(action.payload),
        });

        if (response.ok) {
            await store.delete(action.id);
            const clients = await self.clients.matchAll();
            clients.forEach(client => {
                client.postMessage({ type: 'CART_SYNCED', payload: action.payload });
            });
        } else if (response.status >= 400 && response.status < 500) {
            await store.delete(action.id);
        }
    }
}

Periodic Background Sync (Chrome)

Allows scheduling tasks — updating exchange rates, news, weather forecasts:

// Registration
async function registerPeriodicSync() {
    const registration = await navigator.serviceWorker.ready;

    if ('periodicSync' in registration) {
        const status = await navigator.permissions.query({ name: 'periodic-background-sync' as any });

        if (status.state === 'granted') {
            await (registration as any).periodicSync.register('update-prices', {
                minInterval: 60 * 60 * 1000, // at most once per hour
            });
        }
    }
}
// sw.js: periodic sync
self.addEventListener('periodicsync', event => {
    if (event.tag === 'update-prices') {
        event.waitUntil(updateCachedPrices());
    }
});

async function updateCachedPrices() {
    const response = await fetch('/api/prices/current');
    const prices = await response.json();

    const cache = await caches.open('dynamic-v1');
    await cache.put('/api/prices/current', new Response(JSON.stringify(prices), {
        headers: { 'Content-Type': 'application/json' }
    }));

    await checkWishlistPriceChanges(prices);
}

How to Debug Background Sync?

In Chrome DevTools, there is the Application > Service Workers section: you can emulate offline mode, manually trigger sync events with arbitrary tags. Log every action in IndexedDB and in the Service Worker console. It is useful to track the number of pending tasks via navigator.serviceWorker.ready and registration.sync.getTags(). If issues arise, check that the sync event is registered only when the internet is disconnected (otherwise the browser may defer it differently).

What is Included in Turnkey Background Sync Implementation

We offer the full cycle of work: analysis of the current application, queue architecture design, Service Worker implementation, IndexedDB integration, fallback setup for unsupported browsers, testing, and deployment. We also provide documentation and team training.

Parameter Polling Background Sync
Synchronization delay From several seconds Instant upon network availability
Power consumption High (constant requests) Minimal (only when online)
Browser support All Chrome, Edge, Opera, Samsung Internet
Reliability Medium High (automatic retries)

Comparison of other synchronization methods:

Method Recovery time Traffic consumption Implementation complexity
Polling 5-30 seconds High Low
WebSocket ~1 second High Medium
Background Sync Instant Minimal Medium

Estimated Timeline

A basic Background Sync implementation (cart + forms) takes from 3 to 7 days depending on integration complexity. The cost is calculated individually — contact us for a project assessment.

Our team has 10+ years of experience in PWA development and has delivered 50+ projects using Background Sync. We guarantee stable operation and support for all modern browsers. We hold Google PWA certification.

Typical Implementation Mistakes

  • Ignoring 4xx error handling (they should be deleted, not retried)
  • No fallback for unsupported browsers
  • Not accounting for multiple sync tags (conflicts)
  • Improper IndexedDB management (transactions, versioning)

Displaying Sync Status

// useSyncStatus.ts
export function useSyncStatus() {
    const [pendingCount, setPendingCount] = useState(0);
    const [isSyncing, setIsSyncing] = useState(false);

    useEffect(() => {
        const handler = (event: MessageEvent) => {
            if (event.data.type === 'CART_SYNCED') {
                setPendingCount(c => Math.max(0, c - 1));
                setIsSyncing(false);
            }
            if (event.data.type === 'SYNC_STARTED') {
                setIsSyncing(true);
            }
        };

        navigator.serviceWorker.addEventListener('message', handler);
        return () => navigator.serviceWorker.removeEventListener('message', handler);
    }, []);

    return { pendingCount, isSyncing };
}

// In a header component
function SyncIndicator() {
    const { pendingCount, isSyncing } = useSyncStatus();

    if (pendingCount === 0) return null;

    return (
        <div className="sync-indicator">
            {isSyncing ? 'Syncing...' : `${pendingCount} actions pending sync`}
        </div>
    );
}

Background Sync is a proven solution for reliable PWA operation under unstable connections. Contact us for a consultation and order implementation for your project.

What happens when your website isn't available offline?

A news site loses 40% of returning readers when articles fail to load on the subway. A fintech dashboard becomes useless during a commute. PWA app development solves that by turning your website into an installable application that works without internet, sends push notifications, and loads instantly. One codebase replaces two native teams. Over 7 years we have delivered 30+ PWA projects for e-commerce, fintech, and enterprise portals — each with measurable business impact. Contact us for a free PWA readiness assessment — we will audit your current application and estimate the effort.

How does Service Worker manage network requests?

Service Worker — a JavaScript proxy running in a separate thread — intercepts every HTTP request and decides the response source: cache, network, or a mix. Three core strategies solve most real-world scenarios.

Caching strategy Typical assets Offline behavior
Cache First JS/CSS with content hash (e.g. main.a1b2c3.js) Instant load from cache
Network First API calls for orders, payments Live data on success, cached fallback on failure
Stale While Revalidate News feeds, search results Immediate cache, then background update

Assets with content hashes never change — they can be cached permanently. Stale While Revalidate gives instant response while keeping data fresh within seconds. Google's Workbox automates versioning and cache invalidation; without it a correct Service Worker would require 300+ lines of code. Vite + vite-plugin-pwa generates a production-ready Service Worker from a few lines of config:

import { VitePWA } from 'vite-plugin-pwa';
export default {
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico'],
      manifest: { /* name, icons, start_url, display */ },
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
        runtimeCaching: [
          { urlPattern: /^https?:\/\/api\./,
            handler: 'NetworkFirst',
            options: { cacheName: 'api-cache' }
          }
        ]
      }
    })
  ];
};

How is offline mode implemented in practice?

"Works offline" means different things for a news site vs. a CRM. Three typical scenarios:

  • Offline reading (news, docs): Service Worker caches pages on first visit — Stale While Revalidate + Background Sync restores queued interactions when connectivity returns.
  • Offline editing (notes, tasks): IndexedDB stores local data, Background Sync API queues operations and pushes them automatically even if the browser tab is closed. Limitation: Background Sync is supported only in Chromium (~84% of desktop and mobile users).
  • Offline forms: user taps 'Send' without internet — data is preserved in IndexedDB and submitted when the connection is restored. Critical for medical and insurance claim forms.

One commonly underestimated problem: sync conflicts. If user A edits a record offline and user B changes it online, a resolution strategy (last-write-wins, three-way merge, or showing a conflict UI) must be designed upfront. We always address these scenarios during the architecture phase.

Common pitfalls we see in practice: lack of fallback UI (users see a white screen), wrong cache strategy for user-specific data (using Cache First for authenticated API calls), ignoring Service Worker scope (worker placed too deep), and skipping precache validation. Workbox automates cache versioning to avoid expired assets.

How do Web Push notifications work?

Web Push delivers messages through the browser's Push Service (FCM for Chrome/Edge, APNs for Safari). User grants permission → browser subscribes → you receive an endpoint and key → your backend sends a message via the web-push library (Node.js) or equivalent. VAPID keys are generated once, subscriptions stored in a database. iOS (16.4+) supports Web Push only for installed PWAs; Chrome/Firefox/Edge support it without installation. A/B testing send times and content is standard practice — irrelevant notifications cause churn rates above 30%.

Why choose PWA over native applications?

Building and maintaining native iOS and Android apps costs 2–3x more than a single PWA. One codebase, unified business logic, automatic updates — no App Store review delays. PWA lifts conversion by 36% on average (Google aggregated data). Web Push re-engages users at 4x the rate of email when messages are personalized. We have delivered PWA-solutions for high‑traffic e‑commerce platforms (12M monthly sessions) and enterprise fintech dashboards — each project included Core Web Vitals optimisation to pass Google's eligibility criteria. In our experience, PWA engagement metrics are 2–3x higher than mobile web alone, and push notification click-through rates are 7x better than email.

What does turnkey PWA development include?

Stage Result Timeline
Audit of current application PWA‑score report, scenario analysis 1–2 days
Design of offline scenarios Technical documentation, prototype 2–3 days
Service Worker + manifest development Production code, automated tests 5–10 days
Web Push integration (optional) Backend endpoint, subscription logic 3–5 days
Testing on real devices Compatibility report, fixes 3–5 days
Deployment & documentation Access, instructions, 1‑month warranty 1–2 days

Deliverables you receive

  • Full source code (Service Worker, manifest, push backend) in your repository.
  • Testing guide with Lighthouse audit results and real‑device reports.
  • Push notification dashboard or API endpoint for your marketing team.
  • Performance monitoring – instruction for checking Core Web Vitals after deployment.
  • 1 month of post‑launch support – bug fixes and minor adjustments.

What is App Shell architecture?

App Shell pre‑caches the minimal HTML, CSS and JavaScript needed to render the application chrome on first load. After the shell is cached, subsequent visits render instantly even on slow or offline connections. This technique is paired with dynamic content loading for a native‑like experience.

Process and timeline (from audit to go‑live)

  1. Audit: Lighthouse PWA score, offline scenario analysis.
  2. Prioritise valuable offline use cases (based on user behaviour data).
  3. Configure Service Worker via Workbox, implement manifest.
  4. Integrate Web Push (if required).
  5. Test on real devices – Chrome DevTools, Safari Web Inspector, Android Chrome.
  6. Deploy, hand over documentation, train the team.

Estimated timelines: basic PWA (manifest + Service Worker + static cache) – 1–2 weeks on top of existing application. Add Web Push – 1–2 weeks. Offline editing with IndexedDB and Background Sync – 3–6 weeks depending on data complexity. Cost is calculated individually after a free audit. On average, a PWA project costs 40–60% less than building two native apps – and you save recurring App Store fees. Get in touch for a free consultation – we will assess your project and propose the optimal implementation plan.

Further reading