Headless crawler OOM: hundreds of zombie and orphaned Chrome processes
Our crawler pod was OOMKilled every few hours and ps showed hundreds of defunct chrome entries. Browsers were never closed on the error path, and Node as PID 1 never reaped the children. try/finally, an init process and a context-per-job model fixed it.
We run a crawler that visits partner product pages, renders them with headless Chrome and extracts prices. It runs as a Kubernetes Deployment with a 3 GiB memory limit. Every three to six hours a pod restarted with:
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
Before the restarts, job latency rose steadily and new launches failed with:
Error: spawn EAGAIN
EAGAIN from fork() means "Resource temporarily unavailable": the process could not be created because a limit was hit.
Reproducing it
On a pod that had been running for two hours we listed processes:
kubectl exec crawler-7d9f-abcde -- ps -eo pid,ppid,stat,rss,etime,comm --sort=-rss | head -20
kubectl exec crawler-7d9f-abcde -- sh -c "ps -eo stat,comm | grep -c '^Z'"
PID PPID STAT RSS ELAPSED COMMAND
4121 1 Sl 412880 01:41:07 chrome
5530 1 Sl 398112 01:22:53 chrome
6012 1 Sl 377204 01:09:30 chrome
...
311
Two things stood out. Dozens of full chrome processes had PPID 1 and were over an hour old, although no job runs longer than 60 seconds. And 311 processes were in state Z (zombie, shown as <defunct>).
We reproduced it locally by pointing the crawler at a test server that returned a slow page for 30% of requests, so page.goto timed out.
What we ruled out
A memory leak inside one page. Heap snapshots of a single long-running browser stayed flat. Memory growth was in the number of processes, not their size.
Too much concurrency. The worker pool was fixed at 4. Concurrency was correct; cleanup was not.
Kubernetes limits. Raising the memory limit to 6 GiB only moved the OOM from 4 hours to 9.
Root cause
Two bugs combined:
Browsers were not closed on the error path. Each job launched its own browser and called
browser.close()at the end of the happy path. Whenpage.gotothrew aTimeoutError, the function exited early and the browser kept running with all its child processes.Nothing reaped dead children. The container started
node crawler.jsdirectly, so Node was PID 1. Chrome's helper processes that exited, or whose parent died, were reparented to PID 1. Node does not callwait()on processes it did not spawn, so they stayed as zombies, eventually counting against the pod's PID limit and causing thespawn EAGAINlaunch failures.
The leaked live browsers caused the OOM. The zombies caused the launch failures.
What is happening under the hood
When a Linux process exits, the kernel keeps a small entry in the process table until its parent reads the exit status with wait(). Until then the process is a zombie: it uses no memory beyond that entry, but it still takes a PID. If the parent dies first, the orphan is reparented to PID 1 of its PID namespace, and that process is expected to reap it.
In a container, PID 1 is whatever your CMD or ENTRYPOINT runs. A normal init system reaps orphans; Node, Python and most application runtimes do not. Chrome starts several processes per browser (zygote, GPU, network service, one renderer per site), so each crash or forced kill leaves several orphans at once.
Leaked browsers are the bigger problem. A headless Chrome with a few tabs uses 200 to 400 MB, and nothing ever stops it if your code loses the reference.
Environment
Component | Version / value |
|---|---|
Cluster | Kubernetes 1.33, containerd |
Image |
|
Node.js | 22 LTS |
Puppeteer | 24.x |
Pod limits | 2 vCPU, 3 GiB memory, |
Concurrency | 4 jobs per pod, one browser launched per job |
Minimal reproduction
// broken: browser leaks when goto throws
async function crawl(url) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url, { timeout: 15000 }); // throws on slow pages
const price = await page.$eval('[data-price]', (el) => el.textContent);
await browser.close(); // never reached on error
return price;
}
# broken: node is PID 1 and never reaps orphans
CMD ["node", "crawler.js"]
Who is affected
Any service that launches browsers per job and runs as PID 1 in a container: crawlers, PDF generators, screenshot APIs, test runners in CI containers. Puppeteer, Playwright and Selenium are all affected the same way, because the problem is process lifecycle, not the library.
Close the browser in finally
async function crawl(url) {
const browser = await puppeteer.launch();
- const page = await browser.newPage();
- await page.goto(url, { timeout: 15000 });
- const price = await page.$eval('[data-price]', (el) => el.textContent);
- await browser.close();
- return price;
+ try {
+ const page = await browser.newPage();
+ await page.goto(url, { timeout: 15000 });
+ return await page.$eval('[data-price]', (el) => el.textContent);
+ } finally {
+ await browser.close().catch(() => browser.process()?.kill('SIGKILL'));
+ }
}
If close() itself hangs because the browser is wedged, the fallback kills the main process so its children become orphans that the init process can reap.
Run an init process as PID 1
With plain Docker, --init injects tini as PID 1:
docker run --init crawler:2026.12
Kubernetes has no --init option, so put tini in the image:
RUN apt-get update && apt-get install -y --no-install-recommends tini \
&& rm -rf /var/lib/apt/lists/*
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["node", "crawler.js"]
tini reaps every orphan and forwards signals such as SIGTERM to Node, so graceful shutdown also started working. An alternative on Kubernetes is shareProcessNamespace: true on the pod, which makes the pause container PID 1, but that also lets containers in the pod see each other's processes.
Reuse one browser, one context per job
Launching a browser per job is slow (300 to 800 ms here) and multiplies the cost of every leak. We now launch one browser per worker and create an isolated browser context per job. A context has its own cookies, storage and cache, and closing it closes all its pages.
const browser = await puppeteer.launch();
async function crawl(url) {
const context = await browser.createBrowserContext();
try {
const page = await context.newPage();
await page.goto(url, { timeout: 15000 });
return await page.$eval('[data-price]', (el) => el.textContent);
} finally {
await context.close();
}
}
In Playwright the equivalent is browser.newContext() and context.close().
Add a watchdog
Even with correct cleanup, a long-lived browser can degrade. The worker now:
recycles the browser after 500 jobs or 30 minutes, whichever comes first;
listens for
browser.on('disconnected')and relaunches;checks the resident memory of its Chrome processes every 30 seconds and recycles above 1.5 GiB;
puts a hard timeout around each job with
AbortController, so one stuck page cannot hold a worker forever.
import { execFileSync } from 'node:child_process';
function chromeRssMb(pid) {
const out = execFileSync('ps', ['-o', 'rss=', '--ppid', String(pid), '-p', String(pid)]).toString();
return out.trim().split('\n').reduce((sum, v) => sum + Number(v), 0) / 1024;
}
How to test the fix
Run the slow-page test server with 30% timeouts and push 5,000 jobs through one worker:
docker run --rm --init -e TARGET=http://slow-server.test:8081 crawler:2026.12 node bench.js --jobs 5000
Afterwards, count processes:
ps -eo stat,comm | awk '$1 ~ /^Z/' | wc -l # expect 0
pgrep -c chrome # expect a small, stable number
Before the fix: 1,420 zombies and 61 live browsers after 5,000 jobs. After: 0 zombies, one browser with 6 to 9 processes.
Confirming in production
Pod memory now stays between 900 MiB and 1.4 GiB with a sawtooth at each browser recycle. No OOMKilled restarts in 14 days.
We export two gauges from each worker: number of Chrome processes and number of zombie processes in the container. Both are flat.
p95 job latency dropped from 6.1 s to 2.3 s, mostly from no longer launching a browser per job.
Regression guard
A lint rule flags
puppeteer.launchandbrowser.newPageoutside the worker module, so new code uses the shared browser and contexts.An integration test runs 200 jobs against a server that times out half the time, then asserts the zombie count is 0 and the Chrome process count is below 15.
Alert when the zombie gauge is above 10 for 10 minutes.
Security implications
Contexts isolate cookies and storage between jobs, which matters if any job logs in to a site; a shared default context would leak sessions between crawls. Leaked browsers also keep authenticated sessions alive in memory longer than needed. tini adds no attack surface beyond a tiny, widely used binary from the distribution repository. Keep the Chrome sandbox enabled; process cleanup does not require --no-sandbox.
Prevention checklist
Wrap every browser, context and page in
try/finallyand close it there.Run an init process (tini or
--init) as PID 1 in every container that spawns children.Launch one browser per worker and use a context per job.
Recycle browsers on a job count or age, and on high memory.
Export Chrome process and zombie counts as metrics and alert on growth.
References
Puppeteer, BrowserContext API: https://pptr.dev/api/puppeteer.browsercontext
Playwright, browser contexts: https://playwright.dev/docs/browser-contexts
Docker run reference,
--init: https://docs.docker.com/reference/cli/docker/container/run/tini README: https://github.com/krallin/tini
Kubernetes, share process namespace between containers: https://kubernetes.io/docs/tasks/configure-pod-container/share-process-namespace/
Linux man page, wait(2): https://man7.org/linux/man-pages/man2/wait.2.html
Add a label
Embed this post
<iframe src="https://hibug.me/headless-crawler-zombie-chrome-processes-oom" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I have spent most of my career on the side of software that pages people at night: payment integrations, web platforms with real traffic, CI/CD pipelines, Kubernetes clusters and the databases underneath them. Somewhere along the way I started keeping a notebook of every bug that cost more than an hour — the exact error, what we ruled out, the real root cause and how we proved the fix. Hibug is where those notes live. Every post follows the same path: Investigate, Explain, Fix, Verify — with the environment spelled out, the fix tested, and the security angle checked.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.