Your Agent's Browser Jobs Finished. The Chrome Processes Didn't.
You open a terminal the morning after a run of scheduled scraping and publishing jobs. The agent service shows active, the last job log says it finished, and nothing paged you. But htop is a wall of chrome, free memory is down to a sliver, and the job that was supposed to run at 06:00 died with “Failed to launch the browser process.” Nothing is obviously broken. Something is just slowly filling up.
This guide covers one specific, common failure on small agent boxes: headless Chrome or Chromium processes that outlive the job that started them. We’ll go through the errors you’ll see, the cousins to rule out, how to confirm it with ps, cgroups and /tmp, how to clean up without killing the wrong browser, how to stop it at the service level, and a short fail-closed preflight that blocks the next browser job until the box is clean.
The errors you’ll actually see
People rarely describe this as “orphaned processes.” They say things like “the browser tool worked yesterday and now it won’t start,” “the Pi gets slower every day until I reboot,” or “ps shows forty chrome processes and I only run one job.”
The strings in the logs tend to be some mix of:
- Puppeteer:
Failed to launch the browser process!, often followed by Chrome’s own stderr, orTimeoutError: Timed out after 30000 ms while waiting for the WS endpoint URL to appear in stdout! - Puppeteer:
Protocol error (Target.createTarget): Target closedor similarProtocol error (...)messages when a browser dies mid-session. - Playwright:
browserType.launch: Target page, context or browser has been closed,Browser closed., or a launchTimeout ...ms exceeded. Exact wording varies by version. - Generic Linux pressure:
No space left on devicewhen/tmpfills, orResource temporarily unavailablewhen the box or user hits a process or thread limit. - In
ps, entries marked<defunct>with stateZ. Those are zombies: exited processes nobody reaped.
The tell is the trend. One failed launch is noise. A count of Chrome processes that goes up after every run and never comes back down is this problem.
Rule out the cousins first
A few failures look similar and deserve a quick check before you blame Chrome.
- If
dmesgorjournalctl -kshowsOut of memory: Killed process, the kernel is killing things. That can be a result of orphaned browsers, but read the OOM killer guide to separate cause from effect. - If the box is responsive but every job takes ten times longer and
vmstat 1shows steadysi/soactivity, you’re in swap thrashing. Leftover browsers are one common way to get there. - If the logs say
EMFILEortoo many open files, start with the too many open files guide. Each Chrome process holds a lot of descriptors, so this can also be downstream of orphans. - Stale lock files, such as a
SingletonLockin a reuseduserDataDir, can block launch on their own. If you pin a persistent profile directory, check for that before anything else.
If those come back clean, or they point back at a pile of Chrome, keep going.
Why it hides
Your job runner almost always watches the Node or Python process, not the browser. When that parent exits, the service looks fine. Common ways the browser gets left behind:
- Timeout kills only the parent. A wrapper or scheduler sends SIGKILL to
node. No cleanup code runs, and the browser keeps running. Puppeteer and Playwright typically launch Chrome in its own process group on Linux so they can kill it as a group later, which also means a process-group kill aimed at your script may not reach it. browser.close()is never reached. A selector times out, an exception propagates, and the close call at the bottom of the function never executes.- Cron has no cleanup. Cron starts the job and forgets it. Nothing tracks what it spawned.
- No init in a container. If Node is PID 1 in a container, it usually doesn’t reap orphaned grandchildren, so exited Chrome helpers become
<defunct>zombies. Zombies use almost no memory, but they hold PIDs and show up as noise in every count.
Meanwhile the leftovers sit mostly idle, so CPU graphs look normal. Memory, file descriptors and temp profile directories creep up instead. On distros where /tmp is a tmpfs, those profile directories are RAM too.
Confirm it
Replace agent with the user your jobs run as.
# How many Chrome-family processes does the job user own right now?
pgrep -c -u agent -f 'chrom|headless_shell'
# Oldest first, with parent PID, age in seconds, state and RSS
ps -u agent -o pid,ppid,pgid,etimes,stat,rss,comm --sort=-etimes \
| grep -E 'chrom|headless'
# Top-level browsers whose parent is gone (reparented to PID 1)
ps -u agent -o pid=,ppid=,etimes=,comm= | awk '$2==1 && $4 ~ /chrom|headless/'
# Zombies anywhere on the box
ps -eo pid,ppid,stat,comm | awk '$3 ~ /^Z/'
Two notes. Process names are truncated to 15 characters in comm, so Playwright’s chrome-headless-shell shows as chrome-headless. And orphans don’t always land on PID 1: if a subreaper such as a systemd --user instance is running, they reparent to that instead. Check what the PPID actually is with ps -o comm= -p <ppid>.
Then see where they live and what they hold:
# Which cgroup (and so which service or session) owns a leftover browser?
cat /proc/<pid>/cgroup
systemd-cgls --no-pager | less
# Descriptors held by one browser process
ls /proc/<pid>/fd | wc -l
# Rough RSS total (overcounts shared memory, so treat as an upper bound)
ps -u agent -o rss=,comm= | awk '/chrom|headless/ {s+=$1} END {printf "%.0f MiB\n", s/1024}'
# Temp profile directories and their size
du -sh /tmp/puppeteer_dev_chrome_profile-* /tmp/playwright* \
/tmp/.org.chromium.Chromium.* 2>/dev/null | sort -h | tail -20
If browsers that are hours old sit in a cron session or user.slice instead of the service you expected, and the profile directory count matches the number of runs, you’ve confirmed it.
Clean up safely
Do not run pkill -f chrome on any machine where a person also uses a browser. It will kill their session along with your jobs. Even on a headless box, keep the cleanup narrow: only the job user, only browsers whose driver is gone, only older than a threshold you choose.
JOB_USER=agent
MAX_AGE=1800 # seconds
# List first. Read this output before killing anything.
ps -u "$JOB_USER" -o pid=,ppid=,pgid=,etimes=,comm= \
| awk -v a="$MAX_AGE" '$2==1 && $4>a && $5 ~ /chrom|headless/'
# Then terminate those top-level browsers
ps -u "$JOB_USER" -o pid=,ppid=,etimes=,comm= \
| awk -v a="$MAX_AGE" '$2==1 && $3>a && $4 ~ /chrom|headless/ {print $1}' \
| xargs -r kill -TERM
sleep 5
When the main browser process exits, its renderer and helper children usually follow. Run the listing again; send -KILL only to whatever is still there. If ps shows the browser as its own process group leader (PID equals PGID), kill -TERM -- -<pgid> takes the whole group at once.
Remove profile directories only after the browsers using them are gone. Again, print before deleting:
find /tmp -maxdepth 1 -user agent -mmin +60 \
\( -name 'puppeteer_dev_chrome_profile-*' -o -name 'playwright*' \
-o -name '.org.chromium.Chromium.*' \) -print
# when the list looks right, rerun with: -exec rm -rf {} +
Directory mtime doesn’t always change when files deep inside change, which is why you kill first and delete second. Zombies cannot be killed; they disappear when their parent reaps them or exits.
Make it stop for good
Close the browser on every path. This is the cheap fix and it catches most cases:
const browser = await chromium.launch();
try {
// ...job...
} finally {
await browser.close();
}
finally does not run if the process is SIGKILLed, so you also need a backstop that doesn’t depend on your code behaving.
Run the job as a systemd service, not a bare cron line. systemd puts every process the job spawns, including Chrome in its own process group, into the unit’s cgroup. When the unit stops or times out, it kills the cgroup.
# /etc/systemd/system/browser-job.service
[Unit]
Description=Agent browser job
[Service]
Type=oneshot
User=agent
ExecStartPre=/usr/local/bin/chrome-orphan-preflight.sh
ExecStart=/usr/bin/node /opt/agent/browser-job.js
KillMode=control-group
TimeoutStartSec=20min
TimeoutStopSec=30s
PrivateTmp=yes
KillMode=control-group is already the default; write it explicitly so nobody “fixes” it to process later. For a Type=oneshot job, TimeoutStartSec is the hard cap on run time. RuntimeMaxSec does the same job for long-running Type=simple services but has no effect on oneshot units. TimeoutStopSec is how long systemd waits after SIGTERM before SIGKILL. PrivateTmp=yes gives the unit its own /tmp, which systemd removes when the unit stops, so profile directories can’t accumulate. Pair the service with a .timer unit instead of cron.
Containers need an init. Use docker run --init (or init: true in Compose), or put tini in your entrypoint, so something reaps zombies. You’ll see guides suggest --no-zygote, usually alongside --single-process. That changes how Chrome spawns its helpers and has stability tradeoffs; it isn’t a substitute for a proper init.
A fail-closed preflight
This script counts Chrome-family processes owned by the job user, older than a threshold, that have no live Node or Python driver anywhere above them. Any count above the limit, or any failure to measure, exits 1. It counts processes, not browsers, so one orphaned browser will usually report several.
#!/usr/bin/env bash
# /usr/local/bin/chrome-orphan-preflight.sh
set -euo pipefail
JOB_USER="${JOB_USER:-agent}"
MAX_AGE_SEC="${MAX_AGE_SEC:-1800}"
MAX_ORPHANS="${MAX_ORPHANS:-0}"
MARKER="${MARKER:-/run/agent-preflight/chrome-orphans.alerted}"
WEBHOOK_FILE="${WEBHOOK_FILE:-/etc/agent/discord-webhook-url}"
ps_out="$(ps -eo pid=,ppid=,user=,etimes=,comm=)"
count="$(printf '%s\n' "$ps_out" | awk -v u="$JOB_USER" -v age="$MAX_AGE_SEC" '
{ p=$1; pp[p]=$2; us[p]=$3; et[p]=$4; c[p]=$5; ord[NR]=p }
END {
n=0
for (i=1; i<=NR; i++) {
p=ord[i]
if (us[p]!=u || et[p]<age) continue
if (c[p] !~ /^(chrome|chromium|headless_shell)/) continue
q=pp[p]; driven=0; hops=0
while (q>1 && hops<64) {
if (c[q] ~ /^(node|python|python3|deno|bun)$/) { driven=1; break }
q=pp[q]; hops++
}
if (!driven) n++
}
print n
}')"
[[ "$count" =~ ^[0-9]+$ ]] || { echo "preflight: could not count" >&2; exit 1; }
if (( count > MAX_ORPHANS )); then
echo "preflight: $count orphaned chrome processes for $JOB_USER older than ${MAX_AGE_SEC}s" >&2
if [[ ! -e "$MARKER" && -r "$WEBHOOK_FILE" ]]; then
msg="$(hostname): $count orphaned headless Chrome processes, browser jobs blocked"
# URL goes to curl via stdin config, never argv or logs
if printf 'url = "%s"\n' "$(cat "$WEBHOOK_FILE")" \
| curl -fsS -m 10 -K - -H 'Content-Type: application/json' \
-d "{\"content\":\"$msg\"}" >/dev/null 2>&1; then
touch "$MARKER"
fi
fi
exit 1
fi
rm -f "$MARKER"
echo "preflight: ok"
The marker gives you one alert per outage: it’s written after a successful post and cleared on the first clean run. /run is usually root-only, so create the directory with a tmpfiles.d line such as d /run/agent-preflight 0755 agent agent -. Keep the webhook file mode 0600 and owned by the job user.
The awk ancestor walk treats any Chrome under a non-driver parent as orphaned, which is why the JOB_USER filter matters. Don’t point it at a user who also runs a desktop browser.
Chain it in cron so the job only starts when the box is clean:
*/30 * * * * /usr/local/bin/chrome-orphan-preflight.sh && /usr/local/bin/run-browser-job.sh >> /var/log/agent/browser-job.log 2>&1
Or use it as ExecStartPre= as in the unit above. If it exits non-zero, systemd marks the unit failed and ExecStart never runs.
A standing routine
- Wrap every browser launch in
try/finallywithbrowser.close(). - Run browser jobs as systemd units with a hard timeout and
PrivateTmp=yes, not bare cron lines. - Use
--initortinifor any containerized browser job. - Gate every browser job behind the preflight, so a dirty box fails loudly instead of slowly.
- Once a week, check
pgrep -c -u agent -f chromandduon/tmpprofile directories when the box should be idle. The idle number should be zero. - After any OOM, swap or EMFILE incident, check for leftover browsers before raising limits.
If you want ready-to-use checks like this for your own setup, start with the free prompts. The OpenClaw Agent Ops Toolkit collects preflights, unit templates and runbooks for unattended agent boxes, and the bundle includes it alongside the rest of the MarketMai operator material.
More from the build log
Suggested
Want the full MarketMai stack?
Get the core MarketMai guides and operator playbooks in one premium bundle for $49.
View Bundle