How we made a Manifest V3 extension run a 3-hour job, slowly, on purpose
We build Recant, a Chrome extension that unsends Instagram messages in bulk: you pick a conversation, it removes every message you sent, for both sides.
The product question is simple. The engineering question is not, because a conversation can hold 2,000 of your messages, and doing that safely means doing it slowly: about one message every six seconds. That is more than three hours of work for one chat.
Manifest V3 is not built for three-hour jobs. The background script is a service worker, and Chrome stops it after about 30 seconds without events. Here is what we ended up with, in case you are building anything that has to keep working long after the user stops looking at it.
1. The job lives in storage, never only in memory
The first rule: assume the worker will be killed at any moment, between any two lines. So the whole job is a plain object, persisted to chrome.storage.local after every step: the queue of items, the index reached, counters, the current pace, and a resumeAt timestamp.
function freshJob() {
return {
phase: "idle", // idle | scanning | ready | running | paused | done | error
queue: [], // what is left to do
index: 0, // where we are in it
erased: 0,
failed: 0,
delayBase: 6000, // current pace in ms, adapts to the platform
sinceBreak: 0,
resumeAt: 0, // never act before this time
};
}
When the worker starts, for whatever reason, it loads that object and carries on. Nothing about the job depends on a variable surviving.
Two details that cost us a few bugs:
- Writes are debounced (250 ms), except at the moments that matter (a pause, a failure, the end), where we write immediately. Writing after every single item, thousands of times, is wasteful; not writing before a state change loses it.
- A scan does not survive a restart, a run does. Reading a long history is cheap to redo, so if the worker dies mid-scan the phase goes back to
idle. A run is resumed exactly where it stopped.
2. A heartbeat to wake the worker up
Storage keeps the job. Something still has to wake the worker after Chrome puts it to sleep. That is chrome.alarms:
chrome.alarms.create("heartbeat", { periodInMinutes: 0.5 });
chrome.alarms.onAlarm.addListener((a) => a.name === "heartbeat" && load().then(run));
chrome.runtime.onStartup.addListener(() => load().then(run));
run() is idempotent: if a loop is already alive in this worker instance, it returns at once; if the job is not running, it returns too. So the heartbeat can fire as often as it likes. When the job ends or is paused, the alarm is cleared.
Inside the loop, we never sleep longer than 20 seconds at a time. A long wait (a cooldown, a break) is expressed as resumeAt in storage, and the loop just checks it:
const wait = job.resumeAt - Date.now();
if (wait > 0) {
await sleep(Math.min(wait, 20000));
continue;
}
If Chrome kills the worker during a five-minute break, the next heartbeat wakes it up, it reads resumeAt, and waits for the rest. No timer has to survive.
The result for the user: they can close the side panel, close the Instagram tab, even restart Chrome. The work continues, and a notification says when it is done.
3. Pacing like a person: jitter, backoff, breaks
Platforms watch for automation, and the signature of automation is regularity and speed. Our pacing has four parts:
// 1. A base delay with jitter: 6 s ± 1 s, never a fixed interval
let delay = job.delayBase - jitter + Math.random() * 2 * jitter;
// 2. A real break every 500 actions: 2.5 to 3.5 minutes
if (job.sinceBreak >= breakEvery) {
delay = breakMin + Math.random() * (breakMax - breakMin);
job.sinceBreak = 0;
}
job.resumeAt = Date.now() + delay;
// 3. When the platform pushes back: cool down for a minute AND slow down for good
if (res.throttled) {
job.delayBase = Math.min(job.delayBase + backoff, max); // +1.5 s, capped at 15 s
job.resumeAt = Date.now() + cooldown; // 60 s pause
continue; // retry the same item
}
// 4. After 25 clean successes in a row, speed back up one step (never below the base)
if (++streak >= 25 && job.delayBase > base) job.delayBase -= backoff;
Two less obvious choices:
- Detecting a throttle is harder than checking for HTTP 429. Many refusals come back as a 200 with an error in the body. But a successful response can also contain words like "spam" in ordinary fields. So we only look for throttle signals in responses that are not marked
ok. - The pace is remembered across jobs. If you finish one conversation and start the next, you do not get a fresh, fast pace: the slower rhythm the platform asked for is kept for six hours, and the break counter for fifteen minutes. Without this, a user clearing ten chats back to back would reset the safety margin ten times.
And a circuit breaker: eight hard failures in a row and the job stops with a clear message, instead of hammering on.
4. Remote settings: data, never code
Sooner or later the platform changes, and you need to adjust the pace or pause everything without waiting for a store review. MV3 forbids remote code, which is a good rule. Remote data is fine, so the extension fetches a small JSON every 30 minutes and caches it.
The important part is that the client does not trust it:
const num = (v, lo, hi, d) => typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : d;
// Never faster than 4 s per action, whatever the server says.
CONFIG.pace.base = num(remote.pace?.base, 4000, 60000, DEFAULTS.pace.base);
Every value is type-checked and clamped, strings are matched against strict patterns, and when the server cannot be reached the built-in defaults apply. A compromised or buggy config can make the extension slower, never faster or different.
There is also a hold flag: when it is on, every running job pauses and checks again five minutes later.
5. A side panel instead of a content script
Recant does not inject anything into the Instagram page. The UI is a Chrome side panel, and the work happens in the background worker.
That bought us three things:
- no fight with a page that re-renders constantly and changes its DOM every week;
- the job does not depend on a tab being open or in front;
- a much easier privacy story: the extension reads the session the user already has in this browser, the content of their messages never leaves the computer, and there is no password field anywhere.
6. Small things that bit us
IDs bigger than Number.MAX_SAFE_INTEGER. Message IDs are 19-digit integers. JSON.parse silently rounds them, and you end up "deleting" an ID that does not exist. We quote long numbers before parsing:
JSON.parse(text.replace(/([:\[,]\s*)(-?\d{16,})(?=\s*[,}\]])/g, '$1"$2"'));
A support log with no content. When something goes wrong, users send us a report. It contains times, status codes and the platform's refusal text, and never a single message. We kept it to the last 200 entries in local storage, so it is there when needed and nowhere else.
Counting before acting. Before anything is erased, the panel shows how many messages you sent, out of how many in the conversation, and how long it will take at the current pace. Showing "about 1 h 40 min" up front stopped a whole category of "is it stuck?" emails.
What we would tell anyone building a long-running extension
Put the state in storage and treat the worker as disposable. Use alarms as a heartbeat and make your loop idempotent. Express waits as timestamps, not timers. Jitter everything, back off for real, and remember the backoff. Make remote config strictly data, clamp it on the client, and add a kill switch.
If you are curious what this looks like from the user's side, the extension is Recant for Instagram. Happy to answer questions in the comments.
Comments
No comments yet. Start the discussion.