Coding with AI

This guide explains how to sandbox code executed by AI agents in Python using containers, micro virtual machines, and future alternatives.

This guide compares subprocess, Docker, and Firecracker sandboxes for AI agent Python code, measuring six attacks, latency costs, and trade-offs.

This guide explains how to sandbox code executed by AI agents in Python using containers, micro virtual machines, and future alternatives.

Key Takeaways

  • The article explains how to sandbox AI-agent-generated Python code behind a single `run_python` tool with interchangeable backends: subprocess, Docker, and Firecracker microVMs.
  • Subprocess sandboxing is the fastest tier, using resource limits, isolated temporary directories, dropped privileges, and private network namespaces, but still shares the host kernel and filesystem.
  • Docker containers provide stronger isolation through cgroups, namespaces, read-only filesystems, dropped capabilities, and explicit network limits, though they remain vulnerable to container escapes.
  • Firecracker/E2B microVMs offer the strongest boundary by giving each execution its own kernel behind a hypervisor, improving security at the cost of higher latency.
  • The guide tests six hostile programs and benchmarks latency to show how isolation strength affects both safety and performance.

Meta description: Compare subprocess, Docker, and Firecracker microVM sandboxes for AI agent code, testing six attacks and measuring latency costs for each isolation tier.

This guide explains how to sandbox code executed by AI agents in Python using containers, micro virtual machines, and fu

Tags: AI Agents, Code Sandboxing, Docker, Firecracker, Security

![Abstract friendly illustration of three sandbox tiers for AI agent code execution: a subprocess, a Docker container, and a Firecracker microVM.](sandbox-tiers.png)

This is for developers who build agents that write Python code and then execute it. It shows how to sandbox AI agent code behind one run_python tool, with three interchangeable backends: a limited subprocess, a hardened Docker container, and an E2B Firecracker microVM. The same six hostile programs test each tier, and a latency benchmark shows what stronger isolation costs.

One Tool and Three Backends

The agent exposes a single run_python tool. Every call passes through a sandbox object, so switching tiers does not require changing the agent loop. The tool description tells the model that run_python takes a string of code and returns stdout, stderr, and an exit code. The loop sends the conversation forward, and when the model requests the tool, the code goes to sandbox.run. The result returns as a tool_result, marked as an error whenever the exit code is not zero. The model's code never runs inside the main process. Any object with a run(code) method can serve as the sandbox.

To start, use Python 3.10 or newer. The subprocess tier relies on Linux resource limits and unshare, so run it on Linux or in WSL. Install the SDKs needed for the agent loop and for E2B microVMs. Pull the Docker container image before the first run so the first test does not include the download. Store the E2B account and API key, plus the Anthropic API key, in the environment; the agent loop can be skipped if you want to go straight to the tests. Put four files in one folder: sandbox.py, agent.py, attacks.py, and bench.py. Define Result as the shared return type, trim output, and use SAFE_ENV to omit API keys and the home directory.

This guide explains how to sandbox code executed by AI agents in Python using containers, micro virtual machines, and fu

Untrusted code can consume resources, read secrets, call internal services, or escape its boundary. The three tiers differ by where that boundary sits. A subprocess is the lightest option: a child process with limits on CPU, memory, and file size, but it still shares the host kernel and files. A container adds namespaces and cgroups, yet it remains a set of processes on the host kernel. Docker documentation warns that containers have no resource limits unless you set them. Escapes happen: in November 2025, three runc vulnerabilities let attackers break out of containers. A microVM gives each sandbox its own kernel behind a hypervisor. Docker frames this as a hardware boundary, and AWS describes its Firecracker-based Lambda MicroVMs as having no shared kernel across sessions. Infrastructure, not the model, should define file access, network policy, and secrets before the agent starts.

Limited Subprocess Is the Fastest Boundary

In the subprocess backend, _apply_limits runs inside the child before the code starts. It caps CPU time, memory as address space, and the size of any file the code writes. If the sandbox runs as root, it first drops to the unprivileged nobody user, clears root's supplementary groups, and adds a process limit. That limit counts all processes belonging to a user, so it only makes sense for a dedicated user. On a normal laptop, the process cap is skipped.

The run method creates a fresh temporary folder and executes python -I in isolated mode inside that folder. The command is wrapped in unshare --net, which gives the child a private network with nothing in it. The constructor checks that unshare works and raises an error if it does not, so the sandbox never silently falls back to an open network. Output is written to files, which means the file-size limit also blocks print floods. A timeout kills the whole process group, and the temporary folder is deleted afterward. This tier does not hide your files: the code runs as you, on your filesystem.

Docker and MicroVMs Add Isolation

The Docker backend builds a docker run command where each flag closes one door. --network none removes network access. --read-only makes the root filesystem unwritable, while a small 16 MB /tmp provides scratch space. --cap-drop ALL and no-new-privileges remove special privileges, and --user avoids running as root. Resource flags follow Docker's documented controls: --memory plus an equal --memory-swap stops the container from using swap, and --cpus and --pids-limit cap CPU and process count. The program arrives on stdin, so no host folder is mounted. On a timeout, docker kill stops the container, because killing the Docker client alone would leave the container running.

The E2B backend wraps Firecracker microVMs. E2BSandbox creates a new sandbox for every run, so nothing carries over between executions. The with block destroys the VM when the run ends. run_code returns logs and an error object, per the E2B SDK reference, and those values are copied into the same Result type. If code exceeds its timeout, the SDK raises an exception, which the backend converts into timed_out. A get_backend helper picks the tier by name.

For context, Docker launched Docker Sandboxes on microVMs in April 2026, and AWS offers Lambda MicroVMs, which keep state for up to 8 hours and suspend when idle. The author's expectation, stated as opinion rather than forecast, is that microVMs may become the default boundary for agent code, with policy set by infrastructure rather than by the model.

This guide explains how to sandbox code executed by AI agents in Python using containers, micro virtual machines, and fu

Test and Compare the Three Tiers

The attack script plants a fake credentials file and starts a listener on the host's loopback interface as a stand-in for an internal service. Each attack is a program plus a marker word that appears in the output only if the attack succeeds. The six attacks are an infinite loop, a 512 MB memory grab, a bounded fork flood of 200 processes, a 50 MB file write, a read of the fake secret, and a connection to the local service. The fork flood is capped so it cannot harm the machine. A blocked attack means the marker word never appeared, or, for the infinite loop, that the run timed out.

When the subprocess tier runs as a normal Linux user, four attacks are blocked and two get through. The fork flood is allowed because the process cap only applies to a dedicated user. The secret file is readable because the code runs as you. Both are real limits of this tier, and they are why it suits only code you mostly trust.

Run --backend docker and --backend e2b next. With the flags described above, Docker should block all six attacks: the container has no network, its filesystem does not contain your files, and memory, process, and disk limits apply. In a microVM, memory, process, and disk attacks may run to the limits of the VM you chose, but they stay inside it. The fake secret file and the local service do not exist there.

Safety costs time, so measure it. The bench script runs print(1) ten times on a backend after one warm-up run, then prints the median and slowest times. For E2B, each run creates a microVM, so the measured time includes startup. Expect the subprocess to be fastest, because it only starts Python. Treat published boot times as claims, not guarantees: one write-up reports that E2B boots in about 150 ms, and both AWS and Docker describe near-instant launches for their microVM products.

Use a limited subprocess only for code you trust, such as your own scripts in development. Use a hardened container when you control the host and the stakes are low, and keep runc patched. Use a microVM for code from many users, for anything that touches secrets, and when the agent needs more than Python. Docker notes that agents often need to build and run containers themselves, a job plain containers handle poorly.

Common Mistakes

  1. Letting the model choose file access, network policy, or secrets. Infrastructure should define those boundaries before the agent starts.
  2. Treating subprocess isolation as enough for untrusted code. It shares your files and kernel, and the test lets the fork flood and secret read through when run as a normal Linux user.
  3. Forgetting Docker resource limits. Without --memory, --memory-swap, --cpus, --pids-limit, --network none, --read-only, --cap-drop ALL, no-new-privileges, and --user, the container can behave like a set of host processes.
  4. Killing only the Docker client after a timeout. Stop the container with docker kill.
  5. Reading latency numbers as guarantees. The 150 ms E2B figure and near-instant AWS or Docker claims are published reports, not guarantees; run bench.py on your machine.

Comments (0)

  1. No comments yet. Be the first to share what worked for you.

Leave a comment

Comments are reviewed before they appear. Your email address is not published.