Sub topic 6
Limiting CPU, memory, and process count
A hardened container stops an agent from touching the wrong files. It does not stop the agent from using all of the machine's resources. A test suite that leaks memory, a build that spawns thousands of workers, or a command like while true; do :; done can make the host unusable without breaking any isolation rule. This chapter covers the three limits that matter most for agent sandboxes: memory, CPU, and process count. It also covers the timeout that bounds the whole run.
This chapter assumes you know basic Docker usage, have read the earlier chapters on container primitives and hardening, and understand that a cgroup is a kernel feature that groups processes and caps their resource use.
Why resource limits belong in a sandbox
Agents do not need to be malicious to cause resource problems. Typical causes are:
- Generated code with an infinite loop or unbounded recursion.
- A build or test command that starts one worker per file.
- A fork bomb, which is a process that keeps creating copies of itself until the system cannot create more processes.
- A command that reads a huge file or log into memory.
- A prompt-injected instruction that tries to deny service on purpose.
Without limits, these problems affect the host and every other container on it. With limits, the damage stays inside the sandbox and the agent sees an error it can report.
How Docker applies the limits
Docker translates its flags into cgroup settings. On a host using cgroup v2, each container gets a directory of control files. The three that matter here are memory.max, cpu.max, and pids.max.
| Flag | cgroup v2 file | What happens at the limit |
|---|---|---|
| `--memory 2g` | `memory.max` | The kernel reclaims memory, then the OOM killer terminates a process |
| `--cpus 2` | `cpu.max` | Processes are throttled and slowed, not killed |
| `--pids-limit 256` | `pids.max` | `fork` and thread creation fail with an error |
The three resources fail in different ways, and that affects how you should handle each one.
Memory limits
The --memory flag sets a hard ceiling. When the container's processes need more, the kernel first tries to reclaim memory, such as clean page cache. If that is not enough, the OOM killer terminates a process in the container.
Try it with a command that allocates 2 GiB under a 512 MiB limit:
docker run --rm --memory 512m --memory-swap 512m \
python:3.12-slim \
python -c "x = b'x' * (2 * 1024**3)"
echo "exit code: $?"The exit code is normally 137, which is 128 plus signal 9 (SIGKILL). This only happens when the killed process is the container's main process. If the OOM killer picks a child process, the container keeps running and only that child dies. Do not rely on the exit code alone to detect OOM events. After a run, check docker inspect --format '{{.State.OOMKilled}}' <container>. The check only works if you did not use --rm, because --rm deletes the container on exit. For automated runs, omit --rm, read the state, then remove the container yourself.
Swap
By default, Docker lets a container use swap equal to the memory limit when the host has swap enabled. A 2 GB limit can then mean 4 GB of total use, and heavy swapping slows the whole host. Setting --memory-swap equal to --memory disables swap for the container. Do this for agent sandboxes so the limit means what it says.
What counts against the limit
- Anonymous memory from the processes, such as heaps and stacks.
- Page cache from files the container reads or writes. This is reclaimable, so it rarely causes kills on its own.
- Files in tmpfs mounts. This is the most common surprise.
A --tmpfs /tmp mount with no size cap can grow to half of the host's RAM by default. Its pages are charged to the container's memory limit, so the OOM killer eventually stops it. Even so, give each tmpfs a size so one scratch directory cannot use the container's entire memory budget:
--tmpfs /tmp:rw,noexec,nosuid,size=256mCPU limits
The --cpus flag uses CFS bandwidth control. With --cpus 2, Docker sets cpu.max to 200000 100000: the container may use 200 ms of CPU time in each 100 ms period, which is two cores' worth. A process that exceeds this is paused until the next period. It is slowed down, not killed.
This has two effects on agent runs:
- A CPU-bound loop will not take down the host, but it will keep running at full allowed speed. Only a wall-clock timeout stops it.
- Short bursts can show up as latency. Tools that measure time (test frameworks with timeouts, for example) may report failures that come from throttling, not from bugs.
You can check throttling by reading cpu.stat inside the container, usually at /sys/fs/cgroup/cpu.stat. Look at nr_throttled and throttled_usec.
Two related options exist, with different meaning:
--cpu-sharessets a relative weight. It only matters when containers compete for CPU. On an idle host, a container with low shares can still use every core. It is not a limit.--cpuset-cpus 0,1pins the container to specific cores. This is useful on shared build machines.
For a sandbox, use --cpus as the limit. Add --cpuset-cpus only when you want to reserve cores for other work.
Process limits
The --pids-limit flag caps the number of tasks in the container, and threads count as tasks. When the cgroup reaches the cap, any attempt to create another task fails. The failure shows up as an error from the program, such as fork: retry: Resource temporarily unavailable in bash.
You can see it work:
docker run --rm --pids-limit 20 python:3.12-slim \
bash -c 'for i in $(seq 1 50); do sleep 5 & done; wait'Bash prints fork errors after about 20 background jobs and the rest never start. A fork bomb hits the same wall and stops at the limit instead of exhausting the host's process table.
Choose the number from real workloads. A Python test run with a few workers needs dozens of tasks. A Node.js build or a Java build may use hundreds of threads. If the limit is too low, commands fail in confusing ways, so measure one normal run first. The examples in this tutorial use 128 and 256 as starting points.
Other limits worth setting
Memory, CPU, and PIDs cover the most common problems. Two more are cheap to add:
--ulimit nofile=1024:1024caps open file descriptors, which prevents descriptor exhaustion.--ulimit fsize=1073741824caps the size of any single file a process can write, here 1 GiB.
Disk space is harder. A writable bind mount, like /workspace, writes to the host's real filesystem. Neither memory nor PID limits apply to it, and a runaway command can fill the host disk. Options include putting the project on its own filesystem or quota-enabled volume, or checking free space before each run. Docker's --storage-opt size= only works with some storage drivers, so do not assume it is available.
Putting it together with a timeout
Resource limits bound how much the agent uses. A timeout bounds how long it runs. You need both, because CPU throttling does not stop a loop.
The wrapper from the topic's earlier chapter uses subprocess.run(..., timeout=...). There is a gotcha: when the timeout fires, Python kills the docker client process, not the container. The container can keep running on the daemon. To make the timeout effective, give the container a name and kill it explicitly:
import subprocess
import uuid
from pathlib import Path
def run_limited(project_dir: str, command: list[str], timeout: int = 60):
project = Path(project_dir).resolve()
name = f"agent-{uuid.uuid4().hex[:12]}"
docker_cmd = [
"docker", "run", "--rm", "--name", name,
"--user", "1000:1000",
"--read-only",
"--tmpfs", "/tmp:rw,noexec,nosuid,size=256m",
"--cap-drop=ALL",
"--security-opt", "no-new-privileges",
"--memory", "1g", "--memory-swap", "1g",
"--cpus", "1",
"--pids-limit", "128",
"--ulimit", "nofile=1024:1024",
"--network", "none",
"-v", f"{project}:/workspace",
"-w", "/workspace",
"python:3.12-slim",
*command,
]
try:
return subprocess.run(docker_cmd, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
subprocess.run(["docker", "kill", name], capture_output=True)
raise
if __name__ == "__main__":
result = run_limited(".", ["python", "-c", "print('limited run')"])
print(result.stdout)The Compose equivalents are mem_limit, memswap_limit, cpus, and pids_limit on the service.
Limits in stronger isolation
The same ideas apply with gVisor, since it runs under Docker and honors the same flags. For a VM or microVM, you set the limits when you create the machine: the number of virtual CPUs and the amount of RAM. The guest cannot exceed them. Inside the guest, the agent can still exhaust the guest's own memory, so limits on the VM protect the host but not the sandbox's own health.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Exit code 137 with no output | OOM kill or timeout kill | Check `OOMKilled` and your timeout path |
| `Resource temporarily unavailable` | PID limit too low | Raise `--pids-limit` after measuring |
| Tests time out only in the sandbox | CPU throttling | Raise `--cpus` or loosen test timeouts |
| Limit seems ignored | Swap allowed, or a cgroup v1 host | Set `--memory-swap`, check the cgroup version |
| Host disk fills up | Writable bind mount | Use quotas or a size-limited volume |
Exercise
A coding agent's container runs with --memory 1g and --tmpfs /tmp (no size option). The agent writes a 3 GB file to /tmp, and a process in the container is killed. Explain why this happens, and name two changes that make the behavior safer.
Show answer
Files in tmpfs are stored in RAM, and those pages are charged to the container's memory cgroup. The 3 GB write exceeds the 1 GiB memory.max limit, so the kernel cannot reclaim enough and the OOM killer terminates a process. Safer changes: give the tmpfs a size cap such as --tmpfs /tmp:rw,noexec,nosuid,size=256m, so the write fails with "No space left on device" instead of triggering an OOM kill; and set --memory-swap equal to --memory so the limit cannot be stretched by swap. Checking docker inspect for OOMKilled (without --rm) confirms the cause.