Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Background Service Workers

The Service Worker Lifecycle

Understand when the extension service worker starts, how long it lives, what keeps it alive, why it stops, and how to design long tasks, retries and state restoration.

The most common bug in Manifest V3 extensions is assuming the service worker is always there. It is not. This lesson explains when it starts, how long it lives, what extends its life, and what to do when it vanishes in the middle of your work.

Start, run, stop

A service worker goes through repeating cycles:

  1. Installed or updated. Chrome starts the worker and fires chrome.runtime.onInstalled (once per install or update).
  2. Event arrives. If the worker is stopped, Chrome starts it, runs the top of your script and delivers the event.
  3. Idle. After the last event handler finishes, a countdown begins. After about 30 seconds with no events and no extension API activity, Chrome stops the worker.
  4. Terminated. Variables, timers and in-flight promises are gone. The next event repeats step 2.
stateDiagram-v2
    [*] --> Stopped
    Stopped --> Running: event (message, alarm, click)
    Running --> Running: new events reset the idle timer
    Running --> Stopped: idle ~30 s, or one task > 5 min
    Running --> Stopped: Chrome frees memory

Every stop wipes memory; every start runs your script again from the top.

What resets the idle timer

Chrome counts these as activity, restarting the 30-second timer:

  • Receiving an event (a listener running).
  • Calling an extension API (each chrome.* call that completes).
  • Receiving a message on an open port (in recent Chrome versions).
  • A WebSocket connection sending or receiving a message (Chrome 116+).

Chrome also enforces hard limits: a single event handler or request may run for at most 5 minutes, and a fetch response that takes more than 30 seconds to arrive can end the worker. Long background jobs therefore need design.

Do not "keep the worker alive" with tricks. Pinging yourself every 20 seconds is a hack that wastes memory and may break with a Chrome update. Design for restarts instead.

Designing for restarts

1. Use alarms instead of timers

setTimeout and setInterval die with the worker. chrome.alarms persist and wake it up:

JavaScript
chrome.alarms.create("refresh", { periodInMinutes: 15 });
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === "refresh") refreshData();
});

See alarms.

2. Store progress

If a task has steps, save which step you finished:

JavaScript
async function importAll(items) {
  const { done = 0 } = await chrome.storage.local.get("done");
  for (let i = done; i < items.length; i++) {
    await importOne(items[i]);
    await chrome.storage.local.set({ done: i + 1 });  // resume point
  }
  await chrome.storage.local.remove("done");
}

If the worker dies at item 40, the next start continues at 40 instead of 0.

3. Rebuild caches lazily

A variable cache is fine, but wrap it so a missing value is re-created:

JavaScript
let cache = null;
async function getRules() {
  cache ??= (await chrome.storage.local.get({ rules: [] })).rules;
  return cache;
}

4. Keep handlers short

Do the quick part in the event handler. For heavy jobs, split work into chunks and persist progress, or move it to an offscreen document, which has a DOM and its own lifetime.

Replaying a worker's life

The simulation below models a worker that stops after 30 "seconds" of idleness. It handles three jobs, once with a naive in-memory queue and once with persisted progress. Compare what is lost.

JS Naive vs resumable job

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A visual timeline

Here is the idle countdown as something you can click. Each "event" resets the timer; when it reaches zero the worker stops and its memory counter drops to zero.

Idle timer playground

Press the button a few times, wait for the worker to stop, and press again. The stored counter keeps counting; the in-memory one starts over.

Detecting a restart

Sometimes you need to know whether this is a fresh start. A simple trick: keep a flag in chrome.storage.session and a matching variable.

JavaScript
let warm = false;

async function ensureReady() {
  if (warm) return;
  const { initialized } = await chrome.storage.session.get("initialized");
  if (!initialized) {
    await firstTimeSetup();
    await chrome.storage.session.set({ initialized: true });
  }
  warm = true;
}

chrome.storage.session survives worker restarts but is cleared when the browser closes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Roughly how long can the service worker sit idle before Chrome stops it?

    Chrome stops an idle worker after about 30 seconds without events or extension API activity.
  2. 2. Why is setInterval a poor choice for periodic work?

    Timers live in worker memory. chrome.alarms persist across restarts and wake the worker.
  3. 3. How can a long import survive the worker being terminated?

    Persisting a resume point makes the job restartable. There is no manifest setting to extend the idle timeout.
  4. 4. Which storage area survives worker restarts but is cleared when the browser closes?

    storage.session is held in memory by the browser, so it outlives the worker but not the browser session.

Summary

  • The worker starts on an event, stops after about 30 s idle and loses all memory.
  • Activity (events, API calls) resets the timer; single tasks over five minutes are cut.
  • Use chrome.alarms, persisted progress and lazy caches instead of timers and globals.
  • Keep handlers short; use offscreen documents for DOM-needing work.
  • Do not rely on keep-alive hacks.

Next: Events, Alarms and the Badge