
Photo by Hal Cooks on Unsplash
My Mac kept freezing under parallel agents, so I gave it a bouncer
M. Zakyuddin Munziri
@zakiego
Paste this into your coding agent. It explains the setup with your computer's numbers, tells you the good and bad parts, and only builds it if you say yes.
# Brief: stop parallel coding agents from freezing the machine
Source: https://zakiego.com/en/articles/parallel-agents-bouncer
You are a coding agent. The user pasted this brief to understand a setup and maybe build their own version. Your first job is to explain it. Building it comes second, and only if they say yes.
## Your job, in order
1. Look before you talk. Read-only: the OS and version, RAM, free disk, swap, CPU cores, which coding agents are installed, and whether the agent you run in has a hook that runs before shell commands. Don't change anything yet.
2. Explain the setup to the user in their language, in plain words, using the Explain section below. Use their numbers where they fit ("you have 8 GB of RAM, so this would allow 1 heavy job at a time").
3. Give the trade-offs from the Trade-offs section. Say plainly whether they need it at all. Someone who runs one agent at a time probably doesn't.
4. Map it to their setup with the Porting section: what carries over as is, what changes, what doesn't exist on their system. Name the commands you would use on their machine, and check each one exists before you rely on it.
5. Recommend the smallest version that fixes their problem. For example: only the watchdog, or only the queue for installs and builds.
6. Ask before building. List the files, hooks, background jobs and settings you'd add or change. Wait for a yes.
7. After a yes, build it from the Build spec, run the Verify steps, and report what you tested and what you didn't.
## The original setup (context, not requirements)
- Machines: a Mac Mini M4 with 16 GB of RAM and a MacBook Air M1 with 8 GB, macOS.
- Agent: Claude Code. Several sessions and subagents at once, each often in its own git worktree, working on JavaScript and Go repos (pnpm, bun, vitest, tsc, go test, local CI in Docker containers).
- What broke: 18 worktrees ran `pnpm install` at once and took the Mac down. Later 4 agents running `pnpm install` froze it again. A dev server preview leaked to a 21.8 GB footprint in 11 minutes. That's well over the 16 GB of RAM.
- Results after the change, November 17 to 20, 2026: 2,044 heavy jobs started, 402 of them next to another job. Lowest free memory while jobs shared the machine: 3,768 MB. 205 jobs gave up after waiting too long (183 of them on one bad day). No reboot since.
## Explain
Use this to explain, not as text to paste.
- The problem: each agent session can behave well on its own, but none can see the others. Several of them see free memory at the same moment, all start an install or build, and together they run out of RAM, swap and disk.
- Part 1, a queue for heavy commands. A hook rewrites every heavy shell command (install, build, test run, typecheck) so it first waits for a slot. Each job reserves a memory cost for its class the moment it starts, before its memory shows up anywhere. A job starts only if the reserved total fits a budget. Agents don't need to know about it: their command just starts later.
- Part 2, dev servers. They never exit, so they can't hold a queue slot. They have to start detached, with a pidfile, and get killed (the whole process tree) before the agent's turn ends.
- Part 3, a memory watchdog. It runs every 20 s, reads each dev process's real footprint (RSS hides swapped and compressed memory), and kills the process tree of a runaway dev process.
- Two failures worth telling: a hook that just said no made agents write their own retry loops, which deadlocked. And a watchdog that killed processes on low disk killed a small service 9 times in 18 minutes without freeing any disk, because killing frees memory, not disk.
## Trade-offs
Good:
- Machine-wide. It works across every session, subagent and agent that goes through the hook, which per-session limits can't do.
- Invisible to agents. They run the same commands, and nobody has to change prompts.
- Crash-safe. A slot belongs to a live process id, so a killed shell can't leak one.
- Measured. Every decision is logged, so class costs come from real peaks, not guesses.
Costs and limits:
- Slower. Jobs wait. In the original setup about 1 in 10 jobs gave up after waiting too long and had to be rerun.
- Class costs are estimates. A job can go over its cost (a `pnpm build` peaked at 4,597 MB against a 4,000 MB cost), so the budget needs headroom and tuning from the log.
- Pattern matching. The hook only knows commands it can classify. A heavy command it doesn't recognize runs unqueued.
- Only what goes through the hook. Work started by a human, an IDE, or an agent without a hook skips the queue unless it uses a wrapper script.
- The watchdog only kills dev processes. A big non-dev process (a 10 GB secret scanner was seen) gets an alert, nothing more.
- Disk is not solved. Low disk was the most common reason jobs waited.
- Killing can lose work: an unsaved dev server state, a half-finished test run.
- The original uses macOS-only commands. Everything in Porting has to be checked on the user's system.
When not to build it:
- One agent at a time, or a machine with plenty of RAM for the usual parallel load.
- Linux with cgroups available: per-job memory caps and an existing out-of-memory daemon may cover most of it with less code (see Porting).
- Work already runs in containers or remote sandboxes with their own limits.
## Porting
The original column is what was built. The others are starting points to check, not tested recipes.
| Piece | Original (macOS + Claude Code) | Linux | Windows |
| --- | --- | --- | --- |
| Hook point | Claude Code `PreToolUse` hook, matcher `Bash`, rewrites via `hookSpecificOutput.updatedInput` | Same if the agent supports a pre-command hook | Same if the agent supports a pre-command hook |
| No hook in the agent | n/a | Shims on `PATH` for `pnpm`, `npm`, `bun`, `go`, `docker` that take the lock, then exec the real binary | Same idea with `.cmd` or PowerShell shims, or run agents in WSL2 |
| Memory pressure | `sysctl kern.memorystatus_vm_pressure_level` (1 normal, 4 critical) | PSI: `/proc/pressure/memory` | `Get-Counter '\Memory\Available MBytes'` |
| Free memory | `vm_stat`, `memory_pressure` | `MemAvailable` in `/proc/meminfo` | `Get-CimInstance Win32_OperatingSystem` (`FreePhysicalMemory`) |
| Process footprint | `top -l 1 -o mem -n 30 -stats pid,mem` | `VmRSS` + `VmSwap` in `/proc/<pid>/status`, or the job's cgroup `memory.current` | Private bytes or commit size per process |
| Short mutex | `lockf` | `flock` | A lock file opened exclusively, or a named mutex |
| Run every 20 s | launchd job | systemd user timer | Task Scheduler |
| Kill a process tree | walk children with `pgrep -P`, TERM then KILL | kill the process group, or the cgroup (`cgroup.kill`) | `taskkill /T /F /PID <pid>` |
| Alert | `osascript` notification | `notify-send` | a toast via PowerShell |
| Built-in help | none per process | `systemd-run --user --scope -p MemoryMax=4G <cmd>` caps one job; `systemd-oomd` or `earlyoom` can replace the watchdog | WSL2 `.wslconfig` `memory=` caps the whole Linux VM |
Other agents: check the agent's own docs for a hook that runs before shell commands, and whether it can rewrite the command or only allow and deny. If it can only deny, don't build a deny-only queue (see Two failures). Use the `PATH` shims or a wrapper command instead. Don't assume a hook exists because Claude Code has one.
Scale the numbers to the machine. The original budget was 7,000 MB of reserved cost on 16 GB and one job at a time on 8 GB. Keep about 2 GB of memory and 10 GB of disk free after a job's cost.
## Build spec
### Part 1: queue for heavy commands
1. Classify the command. Split it into segments on `;`, `&&`, `||`, `|`, `&` and newlines. Remove heredoc bodies, quoted strings and comments first, so `grep "pnpm build"` doesn't match. Classify the payload of `sh -c '...'` and `eval "..."` too. Strip wrappers (`timeout`, `nohup`, `nice`, `corepack`, `npx -y`, absolute paths, `@version` suffixes).
2. Classes and the cost each job reserves (original values, tuned from the log):
| class | memory MB | disk MB | matches |
| --- | --- | --- | --- |
| light | 1500 | 0 | `go test`, `go build` |
| medium | 2500 | 300 | test runners, typecheckers, linters (`vitest`, `tsc`, `go vet`) |
| heavy | 4000 | 1500 | installs, builds, deploys, `docker build`, worktree setup |
| ci | 4000 | 2000 | a local CI job in a container |
A command's class is the biggest class among its segments.
3. Don't deny. Rewrite the command so it starts with one line, then the original command unchanged:
```bash
. ~/.claude/hooks/heavy-lock.sh <max_wait_s> '<label>' <class>
```
The original waits up to 300 s (900 s for background commands) and raises the shell tool timeout to 10 minutes so the wait fits.
4. The lock script is sourced, not executed. It polls an admission script every 1 to 2 s until it gets a slot. On a slot: export a marker env var so nested calls are a no-op, and run. On timeout: print why and exit the shell with code 75, with a message telling the agent to rerun the same command. If the lock machinery itself is broken: warn and run unlocked.
5. Admission rules. A job that finds nothing running always starts. A job that wants to start next to running jobs needs all of:
- fewer than 3 jobs running
- reserved cost of running jobs + its own cost <= the budget (7000 MB on 16 GB)
- memory pressure normal
- free memory minus its cost >= 2048 MB
- free disk minus reserved disk minus its disk cost >= 10 GB
- it doesn't take room an older waiter needs (a waiter older than 120 s gets room held for it)
On an 8 GB machine: 1 job at a time.
6. Slots. One file per running job, named after the pid of the shell that sourced the lock, holding the process start time. Before every decision, drop slots whose pid is dead or whose start time no longer matches (pid reuse). Expire a slot after 45 minutes. Nothing releases a slot by hand, so `kill -9` can't leak one. Guard the decision itself with a short mutex.
7. Deny outright only when the machine is already in trouble: memory pressure critical, or under 5 GB free disk. Applies to heavy commands and dev server starts.
8. Log every event as one JSON line (`wait`, `admit`, `done`, `gaveup`) with time, pid, class, label, waited seconds, reason, free memory, free disk, and for `done` the peak memory of the job's process tree (sample every 1 s for the first 10 s, then every 5 s). Add a `report` command that prints per-class peak memory p50 and max, wait reasons, and commands that used more than their class cost.
9. Only the user turns it off. Deny agent commands that create the off switch or skip the queue.
10. Work outside the agent's shell tool (IDE tasks, scripts) takes the same lock through a wrapper: `heavy-run.sh '<label>' '<command>'`.
Message the agent sees while it waits, for example:
```text
heavy-lock: queued behind '<label>' 199s (a ci job needs 4000 MB, 4000 of 7000 MB is reserved)
```
### Part 2: dev servers
1. In the same pre-command hook, deny dev server starts (`pnpm dev`, `next dev`, `vite dev`, `wrangler dev`, `npm start`, and similar) in both background and foreground form. Allow them when already detached (`nohup`, `setsid`, `disown`) or bounded (`timeout N`).
2. Tell the agent to launch detached and keep a pidfile:
```bash
mkdir -p /tmp/claude-dev; nohup pnpm dev > /tmp/claude-dev/NAME.log 2>&1 & echo $! > /tmp/claude-dev/NAME.pid
```
3. Kill the whole process tree before the turn ends, not only the wrapper pid (`pnpm`, `bun run` and `wrangler` leave the real server orphaned).
### Part 3: memory watchdog
1. Measure each process's real footprint, including compressed and swapped memory. Not RSS: a leaking preview showed 1.6 GB RSS against a 21.8 GB footprint.
2. Dev process = executable basename in an allow list: `node`, `bun`, `deno`, `workerd`, `esbuild`, `python`, `go`, `cargo`, Chromium driven by a browser agent. Never kill system paths, desktop apps, or the agent apps themselves.
3. Rules:
- a dev process over 6144 MB (3072 MB on 8 GB): kill its whole tree, including dev-process parents, TERM then KILL after 5 s
- memory pressure critical or swap nearly full: kill the tree of the biggest dev process over 500 MB, one per run, then check again next run
- a dev server alive over 6 h and over 1 GB: alert only
- a non-dev process over the limit: alert only
- free disk under 5 GB: alert only, never kill
4. Alert with a desktop notification and a log line, at most once per 30 minutes per process. Rotate the log at 1 MB.
5. Add test knobs: dry run, a single target pid, an overridden kill limit, fake trouble.
## Verify
- Start 4 installs from 4 shells at once. Expect one to run and three to wait with a `budget` reason.
- Start a typecheck next to an install. Expect both to run when memory and disk allow.
- `kill -9` a shell holding a slot. Expect the next admission check to drop it.
- Run a dummy process that allocates 400 MB with the watchdog limit set to 200 MB, first in dry run, then for real. Expect its tree killed and a log line.
- After a day of use, run the report and adjust class costs from measured peaks.
## Report back
Tell the user, in their language: what you installed and where, how to see the queue status, how to read the report, how to turn it off, and which Verify steps passed or weren't run.

