Handling Sync Failures and Retries
What you'll learn: How browsers automatically handle failed background sync attempts with smart retry logic.
Why Sync Attempts Fail
Even though you've registered a sync event and the service worker wakes up to handle it, things can still go wrong. The network might be flaky, the server could be temporarily down, or your sync handler code might throw an error. When this happens, you need the browser to try again later—automatically.
Signaling Failure to Trigger Retries
When your sync handler encounters a problem, you signal failure by returning a rejected Promise (or letting an error throw). This tells the browser: "Not now, please try again."
// In your service worker
self.addEventListener('sync', event => {
if (event.tag === 'sync-messages') {
event.waitUntil(
sendQueuedMessages()
.catch(err => {
console.error('Sync failed:', err);
// Promise rejected = browser will retry
throw err;
})
);
}
});
Exponential Backoff Strategy
The browser doesn't retry immediately. It uses exponential backoff—like a polite friend who waits longer each time before asking again. The first retry might happen in a few minutes, the next in tens of minutes, and so on. This prevents hammering a struggling server while still eventually completing the sync when conditions improve.
Think of it like knocking on a door: knock once, wait 2 minutes, knock again, wait 4 minutes, knock again, wait 8 minutes—each wait doubles.
Limits and Eventual Abandonment
The browser won't retry forever. After several failed attempts over an extended period (implementation-specific, but typically days), it gives up. At that point, the queued data remains in IndexedDB until the user revisits your app while online.
Key Takeaway: Rejecting the Promise in your sync handler triggers automatic browser retries with exponential backoff, giving your sync multiple chances to succeed without overwhelming the network or server.