When a Worker Isolate Is the Wrong Fit
At 09:14 a support ticket arrives with a reproduction link. The team wants an agent that clones the customer's repository, runs the failing test, and attaches a screenshot of the broken checkout page. The webhook handler that receives the ticket is already a Worker and works fine. The next three steps each break a different assumption.
Cloning a repository needs a filesystem and git. Running tests needs a process tree and native dependencies. Screenshotting a checkout page needs a rendering engine with a DOM, layout, and cookies. None are features you can enable on a Worker; they are outside its execution model.
Four terms matter.
- A Workers isolate is a V8 isolate in a shared process. It starts in milliseconds, has 128 MiB of memory, no filesystem, no child processes, and reaches the network only through
fetch. - A Container is your Linux image (
linux/amd64) running inside a Firecracker microVM with its own kernel and network. A Durable Object starts and stops it, and it is reachable only through that Durable Object. - A sandbox is a trust contract, not a fourth runtime: Cloudflare offers it in two backends, a Container for code that expects Linux and a Dynamic Worker for generated JavaScript that only calls methods your Worker passes in.
- A browser session is a remote Chromium you drive over the Chrome DevTools Protocol (CDP). The browser runs on Cloudflare's network; your code holds a connection, not a browser binary.
The mental model is a ladder of boundaries, climbed only as far as the risk requires. A Worker is a hot desk: instant and cheap, with no lockable storage and no lathe. A Container is a leased workshop with its own door and tools, metered while the lights are on and swept between tenants. A Sandbox is that workshop after you hand the keys to a contractor you do not trust: isolation protects the building, not the equipment inside. Browser Run is a chauffeured van; you never own the engine, and you pay by the hour.
Figure 1 turns that into a routing decision. The first branch is capability: if the work needs processes, files, or native binaries, a Worker cannot do it however the code is written. The second is trust: generated code belongs in a sandbox even when a Worker could execute it. The third is rendering: a browser is required only when the page must actually run.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
R["Task: clone repo, run tests, screenshot page"] --> Q1{"Needs child processes, files, or native binaries?"}
Q1 -->|No| Q3{"Needs a real rendering engine?"}
Q1 -->|Yes| Q2{"Is the code untrusted or generated?"}
Q2 -->|No| C["Container
Firecracker microVM, own kernel"]
Q2 -->|Yes| S["Sandbox
Container or Dynamic Worker"]
Q3 -->|No| W["Workers isolate
128 MiB, no disk, ms start"]
Q3 -->|Yes| B["Browser Run session
remote Chromium over CDP"]
C --> X["Reachable only through its Durable Object"]
S --> Y["Egress off by default; credentials stay in the Worker"]
B --> Z["60 s idle close; billed per browser-hour"]
W -.->|"cannot fork or mount a disk"| F["Task cannot run here"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class R,Q1,Q3,C,S,W,B,X,Y,Z,F secondary;
class Q2 ok;
Figure 2 draws the same decision as boundaries. Each band answers a different question: who the caller is, which instance they reach, what the process may touch, and what may leave.
Choose by boundary, not language
The common mistake is choosing by language. "It is TypeScript, so it runs on Workers" is false for a test runner that spawns children; "it is a container image, so it needs Kubernetes" is false for one long-lived process.
Pick the boundary the work needs, then the runtime that provides it.
Containers and Their Lifecycle
A Container is one image and one process tree inside one microVM, available on the Workers Paid plan. Cloudflare runs each instance in Firecracker with its own kernel and network, so nothing else shares that kernel. The image must target linux/amd64, and the entrypoint is whatever the Dockerfile declares.
The lifecycle has one race worth designing around.
Running is not ready
A Durable Object starts the instance, the image boots, and then ctx.container.running becomes true — before the process is listening. Forward the first request at that moment and you get a connection refused that looks like a broken image.
Poll the port until it answers; that is what startAndWaitForPort does.
Cold starts are commonly 1–3 seconds, depending on image size and entrypoint work. That is a documented range, not a guarantee.
Billing follows the same line. Charges start when a request reaches the container or it is started manually, and stop when it sleeps. Memory and disk bill on the provisioned instance size; CPU bills on active use only. An idle instance that is still running is still billed, the most common surprise here.
Three numbers decide what a later request finds. The Container class sets the default, the Durable Object can override it, and only a forwarded request counts as activity.
| Control | Default | Range or rule | What it means |
|---|---|---|---|
sleepAfter | Ten minutes on the Container class | Set per class in code | A request inside the window resumes the same instance, files and processes |
setInactivityTimeout() | Unset; the class idle setting applies | Up to six hours per the Sandbox docs | The longest gap that still resumes the same instance |
| Snapshot retention | 30 days | Each restore refreshes the window | Files survive a stop, but only if you saved a snapshot |
Code inside the container is not activity. A twenty-minute build on a five-minute timeout is killed mid-run, because the clock tracks requests, not CPU or progress.
Disk is ephemeral. When an instance sleeps and starts again, it gets a fresh disk from the image. That aids reproducibility and endangers anything you forgot to persist. Snapshots are the exception: they save the filesystem, up to 20 GB, with a 30-day retention that each restore refreshes, and they capture secrets written into files.
Placement is not stable. The Durable Object and its container may run in different locations, and after a restart requests can land elsewhere. Persist state in Durable Object storage; treat the container as disposable compute.
| Criterion | Workers isolate | Container | Sandbox | Browser Run |
|---|---|---|---|---|
| Isolation unit | V8 isolate in a shared process | Firecracker microVM, own kernel | Container or Dynamic Worker | Remote Chromium session |
| Typical start | Milliseconds | 1–3 s cold start, warm after | Same as its backend | Launch cost; reuse sessions to avoid it |
| Filesystem | None | Ephemeral, fresh from image | Ephemeral, plus snapshots | Managed browser profile |
| Process tree | No child processes | Any Linux process | Any Linux process, or none | Chromium's own processes |
| Inbound network | HTTP through the Worker | HTTP through its Durable Object only | Same as its backend | CDP connection from your code |
| Outbound network | fetch only | Worker outbound handlers, allowlists | Off by default for containers | Public internet |
| Durable state | KV, D1, R2, Durable Objects | Durable Object storage, not disk | Durable Object storage and snapshots | None; persist results yourself |
| Billed by | Requests plus CPU | 10 ms of active time, provisioned memory and disk | Container or Dynamic Worker rates | Browser-hours plus concurrency |
| Plan | Free and Paid | Workers Paid | Workers Paid | Free and Paid |
Figure 3 shows the healthy path and three failures: the port never becomes ready, the process exits on its own, and the stop sequence runs out of patience.
Cleanup is best effort
The platform sends SIGTERM, waits up to fifteen minutes, then SIGKILL. The Sandbox documentation says the stop follows shortly after, so do not depend on a long cleanup window.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
stateDiagram-v2
[*] --> Stopped
Stopped --> Starting: start()
Starting --> Running: image booted
Running --> Ready: port accepts connections
Starting --> Failed: image or entrypoint error
Failed --> Stopped: instance reported stopped
Ready --> Serving: request forwarded
Serving --> Ready: response returned
Ready --> Stopping: idle timeout, signal(), destroy()
Stopping --> Stopped: SIGTERM, then SIGKILL
Ready --> Stopped: main process exits
Stopped --> Starting: next request is a cold start
note right of Running : running is true before the port is ready
note right of Stopping : cleanup is best effort, not guaranteed
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class Stopped secondary
class Starting,Stopping warn
class Running primary
class Ready,Serving ok
class Failed danger
The widget below is the smallest honest version of that lifecycle: it starts a container only for a named instance, forwards the request, sleeps after sixty seconds, and blocks egress. The second panel writes the configuration and image, deploys, and compares a cold request with a warm one.
Same name, same process. Two requests to alpha should report the same boot time and process ID; beta should report different ones. If the two alpha calls differ, the instance never stayed alive — usually because the sleep window was shorter than the gap, or because the request bypassed the named Durable Object.
Sandboxes for Controlled Command Execution
Sandboxes turn this from a deployment question into a trust question. Cloudflare frames "Sandbox" as one idea with two implementations. A container sandbox runs a Linux image with runtimes, packages, files, and processes. A Dynamic Worker sandbox runs generated JavaScript against methods your Worker hands it, and does not inherit your bindings, credentials, or data.
The selection rule is mechanical. If the code expects an operating system — npm test, a compiler, a preview server on a port, a native add-on — use the container backend. If it only calls operations you already expose, use a Dynamic Worker: it starts faster, has no image to maintain, and its blast radius is the method list you wrote. One request can use both: a Dynamic Worker answers questions through scoped methods, then a container runs the test suite.
A separate Linux user is not an isolation boundary. Every process in a deployed sandbox has the same Linux capabilities as root, so file permissions do not restrict it and it can switch back to root.
The sandbox, not the process, is the trust boundary
All processes in one sandbox share a filesystem and share localhost, and Cloudflare states the conclusion directly: isolate at the sandbox, not at the process.
Isolation protects your Worker from the sandbox, not the sandbox from itself. Anything you put inside — a token in a clone URL, an environment variable, a snapshot — is readable by every process the sandbox runs, and by anything those processes download.
Cloudflare's security guide gives the case study. A coding agent clones a private repository and the Worker puts a token in the clone URL. Git writes that URL into .git/config. The tests run, a test dependency reads the file, and the token leaves in a request the agent never made. Keep the credential outside the sandbox: the container sends a plain request, and an outbound handler in the Worker adds the token after the request leaves the microVM. It must only attach credentials to HTTPS, because it forwards using the scheme the container chose.
Two rules follow. First, the sandbox name is a routing key, not an identity. getByName() returns the same sandbox and saved files for anyone who supplies the name, so derive it from an authenticated principal. Second, snapshots carry files forward, including .git/config; reusing one across users hands the second user the first user's workspace.
Egress is a decision, not a default. A container sandbox starts with enableInternet: false; a Dynamic Worker starts with your Worker's network access unless you load it with globalOutbound: null.
Opening the internet opens every host
Enabling internet so one install works also gives a malicious dependency a route to any server it can resolve. Allowlist the registry and deny the rest; a Dynamic Worker loaded with globalOutbound: null fails every call instead.
Browser Run for Browser Sessions and Automation
Browser Run answers a narrower question: does the page have to execute? If the content is in the initial HTML, fetch plus a parser is cheaper, faster, and easier to secure. If JavaScript must render a price, a chart, or a checkout form, a browser is the only way to see what the user sees.
The product has two shapes. Quick Actions are stateless HTTP endpoints for screenshots, PDFs, Markdown, links, scraped elements, structured JSON, and crawls; there is no code to deploy. Browser Sessions give you Puppeteer, Playwright, CDP, or Stagehand against real Chromium, for logins, clicks, uploads, and multi-step flows.
Session lifetime is the part that generates invoices. A session closes after sixty seconds without a command by default. keep_alive extends that inactivity window to twenty minutes, but it is not a maximum duration: a session receiving commands can stay open longer. Sessions also close on their own — Chromium can crash on a heavy DOM, the connection can drop when your Worker hits its CPU limit, and Cloudflare can evict a session during a release. The recorded reasons are normal closure, browser idle, Chromium crashed, connection error, and session evicted.
Figure 4 contrasts the two endings. On the healthy path, browser.close() runs in a finally block and billing stops. On the failure path, an exception skips the close, the session idles until its timeout, and you pay for a browser that did nothing.
The safe shape is small: launch, work, close in a finally. The idle window is a cost setting, not a lifetime guarantee, so the close runs on both the success and the error path.
The limits shape a safe design. At verification time the Free plan allowed ten browser-minutes per day, three concurrent browsers, and one new browser every twenty seconds. Workers Paid included ten browser-hours per month, then USD 0.09 per hour, and ten concurrent browsers averaged monthly, then USD 2.00 each. Paid defaults cap sessions at 200 concurrent and three new instances per second, with a sixty-second timeout. Those are dated observations, not constants.
Two boundaries are easy to forget. The browser is not inside your isolate: your Worker holds a CDP connection, and every command consumes its CPU budget while the page renders elsewhere. And the browser can reach anything the public internet can, so a user-supplied URL is an SSRF primitive. Allowlist schemes and hosts, reject private address ranges, and cap redirects before the first goto.
Choose a Runtime for Three Concrete Workloads
Choose a Runtime for Three Concrete Workloads
Execution status: design-only; not executed for this article. Every expected result is an acceptance criterion, not a measurement. The planning baseline is 2026-11-02; documentation was re-checked on 2026-11-05.
Three workloads, three boundaries. Each row needs a different runtime, and none of them is chosen by language.
- A — validate and write once. A webhook validates JSON and writes one row to D1. Plain Worker.
- B — run untrusted Python. A user uploads a Python script and a 50 MB CSV; it runs with
pandasand returns a summary. Container sandbox. - C — screenshot behind a login. Every hour, capture a customer dashboard. Browser Session.
Prerequisites. A current Node.js LTS, Docker running locally (Wrangler builds the image with it), Wrangler, curl, and a Workers Paid account. Containers and Sandboxes require Paid; Browser Sessions above the Free allowance do too. Free-plan Browser Run covers only the Quick Action variant.
Minimal setup. One Worker project with the container class from the previous section, a D1 binding, and a MYBROWSER binding. Put all three routes behind a shared secret header.
- Route A through a plain Worker
fetchhandler. Reject bodies over 100 KB, validate the schema, and insert with a prepared statement. Expected: the response returns before any container or browser starts, and the row appears once per idempotency key. - Send the same webhook twice with the same key. Expected: one row, not two.
- Route B to a container sandbox with
enableInternet: false,entrypoint: ["sleep", "infinity"], and a 15-minute inactivity timeout. Write the CSV in, runpython3 analyze.py, read stdout. Expected:exitCode0 and a summary matching a local run. - Run a script that calls
curl https://example.com. Expected: it fails, because egress is off and no handler allows that host. - Allow only
pypi.organdfiles.pythonhosted.orgin an outbound handler, then runpip install pandasand the samecurl. Expected: the install succeeds and thecurlstill fails. - Request sandbox
user-42twice with a gap shorter than the timeout. Expected: the second call sees the CSV written by the first. - Force a restart with
destroy(), then call again. Expected: container files are gone unless you saved a snapshot; the Durable Object's SQLite rows remain. - Route C through a Browser Session:
launch,goto, wait for a selector, screenshot, andclose()in afinally. Expected: a PNG larger than zero bytes and aNormalClosureinpuppeteer.history(). - Remove the
finallyand throw aftergotowithkeep_alive: 1200000. Expected: the request errors, buthistory()later showsBrowserIdle, and browser time accrues for up to twenty minutes.
Failure checks. Each symptom points at one boundary, not at the whole stack.
| Symptom | Likely cause | First check |
|---|---|---|
| 502 on the first container request | Port not ready, not a broken image | Poll the port before forwarding |
| Connection refused on every request | Container never started | max_instances and the binding |
| Duplicate D1 row | Idempotency key not enforced | The insert statement |
| Screenshot timeout on a page that loads locally | Bot challenge | The navigation response |
BrowserIdle close | close() was skipped | The finally block |
Cost dimensions. Local wrangler dev is USD 0 apart from your machine. Container cost follows instance size and wall-clock time while running, not request count; an idle instance with a long timeout is the expensive mistake. Browser cost follows browser-hours plus monthly-averaged concurrency. D1 bills by rows read and written.
Cleanup. Work from the outside in.
- Stop
wrangler devand delete.wrangler/state. - Call
destroy()on every sandbox you created, then delete saved snapshots. - Close every browser and confirm nothing ended as
BrowserIdle. - Run
npx wrangler containers list, thennpx wrangler delete; remove the D1 database and browser binding.
Document Startup, Persistence, Access, and Cleanup Tests
Planned exercise: execution not yet performed. No container, sandbox, or browser session was deployed for this article, so the statements below are pass criteria and documented behavior, not measured results.
Pass evidence. The first request to a new container name takes longer than the second, and both return the same process identity. A request after the inactivity timeout returns a different identity while the Durable Object's rows survive. A sandbox with enableInternet: false cannot reach an unrelated host, and an allowed host succeeds only through the outbound handler. A second user's name never resolves to the first user's files or snapshot. Every browser path, including the error path, ends with a close and a non-idle close reason. wrangler containers list is empty after cleanup.
Fail evidence.
- Warm start disguised as cold. The same boot time after a supposed cold start means the request reached a warm instance.
- State outside the boundary. Files that survive a restart without a snapshot mean state was written outside the container, or the instance never stopped.
- Credential in a snapshot. A token visible in the git config inside a snapshot means a credential crossed the boundary.
- Unclosed browser. A
BrowserIdleclose means the close was skipped. - A bill with no traffic. Growth without requests usually means a long inactivity timeout or an unclosed browser.
Self-check.
Why not run the test suite in a Worker? Because npm test needs a process tree, a filesystem, and often native binaries. A Worker has none of those and 128 MiB of memory. Moving JavaScript into a Worker does not move the operating system with it.
Why is one sandbox per user safer than one sandbox with two Linux users? Every process has root capabilities, so file permissions do not separate them, and all processes share the filesystem and localhost. The sandbox is the smallest unit of trust; a second user can read the first user's files and credentials.
The page renders locally but times out in Browser Run. What do you check first? Whether the page is challenging the request as a bot. Browser Run requests are identified as bots, and a custom user agent does not bypass bot protection. Check the navigation response and the close reason before increasing the timeout.
Unresolved limitations.
- No hosted run. Cold-start duration, throughput, snapshot restore time, and browser reliability were not measured.
- No pinned versions. Wrangler, the container and Puppeteer packages, and workerd are all unpinned because nothing ran.
- Two sandbox surfaces. Sandbox SDK 0.x is documented as legacy for existing applications, while the current product exposes Container and Dynamic Worker environments; do not mix them.
- Scheduling in beta. The
durable_objectcontainer scheduling policy was in public beta at verification time. - SIGTERM wording differs. The lifecycle page describes a grace period of up to fifteen minutes, while the lifetime page says the stop follows shortly after. This article relies on neither as a cleanup guarantee.
- Dated observations. Pricing, allowances, concurrency ceilings, and the Browser Run name are October–November 2026 observations.
References (verified 2026-11-05):
- Containers overview: https://developers.cloudflare.com/containers/
- Lifecycle of a Container: https://developers.cloudflare.com/containers/concepts/architecture/
- Containers limits and instance types: https://developers.cloudflare.com/containers/platform/limits/
- Containers pricing: https://developers.cloudflare.com/containers/platform/pricing/
- Container outbound traffic: https://developers.cloudflare.com/containers/configuration/outbound-traffic/
- Container snapshots: https://developers.cloudflare.com/containers/guides/snapshots/
- Sandboxes on Cloudflare: https://developers.cloudflare.com/sandbox/
- Choose a sandbox environment: https://developers.cloudflare.com/sandbox/concepts/
- Sandbox lifetime: https://developers.cloudflare.com/sandbox/concepts/lifetime/
- Sandbox security: https://developers.cloudflare.com/sandbox/concepts/security/
- Run a Linux command in a sandbox: https://developers.cloudflare.com/sandbox/get-started/
- Dynamic Workers: https://developers.cloudflare.com/dynamic-workers/
- Dynamic Workers pricing: https://developers.cloudflare.com/dynamic-workers/pricing/
- Browser Run overview: https://developers.cloudflare.com/browser-run/
- Browser Run limits: https://developers.cloudflare.com/browser-run/limits/
- Browser Run pricing: https://developers.cloudflare.com/browser-run/pricing/
- Browser Run with Puppeteer: https://developers.cloudflare.com/browser-run/puppeteer/
- Browser close reasons: https://developers.cloudflare.com/browser-run/reference/browser-close-reasons/
- Workers limits: https://developers.cloudflare.com/workers/platform/limits/
- Workers security model: https://developers.cloudflare.com/workers/reference/security-model/
Next in the Series
In Use Workers KV for Read-Heavy Distributed Data, we'll explore Model consistency, expiration, and invalidation deliberately.