Back to blog

Why your extension service worker keeps dying

MV3 service workers stop after 30 seconds idle and lose every global variable. The exact timeouts, what resets them, and the patterns that survive a restart.

ExtensionBill 6 min read Updated

You set a variable in background.js, close the popup, come back a minute later, and it is undefined. Your setTimeout never fired. Your listener stopped responding. Nothing is broken: this is Manifest V3 working exactly as designed, and once you know the rules the workarounds are short.

The timeouts, exactly

Chrome terminates an extension service worker when any of these happen:

  • 30 seconds of inactivity. This is the main one. Receiving an event or calling an extension API resets the timer.
  • 5 minutes on a single request. One event handler or API call that runs longer than five minutes gets killed mid-flight.
  • 30 seconds waiting on fetch(). A response that has not arrived in 30 seconds terminates the worker.

“Inactivity” means no events and no extension API calls. A long await on something that is not an extension API does not keep you alive.

What resets the idle timer

Chrome has expanded this list over several releases, so the behavior depends on the minimum version you support:

SignalSince
Native messaging connectionsChrome 105
Messages from an offscreen documentChrome 109
Any extension API callChrome 110
Long-lived message portsChrome 114
WebSocket messages sent or receivedChrome 116

If you support Chrome 110+, “call an extension API” is the practical rule. If you need a persistent socket, Chrome 116+ keeps the worker alive while messages flow across it.

Rule 1: register listeners at the top level

This is the failure that produces the most confusing bug reports. When Chrome wakes a terminated worker for an event, it re-runs your whole script and then dispatches the event. If the listener registration is inside a callback, a promise chain, or an async IIFE, it may not exist yet when the event fires.

// Broken: the listener is registered asynchronously
chrome.storage.local.get('config', (config) => {
  chrome.runtime.onMessage.addListener(handler) // may miss the wake-up event
})

// Correct: registration is synchronous and top-level
chrome.runtime.onMessage.addListener(handler)

async function handler(msg, sender, sendResponse) {
  const { config } = await chrome.storage.local.get('config')
  // ...
  return true // keep the message channel open for an async response
}

Everything that must survive a restart (message listeners, alarm listeners, onInstalled, onStartup, context menu handlers) is registered at the top level, unconditionally, on every script evaluation.

Rule 2: globals are cache, never state

Every global is gone after termination. Treat in-memory values as a cache you may lose at any moment and keep the source of truth in chrome.storage (or IndexedDB for anything large).

let cachedToken = null // fine as a cache, fatal as the only copy

async function getToken() {
  if (cachedToken) return cachedToken
  const { token } = await chrome.storage.local.get('token')
  cachedToken = token ?? null
  return cachedToken
}

Which storage area to use:

  • chrome.storage.local for device-scoped data and anything sizeable
  • chrome.storage.sync for small values that should follow the user across browsers (roughly 100KB total, 8KB per item)
  • chrome.storage.session for values that should not survive a browser restart but should survive a worker restart, such as an in-memory auth token
  • IndexedDB for large or structured datasets

Rule 3: alarms instead of timers

setTimeout and setInterval die with the worker. chrome.alarms persist and wake the worker to deliver the event.

// manifest.json needs: "permissions": ["alarms"]

chrome.alarms.create('sync', { periodInMinutes: 1 })

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name !== 'sync') return
  await syncNow()
})

Since Chrome 120 the minimum alarm period is 30 seconds, matching the service worker idle timeout. If you need something to happen more often than that, you need a different mechanism, and usually a different design: sub-30-second work belongs in a content script, an offscreen document, or the page the user is looking at.

Rule 4: do not fight the lifecycle

Every “keep alive” trick you find in a forum thread (a self-pinging message loop, a dummy chrome.runtime.getPlatformInfo() on an interval, a permanent port to a content script) works by making Chrome think your extension is busy. Google’s guidance limits that pattern to managed enterprise and education deployments, and reviewers have flagged extensions that burn CPU to stay resident.

The framing that actually works: your worker is a function, not a process. It should start fast, handle one event, persist what it learned, and be ready to die. If you find yourself needing a resident process, the honest options are an offscreen document for the specific API you need (audio, clipboard, DOM parsing), or moving the work to a server.

Rule 5: know which startup event you get

Three distinct moments run different code paths:

  • Install or update: the SW install event, then chrome.runtime.onInstalled, then the SW activate event
  • Browser start: chrome.runtime.onStartup only, with no service worker lifecycle events
  • Wake from idle: no lifecycle event at all, the script is simply re-run and the triggering event dispatches

That last case is why one-time setup belongs in onInstalled, not at the top level. Top-level code runs on every single wake-up, dozens of times an hour.

chrome.runtime.onInstalled.addListener(async ({ reason }) => {
  if (reason === 'install') await chrome.storage.local.set({ installedAt: Date.now() })
  if (reason === 'update') await migrateSchema()
})

Debugging a worker you cannot catch

The service worker devtools window closes when the worker terminates, which makes intermittent bugs hard to observe.

  1. Open chrome://extensions, enable Developer Mode, and click service worker under your extension to open its console.
  2. Use the Stop button next to the service worker link to force termination on demand, then trigger your feature. If it fails only after a forced stop, you have a state-in-globals bug.
  3. Watch for Uncaught (in promise) on wake-up. A top-level await that rejects can leave listeners unregistered.
  4. If a listener never fires after idle, check that its addListener call is genuinely top-level and synchronous.
  5. chrome://serviceworker-internals shows the running state when the devtools window will not stay open.

Where this bites payment code

Anything that polls a server for a status change is exactly the pattern MV3 makes awkward: the user leaves the browser to complete a checkout, comes back, and the code that was supposed to notice is long dead.

That is why the ExtensionBill SDK is built around alarms and top-level registration rather than timers:

// background.js
import { ExtensionBill } from '@extensionbill/sdk'

// Re-created on every service worker start. chrome.alarms persists, so a poll
// in progress resumes after a restart instead of being lost.
const bill = ExtensionBill({ publishableKey: 'pk_live_…' })

// Registers onInstalled, onStartup, onMessage, and onAlarm listeners,
// top level, once.
bill.startBackground()

bill.onPaid((user) => {
  // Fires even if the worker was terminated while the user was on the
  // checkout page.
})

The same shape applies to your own code: persist the fact that work is pending, schedule an alarm, and let the wake-up finish the job.

Checklist

  • All addListener calls are top-level and synchronous
  • No state lives only in globals; chrome.storage holds the truth
  • No setTimeout or setInterval for anything that must outlive 30 seconds
  • Periodic work uses chrome.alarms with a period of 30 seconds or more
  • One-time setup is in onInstalled, not at the top level
  • No keep-alive hacks in a consumer extension
  • Tested after clicking Stop on the worker, not just after a reload

If you are still moving off Manifest V2, the MV3 migration checklist covers the rest of the API changes, and the manifest validator catches deprecated background keys before you submit. When you are ready to charge for the result, adding payments is the next step.