John Young

Production Operations

A Sandbox for AI Coding Agents at Scale Is a Warm-State Problem

Abstract
  1. At 20 to 100 parallel coding-agent sessions, the expensive part of a sandbox is the setup between boot and first useful action, not the boot, so the choice is about who pays that setup cost, how many times, and on whose critical path.
  2. Match isolation to trust: a worktree isolates files only and fits trusted sessions on one machine, while unattended or untrusted-input sessions need a per-session kernel, audited for engine pin, default runtime, and egress default.
  3. Build the warm state once and fork it, but re-mint every session-unique identity after restore, because a cloned snapshot duplicates IDs, nonces, and entropy.
  4. Share dependency caches read-only with a private writable layer per session, and keep credentials in a proxy outside the sandbox with egress denied by default, since an allowlisted domain is a capability grant.
  5. Price per session-hour at your real concurrency: three of the four hosted rates land within a few dollars of each other, so the provider’s concurrency ceiling decides the run.
The plain-language edition for readers outside AI engineering no background needed · 9 min

When you let many AI coding helpers work at the same time, each one needs its own safe workspace, and the hard part is not starting that workspace.

The big idea

Picture 50 cooks who all need to make a dish from the same recipe. Turning on a stove takes a second. But each cook also has to shop, unpack, chop and preheat before cooking anything useful. If every cook does all of that alone, you pay for it 50 times. The better plan is to prep one kitchen, copy it 50 times, and give each copy its own lock and its own key.

That is the post’s point. A “sandbox” is a sealed workspace where an AI helper can run code without touching anything it shouldn’t. Starting one is fast. Getting it ready to do real work is slow, and how you pick a sandbox decides whether you pay that getting-ready cost once or fifty times. The same choice also decides how safe the whole setup is.

The author works through one example he made up for illustration, not a real incident. A team wants to upgrade one software ingredient across 50 parts of a big project, so it starts 50 AI helpers at once. Each helper needs the project copied in, its pieces installed, and a first build run. Each also needs a key to save its work and a way to reach the shared parts library.

Measure the getting-ready time, not the startup time

Starting one of these sealed workspaces can take about an eighth of a second. One company that measured its own project found that of a 6-minute build, 3.5 minutes went to getting the worker ready. If every helper in the example lost 3.5 minutes that way, the 50 helpers would burn 175 minutes before writing a single line of the upgrade. The 3.5 minutes belongs to that company’s project. Yours will differ, which is why the post says to time it yourself.

One real case shows the payoff of waiting. Anthropic’s early design set up a full workspace for every session before it did anything. After they stopped building one until a session actually asked for it, the typical wait for a first response dropped by roughly 60%.

A separate folder is not a separate room

The cheapest way to give each helper its own copy of the project is a separate folder for each one. But a separate folder only separates the files the helper edits. Everything else on the machine is still shared: the network door numbers, the test database, the memory, the core of the operating system.

So 50 helpers on one laptop will soon collide. They all want the same door number for their test server, and one helper’s cleanup wipes the data another is checking. The author’s view is that separate folders are fine only when you trust the helpers and they all run on one machine. For anything unattended or untrusted, a folder gives no security protection at all.

If you do use shared setups, prepare the environment once each time your ingredients change, rather than rebuilding it every time a helper starts. Even then, it still shares the machine’s core, so it stays in the “trusted” category.

For untrusted work, give each helper its own core

Suppose the helpers run overnight with nobody watching, and they read code written by strangers. Then sharing the machine’s core with them is not good enough. Amazon states plainly that it does not treat ordinary containers as a security wall between customers.

One research team planted weaknesses in container setups and found that advanced AI models could find and use them. The post is careful about what this shows. It shows what a capable AI does with a badly configured setup. It does not show that standard containers fall apart on their own.

The safer options give each helper its own private core, either as a tiny virtual computer or through a lookalike core that sits between the helper and the real one. The post also notes that a virtual computer is not automatically more secure than the lookalike approach. It then gives five questions to ask any product:

  • Does each session get its own core?
  • Which version of the underlying engine does it run, and how far behind the latest fixes is it? One study found some products lagged anywhere from no time at all to well over a year.
  • What happens when nobody says which kind of isolation to use? In one system, the answer was no protection.
  • What can it send out to the internet by default? Even a strong wall around the helper does not stop it from uploading something.
  • How much slower is it on your real work? The lookalike core can be up to 10 to 200 times slower on tasks that open and close lots of files, which installing parts does constantly. The post warns that most published slowdown numbers are out of date, so run your own test and compare.

Prepare one kitchen, copy it, then re-number every copy

Instead of preparing each workspace separately, get one fully ready, take a snapshot of it (like a photo of the exact state), and start all 50 helpers from that snapshot. Then the preparation cost stays the same whether you run 5 helpers or 500. In the one real case cited, the company’s typical test run dropped to 30 seconds.

The catch is that copying also copies things that were supposed to be one of a kind. Think of photocopying a form that already has a ticket number on it. All 50 copies now claim the same number. For computers, that means IDs, random numbers and security codes. The people who build these tools say that resuming from the same snapshot more than once is unsafe unless something makes each copy generate fresh versions. So the rule is to create anything unique after each copy starts, not before the snapshot is taken. Each copy also gets its own branch name so the 50 helpers never save onto the same one.

Also expect a slow start. The copy’s first real task has to load pieces it hasn’t touched yet, and in one study a started-from-snapshot function ran 95% longer than normal on average. Time the first few minutes after the restore, not only the restore itself.

Share the parts shelf, but let nobody write to it

Fifty helpers downloading the same parts pay for the same files 50 times. A shared shelf fixes that. But the shelf must be read-only for the helpers. If all 50 can write to it, one helper that picks up a bad part can slip something harmful onto the shelf that the other 49 will use.

The safe version is a shelf stocked by a trusted job, which each helper reads but can’t change, plus a private notebook for each helper’s own additions. This is the author’s judgment: he is applying a space-saving trick measured elsewhere to coding helpers. The danger of a poisoned shared shelf, though, is well documented in ordinary software building.

Keep the keys and the door outside the room

In a story from Anthropic, a sandbox worked perfectly and the data still got out. The helper was allowed to contact one approved website, and that website could accept uploads to anyone’s account. So a list of allowed sites is not just a filter. Each entry is a power you handed over.

The fix is to keep the real keys outside the sandbox, with a trusted middleman who adds them to outgoing requests. Block outside contact by default. In the example, the one real key to save work lives with the middleman, and each helper holds only a ticket that works for its own branch.

Even then, a hostile instruction hidden in a downloaded part could tell a helper to send out the project. The blocked sites are safe, but the parts library has to be allowed so installs work, and that is a hole to watch.

Tighter rules also cost something. A study found that hardening always costs AI coders either success or money, in different amounts for different tools. So set each helper’s time and spending budget under the rules you really enforce. A helper that hits a blocked door tends to build a workaround, and the workaround eats the budget.

Price it at your real number of helpers

Price one helper for one hour, then scale to how many you really run. In the example, 50 helpers for 8 hours came to somewhere around $66 to $95 across four providers, which is the author’s own arithmetic from their published rates and leaves out some fees. The dollars are small and similar. What decides the outcome is each provider’s cap on how many helpers can run at once. On one entry-level plan, only five of the 50 would run while the other 45 waited.

Idle time matters too. A helper waiting on a person or a model should stop costing money while it waits. An all-night batch is busy almost the whole time, so price it by hours of active work.

A fixed order of questions

The author suggests walking through the questions in a set order. This order is his own synthesis; no source prescribes it. In short: time the getting-ready cost, then ask whether the helpers are trusted and on one machine. If yes, use separate folders and stop. If not, add a private core, then a snapshot, then a read-only shared shelf, then keys outside, then price it. Only the first yes ends the walk early; every other yes adds another protection.

What this means for you

If you are planning to run many AI coding helpers at once, do not judge a sandbox by how fast it starts. Ask how much work each helper must do before it can begin, and whether that work can be done once and copied. Match the wall to the trust: separate folders only for trusted work on one machine, a private core for anything unattended or untrusted. When you copy a prepared setup, give every copy fresh locks. Keep real keys and internet access outside the room. Check the provider’s limit on simultaneous helpers before you look at the hourly price.


The technical terms, in plain words

  • Sandbox = a sealed workspace where a program can run without touching anything outside it
  • Coding agent or session = one AI helper working on a coding task
  • Fan-out = starting many helpers at once on pieces of the same job
  • Boot = starting up the sealed workspace
  • Setup cost = the work between starting and the first useful action (copying the project, installing parts, a first build)
  • Git worktree = a separate folder holding its own copy of the project’s files
  • Shared kernel = all the programs on a machine sharing the same operating-system core
  • Container = a lightweight sealed box that still shares the machine’s core
  • MicroVM = a tiny virtual computer with its own core
  • Firecracker = a tool that starts such tiny virtual computers very fast
  • gVisor = a lookalike core that sits between the helper and the real one
  • Snapshot = a saved photo of a fully prepared workspace
  • Fork or clone = starting a new workspace as a copy of a snapshot
  • Re-mint = generate fresh unique values for a copy
  • Cache = a shared shelf of already-downloaded parts
  • Cache poisoning = slipping a bad item onto that shelf so others use it
  • Egress = data going out from the sandbox to the internet
  • Allowlist = the approved list of outside sites a helper may contact
  • Proxy = a middleman outside the sandbox that holds keys and adds them to outgoing requests
  • Credentials or token = a key that proves who you are
  • Concurrency = how many things run at the same time

Keep reading: the full version, with the research and sources ↓

The expensive part of a sandbox is rarely the boot. It is everything a session does between boot and its first useful action. At 20 to 100 parallel coding-agent sessions, your sandbox choice either multiplies that setup cost or hides it.

Anthropic’s first Managed Agents design made every session pay full container setup before it could produce a single token. After they stopped provisioning a container until a session asked for one, p50 time-to-first-token dropped roughly 60% and p95 dropped over 90% (Anthropic: Scaling Managed Agents1).

Every section below works one example: the dep-upgrade fan-out. It is my own constructed scenario, not a cited incident. A team upgrades a dependency across 50 packages in one monorepo by launching 50 coding-agent sessions at once. Each session needs the repo cloned, dependencies installed, a warm build, a GitHub token to push its branch, and access to the package registry.


Time Setup, Not Boot, Before Picking a Substrate

Before you compare substrates, time what each session spends between accepting work and its first useful action. Then defer provisioning until a session needs a sandbox at all.

Boot is already fast. Firecracker’s specification puts InstanceStart to the guest’s /sbin/init at <= 125 ms on a minimal kernel and root filesystem (Firecracker: Specification2).

Two production teams attacked start-up cost from different directions:

  • AWS Lambda pre-boots. It keeps a pool of pre-booted microVMs because a 125 ms boot is “not fast enough for the scale-up path of Lambda” (Agache et al.: Firecracker, NSDI ‘203).
  • BuildBuddy measured the worker. A fully cached Bazel build of its repo took about 6 minutes on GitHub Actions. Of that, 3.5 minutes went to initializing the worker: installing tools, checking out the repo, and building Bazel’s analysis graph (BuildBuddy: Snapshot, Chunk, Clone4).

Now size dep-upgrade with BuildBuddy’s number. At 3.5 minutes of clone, install, and warm build each, the 50 sessions burn 175 session-minutes before any of them writes a line of the diff. Boot is a rounding error inside that. (The 3.5 minutes is BuildBuddy’s figure for its own repo. Yours will differ, which is why you time it.)

Time the setup, not the boot
# Run once inside a fresh sandbox on each candidate substrate.
time git clone --depth 1 https://github.com/acme/mono.git /workspace   # clone
cd /workspace
time pnpm install --frozen-lockfile                                     # dependencies
time pnpm --filter "./packages/**" build                                # warm build

Sum the three real lines and multiply by your session count. A substrate that boots in 100 ms and then runs all three steps cold has not beaten that number. It has only moved it.

The sandbox question is therefore: who pays the setup cost, how many times, and on whose critical path?


Know What a Worktree Actually Isolates

Author’s judgment. “Worktrees for trusted sessions on one machine only” is my inference. It follows from git’s documented sharing model, Claude Code’s description of which isolation rungs run on the host, and Conductor’s documented collisions between parallel workspaces.

A git worktree isolates the files an agent edits, and little else. Use it only for trusted sessions on one machine.

Git’s documentation says a new worktree shares “everything except per-worktree files such as HEAD, index, etc.”, including refs and the repository config (git-scm: git-worktree5). Below git, sessions on one host also share ports, databases, caches, and the kernel. Claude Code’s own comparison notes that the lightest rungs “run on the host operating system without containers” (Claude Code Docs: Choose a sandbox environment6).

Worktrees are still the cheapest way to give each task its own checkout across agents (Switching Between AI Coding Agents). The failure is mistaking file isolation for session isolation.

Run the dep-upgrade fan-out as 50 worktrees on one laptop, and the collisions arrive early. Every session that starts the dev server wants port 3000. Every integration suite points at the same acme_test database, so one session’s fixture teardown truncates the table another is asserting against.

Conductor gives each parallel agent workspace its own worktree. When an action fails, it lists both causes: “The app uses a fixed port that is already in use.” and “Multiple workspaces are trying to use the same database, cache, or external service.” (Conductor: Troubleshooting issues7).

When you seeIt meansDo this
EADDRINUSE :3000 from a session’s dev serverPorts are host-global; the worktree never isolated themGive each session its own port range (Conductor’s fix is $CONDUCTOR_PORT)
Two sessions failing on the same acme_test rowsThe database is shared stateGive each session its own database or schema, or leave the rung for that resource
Sessions swapping or getting OOM-killedYou hit the single-host memory ceilingBudget per-session process trees before adding sessions (memory budget)
The session will run unattended or read untrusted inputA worktree has no security boundary at allLeave the rung entirely for a per-session kernel
Every session rebuilds its devcontainer on startYou are paying image build cost per sessionPrebuild the image once per dependency change

Prebuild the Image, Not the Session

Pay the image build once per dependency change, not once per session. That is what makes a devcontainer a repeatable environment at fan-out instead of a build tax on every start.

The Dev Container guidance says the same: “You need to build your container once it has all the dependencies it needs, and rebuild anytime you add new dependencies” (containers.dev: Prebuilds8).

For dep-upgrade, that is one devcontainer build --workspace-folder . --push true --image-name ghcr.io/acme/mono-dev:base against the pre-upgrade lockfile, then 50 pulls.

One limit: a devcontainer still shares the host kernel. This stays the trusted rung.


Put a Kernel Boundary Under Untrusted Fan-Out

A shared-kernel container stops being an acceptable floor the moment the dep-upgrade sessions run unattended overnight and read third-party package code.

AWS’s runc bulletin is blunt: “AWS does not consider containers a security boundary, and does not utilize containers to isolate customers from each other.” (AWS: Security Bulletin AWS-2025-0249).

UK AI Security Institute and Oxford researchers built SandboxEscapeBench and found that frontier models identify and exploit vulnerabilities planted in a container setup. Its authors cite NCSC guidance that “hypervisor isolation should be used as a bare minimum” (Marchand et al.: Container Sandbox Escape10). Read the result narrowly: it shows what a capable agent does with a misconfiguration, not that default containers fall.

Per-session kernels are now ordinary infrastructure.

Kata Containers runs pods as “lightweight virtual machines (VM’s) that feel and perform like standard Linux containers,” selected per pod by RuntimeClass (Kata Containers: Architecture11). The Kubernetes docs’ Kata-on-Firecracker example “uses around 120MiB per Pod for the virtual machine and the guest OS” (Kubernetes Docs: Pod Overhead12).

On a laptop, Docker Sandboxes runs each agent session “inside a dedicated microVM with a private Docker daemon” on a VMM Docker built itself (Docker: Why MicroVMs13). Each session gets “its own Linux kernel” (Docker Docs: Isolation layers14).

gVisor is the userspace-kernel option.

The class separates cleanly on architecture. But you run a product, not a class.

Andronchik and Lokhmakov compared five AI sandbox products and found pin policy is the dominant operator-facing variable (Andronchik & Lokhmakov: AI Code Sandboxes15). Engine-side patch latency for coordinated disclosures aggregated to about 0 days. Downstream products lagged anywhere from 0 to 471+ days, stayed opaque, or never patched one non-default path. The strong-isolation microVM product in their set was the one frozen on an old Cloud Hypervisor pin.

Put these five questions to any sandbox product before the overnight run:

  1. Does each session get its own kernel? Process sandboxes and containers share the host kernel. For kernel-level isolation, Claude Code’s guide says to “use gVisor or a separate VM,” and warns that VMs “aren’t automatically ‘more secure’ than alternatives like gVisor” (Claude Code Docs: Securely deploying AI agents16). Firecracker and gVisor both allow far fewer host syscalls than containers (Anjali et al.: Firecracker and gVisor, VEE ‘2017). gVisor still “relies on the host operating system and the platform for defense against hardware-based attacks” (gVisor: Security Model18).
  2. Which engine version is pinned, and how far behind upstream? Get the bump policy in writing.
  3. What runs when nobody names a runtime? As METR’s Hawk docs put it, “Kubernetes has no “default RuntimeClass” concept.” Task-authored pods that name no runtime run under runc “with no kernel boundary” unless the operator fills in a default (METR Hawk: Sandbox Network Isolation19). Check every rendered pod for runtimeClassName: kata-fc or your handler.
  4. What is the egress default? Firecracker does no traffic filtering. Guest egress “should be filtered at the host-level” (Firecracker: Design20). The boundary that stops an escape does not stop an upload.
  5. What does it cost on your build and test loop? Claude Code’s guide puts gVisor at about 0% overhead for CPU-bound work. File I/O is another story: “Up to 10-200× slower for heavy open/close patterns” (Claude Code Docs: Securely deploying AI agents16). A pnpm install is exactly that pattern.

Those five answers bound the blast radius. The next two sections make it affordable.

Measure gVisor on Its Current Platform

Most gVisor overhead figures in circulation are stale. They predate the features that changed its file-I/O cost, so don’t cite them as today’s price.

  • Check the platform behind any gVisor benchmark. gVisor’s own performance guide benchmarks on ptrace, the platform it says has the highest structural costs, and recommends Systrap (gVisor: Performance Guide21).
  • Check the filesystem features behind any file-heavy build number. Rootfs overlay “halved the sandboxing overhead for abseil build” and is now the runsc default (gVisor: Rootfs Overlay22). Directfs is also default; measured on Systrap, it cut workload time 12% and Ruby load time 17% (gVisor: Directfs23).
  • Run your own loop instead of trusting anyone else’s number. Time pnpm install --frozen-lockfile && pnpm test under docker run --runtime=runsc and under the default runtime, on the same host. That ratio is the only gVisor cost that belongs in the decision.

Fork Warm Snapshots and Re-Mint Every Clone

Build the dep-upgrade warm state once: repo cloned, dependencies installed, build graph primed. Snapshot it. Fork all 50 sessions from it. Then assume every clone is wrong about its own identity until it regenerates what the snapshot assumed was unique.

The payoff is a change in complexity class. Marc Brooker on Lambda SnapStart: “The work of initialization is amortized over many sandboxes, rather than being done once for every sandbox,” which takes initialization from O(N) to O(1) (Brooker: Lambda Snapstart24). BuildBuddy’s snapshotted runners brought its median CI run to 30 seconds (BuildBuddy: Snapshot, Chunk, Clone4). DeltaBox’s authors make the same point for agent rollouts. Rebuilding warm state per rollout costs hundreds of milliseconds to seconds, so fork latency bounds training throughput (Dong et al.: DeltaBox25).

The cost: one snapshot becomes 50 copies of things meant to exist once. Brooker’s AWS team: “cloning duplicates memory state, which is a challenge for applications which want to generate unique data such as request IDs, UUIDs, and cryptographic nonces” (Brooker et al.: Restoring Uniqueness26). Modal warns that state built before a snapshot is reused on every restore, so “expectations of entropy may be violated” (Modal: Memory snapshots27). The Firecracker maintainers are blunter:

“When snapshots are used in a such a manner that a given guest’s state is resumed from more than once, guest information assumed to be unique may in fact not be; this information can include identifiers, random numbers and random number seeds, the guest OS entropy pool, as well as cryptographic tokens. Without a strong mechanism that enables users to guarantee that unique things stay unique across snapshot restores, we consider resuming execution from the same state more than once insecure.”

AWS Lambda MicroVMs launch every instance from one Firecracker snapshot, and they turn the warning into a rule: “Generate unique content after a new MicroVM starts, not during image build. Use the /run lifecycle hook to reset previously generated unique content.” (AWS: Working with snapshots29). Per-session values arrive in a run hook payload that “is unique to each MicroVM” (AWS: Running MicroVMs30).

The launch loop mints one random proxy token per session. It records each token in sessions.tsv for the egress proxy two sections down:

Launch 50 sessions from one warm image
# packages.txt: one package name per line (50 lines)
while read -r pkg; do
  tok=$(openssl rand -hex 32)
  printf '%s\t%s\n' "dep-upgrade-${pkg}" "$tok" >> sessions.tsv
  aws lambda-microvms run-microvm \
    --image-identifier "$WARM_IMAGE_ARN" \
    --run-hook-payload "{\"session\":\"dep-upgrade-${pkg}\",\"proxy_token\":\"${tok}\"}" \
    --idle-policy '{"autoResumeEnabled":true,"maxIdleDurationSeconds":900,"suspendedDurationSeconds":1800}' \
    --maximum-duration-in-seconds 28800
done < packages.txt

Inside the image, the hook server captured in the snapshot answers Lambda’s POST to /run. It re-mints everything session-unique before the session takes traffic:

/run hook: re-mint what the snapshot duplicated
import json, secrets, subprocess, uuid
from http.server import BaseHTTPRequestHandler, HTTPServer

RUN = "/aws/lambda-microvms/runtime/v1/run"

class Hooks(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != RUN:
            self.send_response(404); self.end_headers(); return
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        payload = json.loads(body["runHookPayload"])
        session = payload["session"]
        with open("/run/session.env", "w") as f:
            f.write(f"SESSION_ID={session}\n")
            f.write(f"MICROVM_ID={body['microvmId']}\n")
            f.write(f"RUN_UUID={uuid.uuid4()}\n")               # fresh, from os.urandom
            f.write(f"SESSION_NONCE={secrets.token_hex(32)}\n")
            f.write(f"PROXY_TOKEN={payload['proxy_token']}\n")  # delivered at run time, never baked in
        # One branch per clone, so 50 forks never push to the same ref.
        subprocess.run(["git", "-C", "/workspace", "switch", "-c", session], check=True)
        self.send_response(200); self.end_headers()

HTTPServer(("0.0.0.0", 9000), Hooks).serve_forever()

E2B’s fork endpoint, POST /sandboxes/{sandboxID}/fork, boots up to 100 forks from one snapshot of a live sandbox. It says nothing about uniqueness. It also carries a footgun: forks default to a 15-second time to live unless you set timeout (E2B: Fork sandbox31).

Budget for the Post-Restore Tail

Time the first minutes after restore, not the restore call.

Ustiugov et al. found that a function started from a Firecracker snapshot ran 95% longer on average than a memory-resident one. Its state arrived one page fault at a time. Prefetching the recorded working set cut cold-start delays 3.7x on average (Ustiugov et al.: Serverless Function Snapshots32).

The dep-upgrade fan-out hits the same tail. Each clone’s first pnpm test touches node_modules pages nobody has faulted in yet.

Lambda MicroVMs give you the lever: run the test suite in the /validate build hook. Lambda tracks the snapshot regions that work touches and optimizes their retrieval at startup (AWS: MicroVM images33).


Share the Cache Read-Only, Write Per Session

Author’s judgment. Applying Lambda’s chunk deduplication to coding-agent sessions is my extension of a mechanism measured on Lambda functions. The cache-poisoning half of this section is directly sourced.

Share the dependency cache, but never let a session write to the shared copy. Fifty sessions that each download the same dependency tree pay for the same bytes fifty times. One writable cache shared by all fifty is worse: it lets one session write what the other 49 execute.

Bad: One writable ~/.pnpm-store bind-mounted into all 50 dep-upgrade sessions. Say one session installs a compromised package with a malicious postinstall. It can rewrite store entries the other 49 import on their next install.

Good: A trusted job builds a content-addressed store from the base lockfile. Every session mounts it read-only, with its own private writable overlay on top. Packages a session adds land in its overlay. Nothing reaches the shared layer except through the next trusted build.

The density win is real at scale. Lambda splits images into deduplicated chunks behind tiered caches. Over a week in one region, “a median of 67% of chunks were loaded from the on-worker cache, 32% from the AZ-level distributed cache, and the remaining 0.06% from the backing store” (Brooker et al.: On-demand Container Loading34).

Coding-agent benchmarks use the same trick. SWE-bench layers base, environment, and instance images so common components are cached while each task runs isolated (SWE-bench: The Harness35). Epoch AI’s restructured layers fit all 500 Verified images in 30 GiB, because “shared layers are only stored once” (Epoch AI: SWE-bench in one hour36).

The shared layer also has to absorb a correlated spike. The Firecracker paper notes that “multiple workloads from the same application” behave as a single workload for oversubscription (Agache et al.: Firecracker, NSDI ‘203). Fifty sessions running pnpm install in the same minute are exactly that.

CI has already settled the security side. GitHub’s docs warn that “Poisoned caches can lead to code execution in trusted workflows.” So low-trust runs get read-only access to the default branch’s cache and should “treat restored files as untrusted input” (GitHub Docs: Dependency caching37). Adnan Khan’s rule: “Never run untrusted code within the context of the main branch if any other workflows use GitHub Actions caching.” (Adnan Khan: The Monsters in Your Build Cache38). A session reading third-party package code is untrusted code by that definition.


Keep Credentials and Egress Outside the Sandbox

A perfect sandbox can still leak your data. Anthropic’s containment write-up describes that failure:

“The sandbox worked perfectly, and yet the data was exfiltrated. Previously, we’d conceptualized the allowlist as a destination filter, something that told Claude these domains are okay to talk to. But it may be better conceptualized as a capability grant. Every function reachable through any domain on an allowlist is now an attack surface. Allowing api.anthropic.com meant allowing file uploads to arbitrary Anthropic accounts.”

So hold credentials outside the sandbox, in a proxy or vault that attaches them to outbound requests. Deny egress by default. Treat every allowlisted domain as a capability you granted.

The same post states the payoff: “if credentials never enter the sandbox, they can’t be exfiltrated.” Claude Code’s deployment guide calls a proxy outside the agent’s security boundary “the recommended approach” (Claude Code Docs: Securely deploying AI agents16). Production systems already ship it:

For dep-upgrade, the one GitHub token lives in the proxy. Each session holds only the PROXY_TOKEN its /run hook wrote. The proxy maps that token through sessions.tsv to pushes on the session’s own dep-upgrade-<pkg> branch.

Now one session reads a hostile README in an upgraded dependency. The README tells it to post the repo somewhere. Default-deny egress blocks the paste site. But registry.npmjs.org is allowlisted so installs work, and that is the gap. Hawk names what its Kata network modes still do not stop: “data sent to an allowed host, such as an upload to a package index.” The registry entry is the capability grant to watch. (Claude Code’s built-in Bash sandbox settings are covered in the harness audit.)

Then size each session’s time and token budget under the policy you actually enforce. Davidovich et al. found hardening always costs coding agents success or spend, though unevenly. Under the strictest policy, success fell up to 18.3 points for one model-harness bundle, and cost rose up to 167.3% for another. Their conclusion: “budgets must be provisioned under the deployment’s policy” (Davidovich et al.: Permission Denied42). A session that hits a denied mirror does not stop. It builds a workaround, and the workaround eats the budget.


Price the Fleet at Your Real Concurrency

Author’s judgment. The per-session-hour and per-run figures are my arithmetic from each provider’s published rates on 2026-11-23, excluding disk, plan fees, included allowances, transfer, and Cloudflare’s Workers and Durable Objects charges.

Before you choose hosted or self-hosted, price one session-hour at the concurrency you will actually run. Hosted sandboxes bill per vCPU-second and GiB-second. Then they cap how many sessions run at once.

Here is dep-upgrade at 2 vCPU and 4 GiB per session, 50 sessions for 8 hours:

ProviderPublished ratePer session-hour50 sessions × 8 hWhat binds at 50
E2B$0.000014/vCPU-s, $0.0000045/GiB-s~$0.166~$66Hobby caps at 10 concurrent; Pro ($150/month) allows 100
Daytona$0.0504/vCPU-h, $0.0162/GiB-h~$0.166~$66Tier 1 pools 10 vCPU total (5 sessions); Tier 2 pools 100 vCPU and 200 GiB
Cloudflare$0.000020/vCPU-s (active only), $0.0000025/GiB-sup to ~$0.18up to ~$72Account-wide pool, 15,000 vCPU by default
Modal$0.00003942/core-s (1 core = 2 vCPU), $0.00000667/GiB-s~$0.24~$95Starter allows 100 containers

Where the rates and caps come from:

The dollar column is small, and three of the four providers land within a few dollars of each other. The ceiling column decides the run. On Daytona’s Tier 1, the dep-upgrade fan-out gets five sessions, not fifty. The other 45 queue.

Idle time is the other variable. Interactive sessions spend most of their hours waiting on a model or a human. Per-second billing only helps if the sandbox stops billing while it waits.

AWS prices its own coding-assistant example on Lambda MicroVMs at $12.41 per developer-month (AWS: Lambda pricing50). The example assumes 100 developers, each active 2.5 hours of an 8-hour day, 20 days a month, with six suspend cycles daily. The lever is suspend: “MicroVMs can be suspended when idle, preserving memory and disk state while reducing costs” (AWS: Lambda MicroVMs51).

So price by workload. An unattended batch like dep-upgrade is mostly active: price it on active hours. Price an interactive fleet on its suspend behavior.


Route Your Fleet Through Six Questions

Author’s judgment. The order of these gates is my synthesis of the sections above; no source prescribes it.

Ask the questions in this order. Only the worktree rung ends the walk early. Every other yes adds a control and moves you to the next question.

flowchart TD
    A[Time setup per session] --> B{Setup dominates time to first action?}
    B -- yes --> B1[Defer provisioning until a session needs a sandbox]
    B -- no --> C
    B1 --> C{Trusted sessions on one machine?}
    C -- yes --> C1[Worktree per session plus a prebuilt devcontainer image. Stop.]
    C -- no --> D{Unattended or untrusted input?}
    D -- yes --> D1[Per-session kernel. Audit pin, default runtime, egress default]
    D -- no --> E
    D1 --> E{Setup still over budget at your session count?}
    E -- yes --> E1[Warm snapshot, fork, re-mint identity in the run hook]
    E -- no --> F
    E1 --> F{Sessions share dependencies?}
    F -- yes --> F1[Read-only shared layer plus private writable layer per session]
    F -- no --> G
    F1 --> G{Sessions need credentials or network?}
    G -- yes --> G1[Proxy outside the sandbox, egress denied by default]
    G -- no --> H
    G1 --> H[Price per session-hour at your real concurrency]

dep-upgrade hits every rung except the worktree one. It gets deferred provisioning and a per-session kernel with an audited pin. It gets one warm snapshot, with identity re-minted in /run. Its store is read-only, with a private overlay per session. Its GitHub token sits in a proxy behind default-deny egress. Priced at 50 concurrent sessions, the provider is picked by the concurrency ceiling, not the hourly rate.

I packaged this route and the pricing table as sandbox-substrate-picker52, a script that walks your fleet through the six questions and prices it per vendor plan at your real session count, flagging every plan whose cap binds.

Once each session has a place to run, the next question is what it may do there. That is a permission question, not a substrate question. The principle is the same: put the control in the environment, not in the prompt (Tier Your AI Agent’s Production Authority by Task Risk).

Sources

  1. Anthropic: Scaling Managed Agentsanthropic.com/engineering/managed-agents
  2. Firecracker: Specificationgithub.com/firecracker-microvm/firecracker/blob/main/SPECIFICATION.md
  3. Agache et al.: Firecracker, NSDI '20files.usenix.org/s3fs-public/cdn/nsdi20-paper-agache.pdf
  4. BuildBuddy: Snapshot, Chunk, Clonebuildbuddy.io/blog/fast-runners-at-scale
  5. git-scm: git-worktreegit-scm.com/docs/git-worktree
  6. Claude Code Docs: Choose a sandbox environmentcode.claude.com/docs/en/sandbox-environments
  7. Conductor: Troubleshooting issuesconductor.build/docs/troubleshooting/issues
  8. containers.dev: Prebuildscontainers.dev/guide/prebuild
  9. AWS: Security Bulletin AWS-2025-024aws.amazon.com/security/security-bulletins/rss/aws-2025-024
  10. Marchand et al.: Container Sandbox Escapearxiv.org/abs/2603.02277
  11. Kata Containers: Architecturegithub.com/kata-containers/kata-containers/blob/main/docs/design/architecture/README.md
  12. Kubernetes Docs: Pod Overheadkubernetes.io/docs/concepts/scheduling-eviction/pod-overhead
  13. Docker: Why MicroVMsdocker.com/blog/why-microvms-the-architecture-behind-docker-sandboxes
  14. Docker Docs: Isolation layersdocs.docker.com/ai/sandboxes/security/isolation
  15. Andronchik & Lokhmakov: AI Code Sandboxesarxiv.org/abs/2606.08433
  16. Claude Code Docs: Securely deploying AI agentscode.claude.com/docs/en/agent-sdk/secure-deployment
  17. Anjali et al.: Firecracker and gVisor, VEE '20pages.cs.wisc.edu/~swift/papers/vee20-isolation.pdf
  18. gVisor: Security Modelgvisor.dev/docs/architecture_guide/security
  19. METR Hawk: Sandbox Network Isolationhawk.metr.org/user-guide/sandbox-network-isolation
  20. Firecracker: Designgithub.com/firecracker-microvm/firecracker/blob/main/docs/design.md
  21. gVisor: Performance Guidegvisor.dev/docs/architecture_guide/performance
  22. gVisor: Rootfs Overlaygvisor.dev/blog/2023/05/08/rootfs-overlay
  23. gVisor: Directfsgvisor.dev/blog/2023/06/27/directfs
  24. Brooker: Lambda Snapstartbrooker.co.za/blog/2022/11/29/snapstart.html
  25. Dong et al.: DeltaBoxarxiv.org/abs/2605.22781
  26. Brooker et al.: Restoring Uniquenessarxiv.org/abs/2102.12892
  27. Modal: Memory snapshotsmodal.com/blog/mem-snapshots
  28. Firecracker: Snapshottinggithub.com/firecracker-microvm/firecracker/blob/main/docs/snapshotting/snapshot-support.md
  29. AWS: Working with snapshotsdocs.aws.amazon.com/lambda/latest/dg/microvms-images-snapshots.html
  30. AWS: Running MicroVMsdocs.aws.amazon.com/lambda/latest/dg/microvms-launching.html
  31. E2B: Fork sandboxdocs.e2b.dev/api-reference/sandboxes/fork-sandbox
  32. Ustiugov et al.: Serverless Function Snapshotsarxiv.org/abs/2101.09355
  33. AWS: MicroVM imagesdocs.aws.amazon.com/lambda/latest/dg/microvms-images.html
  34. Brooker et al.: On-demand Container Loadingarxiv.org/abs/2305.13162
  35. SWE-bench: The Harnessswebench.com/SWE-bench/reference/harness
  36. Epoch AI: SWE-bench in one hourepoch.ai/latest/swebench-docker
  37. GitHub Docs: Dependency cachingdocs.github.com/en/actions/concepts/workflows-and-actions/dependency-caching
  38. Adnan Khan: The Monsters in Your Build Cacheadnanthekhan.com/2024/05/06/the-monsters-in-your-build-cache-github-actions-cache-poisoning
  39. Anthropic: How we contain Claudeanthropic.com/engineering/how-we-contain-claude
  40. Cloudflare: Credential injection for Sandboxesdevelopers.cloudflare.com/changelog/post/2026-04-13-sandbox-outbound-workers-tls-auth
  41. Claude Code Docs: Use Claude Code in the cloudcode.claude.com/docs/en/claude-code-on-the-web
  42. Davidovich et al.: Permission Deniedarxiv.org/abs/2608.02670
  43. E2B: Pricinge2b.dev/pricing
  44. Daytona: Pricingdaytona.io/pricing
  45. Daytona: Limitsdaytona.io/docs/en/limits
  46. Cloudflare: Sandbox pricingdevelopers.cloudflare.com/sandbox/platform/pricing
  47. Cloudflare: Containers pricingdevelopers.cloudflare.com/containers/pricing
  48. Cloudflare: Containers limitsdevelopers.cloudflare.com/containers/platform-details/limits
  49. Modal: Pricingmodal.com/pricing
  50. AWS: Lambda pricingaws.amazon.com/lambda/pricing
  51. AWS: Lambda MicroVMsdocs.aws.amazon.com/lambda/latest/dg/lambda-microvms-guide.html
  52. agent-engineering-toolkit: sandbox-substrate-pickergithub.com/johnayoung/agent-engineering-toolkit