Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Sandbox Execution Environment: Architecture, Lifecycle, Sessions and Security

How Cloudflare Sandboxes run untrusted code in isolated containers—from Workers architecture to exec, files, sessions, and security boundaries.

This page summarises Cloudflare documentation on running untrusted or generated code in sandboxes: isolated Linux environments you control from a Worker. The platform spans Sandbox SDK 0.x (@cloudflare/sandbox on Containers) and the newer 1.0 model where helper classes run inside a Durable Object container you start yourself. Most examples below describe 0.x, which remains the bulk of the published guides; new projects should follow Sandboxes on Cloudflare and Migrate from Sandbox SDK 0.x when moving forward.

Sandbox architecture: Workers, Durable Objects and Containers

Section titled “Sandbox architecture: Workers, Durable Objects and Containers”

A sandbox is an isolated place to run code that must not share a process with your application. Cloudflare wires three layers together:

Sandbox SDK lets you execute untrusted code safely from your Workers. It combines three Cloudflare technologies to provide secure, stateful, and isolated execution:

Workers - Your application logic that calls the Sandbox SDK
Durable Objects - Persistent sandbox instances with unique identities
Containers - Isolated Linux environments where code actually runs

— Cloudflare, Architecture

From your Worker you call getSandbox(); that reaches a Sandbox Durable Object, which talks to the container over HTTP (default transport). The developer-facing surface is intentionally small:

import { getSandbox } from "@cloudflare/sandbox";
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
const result = await sandbox.exec("python script.py");

Purpose: Provide a clean, type-safe TypeScript interface for all sandbox operations.

— Cloudflare, Architecture

In 1.0, the @cloudflare/sandbox package does not start or stop the container; classes such as Files run helper processes via exec() on a container you already started from the Durable Object container API. The image must include sandbox-shim at /usr/local/bin/sandbox-shim, matching the installed package version, and the Worker needs the nodejs_compat flag (@cloudflare/sandbox reference).

Sandbox lifecycle: when state exists and when it disappears

Section titled “Sandbox lifecycle: when state exists and when it disappears”

Each sandbox has a unique ID, its own filesystem, a dedicated Linux container, and persists as a Durable Object while active (Sandbox lifecycle).

Creation is lazy: getSandbox() returns immediately; the container starts on the first operation (command, file write, and so on) (Lifecycle API — getSandbox()).

While active, files under /workspace, /tmp, and /home, background processes, shell sessions, and code-interpreter contexts remain available. When the container stops (inactivity sleep or explicit destroy()), that state is gone and the next request gets a fresh environment (Sandbox lifecycle — Container lifetime and state).

Naming patterns from the docs:

Pattern Typical ID Use when
Per user `user-${userId}` Playgrounds, notebooks, returning workspaces
Per session / CI job `session-${Date.now()}-…` One-shot tests and pipelines; call destroy() when done
Per task `build-${repoName}-${commit}` Idempotent builds and background jobs

destroy() terminates the container immediately and deletes files, processes, sessions, and exposed ports (Lifecycle API — destroy()). Containers may sleep after about 10 minutes of inactivity but still count toward limits until destroyed. With keepAlive: true, you must call destroy() when finished or containers can run indefinitely (Lifecycle API — getSandbox()).

exec() and commands: run shell safely in the container

Section titled “exec() and commands: run shell safely in the container”

The Commands API runs processes in the isolated container. Quick checks use exec(); long output uses execStream() (Execute commands).

Pass user input safely. Embedding untrusted strings in the shell string is dangerous; the docs recommend validation, writing input to a file, or using stdin:

When you provide the stdin option:

The input data is written to a temporary file inside the container
The command receives this data through its standard input stream
The temporary file is automatically cleaned up after execution

This approach prevents shell injection attacks that could occur when embedding user data directly in commands.

— Cloudflare, Commands — How stdin works

Per-command timeout and session-level commandTimeoutMs are supported; a per-command timeout overrides the session default (Execute commands).

Common workflows include cloning a repo, installing dependencies, and running tests—see the automated testing pipeline tutorial and Run tests from a Git repository. For operations outside Workers, the sandbox bridge exposes the same capabilities over HTTP (POST /v1/sandbox, POST /v1/sandbox/:id/exec, file routes under /v1/sandbox/:id/file/*) with authentication and workspace path containment (HTTP API reference).

Files in the sandbox: paths, writes, and the Files class

Section titled “Files in the sandbox: paths, writes, and the Files class”

0.x SDK methods such as writeFile(), readFile(), mkdir(), and gitCheckout() use absolute paths (for example /workspace/app.js) (Files API, Manage files).

Standard layout inside the container (Container runtime):

  • /workspace — default working directory for application code
  • /tmp — temporary files
  • /home — user home

Parent directories must exist before writeFile() unless you call mkdir(..., { recursive: true }) first (Change file calls, Files API — mkdir()).

Binary data: with RPC transport, readFile(..., { encoding: "none" }) and streaming writeFile() support large or binary payloads; HTTP transport often uses base64 (Files API). The bridge HTTP API limits single PUT bodies to 32 MiB and constrains paths under /workspace (HTTP API reference — File operations).

1.0 Files reads and writes in a running container via sandbox-shim; it does not start the instance (Files API reference). Errors surface as SandboxFileError with Linux codes such as ENOENT; version mismatches between the npm package and container image can yield SandboxProtocolError (Files API reference).

For large repos where clone time dominates startup, ArtifactFS can mount a working tree instead of a full clone when startup time matters more than a complete local clone.

Sessions: shell state inside one sandbox (not a security boundary)

Section titled “Sessions: shell state inside one sandbox (not a security boundary)”

Sessions are bash execution contexts within one sandbox—like terminal tabs on the same machine (Session management).

Sandbox = A user or task workspace
Session = A shell in that workspace

Sessions are useful for organizing work inside one sandbox. They are not a security boundary between users because sessions share the same filesystem and process space.

— Cloudflare, Session management

By default, enableDefaultSession is true, so implicit calls share the default session’s cwd and environment. Cloudflare recommends enableDefaultSession: false for stateless APIs and explicit createSession() when you need shared shell state (Sandbox options, Sessions API).

Scoped to a session Shared across all sessions in the sandbox
Shell env, cwd, session env from createSession() Filesystem, processes on localhost, code interpreter files on disk

Use separate sandboxes (not just sessions) when different users or untrusted tenants must not see each other’s files (Security model, Sandbox security).

Environment variables can be set per session—for example concurrent prod and staging DB URLs (Environment variables).

Code interpreter, Git, and typical workloads

Section titled “Code interpreter, Git, and typical workloads”

The Code interpreter API runs Python, JavaScript, and TypeScript with rich output; contexts keep variables and imports until the container restarts (Use code interpreter). Tutorials cover AI code executors, data analysis with AI, and Workers AI.

gitCheckout() clones into the sandbox (Files API — gitCheckout()); private repos often use a token in the URL or outbound traffic interception (Work with Git, Clone a private repository). Directory snapshots via createBackup() / restoreBackup() help recover from failed installs (Backup and restore).

Perplexity’s Agent API describes sandboxes as suited to scoped repository tasks that finish in one run, not open-ended multi-stage development without clear verification (Sandbox tool).

Security model: isolation between sandboxes, shared trust inside one

Section titled “Security model: isolation between sandboxes, shared trust inside one”

Between sandboxes, Containers run in separate VMs: filesystem, process, and network isolation plus per-sandbox quotas (Security model — Container isolation).

Inside one sandbox, every process shares the same files, can see other processes, and reaches the same localhost ports. A separate Linux user does not contain untrusted code; deployed sandboxes effectively run with root-level capabilities (Sandbox security — Everything in one sandbox is shared).

Practices repeated across guides:

  • One sandbox per user or job: getSandbox(env.Sandbox, `user-${userId}`)
  • Never interpolate raw user input into exec() strings; prefer stdin, file APIs, or strict validation (Security model — Command injection)
  • Keep secrets in Worker bindings and pass only what each session needs
  • If callers choose paths, validate against .. and enforce a workspace root; Files does not restrict paths by itself (Move files in and out of a sandbox)
  • For agent tools, treat command stdout/stderr as untrusted prompts (Sandbox — Agents)

Sandboxes run on Containers; pricing and limits follow that platform (Limits, Pricing). Choose a base image variant (default, -python, -opencode, -musl) in the Dockerfile reference and match Docker tag to @cloudflare/sandbox npm version to avoid compatibility warnings. Deploy flows are covered in Deploy a Sandbox application and Getting started.

  • Reusing one sandbox ID for different users, exposing each other’s /workspace data
  • Assuming destroy() or sleep happened when only a command timed out—processes may still run
  • Writing files without mkdir({ recursive: true }) and hitting ENOENT (Change file calls)
  • Mixing normalizeId: true and false for the “same” logical ID, creating two Durable Objects (Sandbox options — normalizeId)
  • Storing important interpreter or shell state only in memory while the container can sleep after inactivity

Further reading: Concepts, API reference, How-to guides, and Tutorials.

  1. Scaffold or open a minimal Worker from Getting started and deploy with Wrangler so the container image version matches your @cloudflare/sandbox package (Dockerfile reference).

  2. Call your Worker’s run endpoint (for example /run from the template) and confirm JSON includes success: true and expected stdout from exec() (Getting started — Test your deployment).

  3. Exercise a file route: writeFile then readFile under /workspace and confirm content round-trips (Manage files).

  4. For CI-style checks, POST a repo URL to an automated testing pipeline-style handler and verify exitCode reflects pass or fail; call destroy() in a finally block (Sandbox lifecycle — When to destroy).

  5. Optionally deploy the sandbox bridge, hit /health, then create a sandbox and run exec via the documented curl examples (Sandbox bridge — Deploy).

You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.