The dream of AI agents has always been limited by the "sandbox tax." If you want an agent to actually do something—like write and execute code to process data or call APIs—you traditionally had to spin up a heavy Linux container. This meant waiting hundreds of milliseconds for boot times and paying for massive memory overhead.
Cloudflare just changed the game.
Cloudflare Dynamic Workers allow you to instantiate a new, secure JavaScript sandbox (an Isolate) from within a Worker, using code generated by an AI at runtime.
By moving away from containers and toward V8 Isolates, Cloudflare has made sandboxing 100x faster and significantly more memory-efficient. For builders, this means you can now give every single user request its own dedicated, secure execution environment without breaking your budget or your latency goals.
Why this matters for builders
Cloudflare Dynamic Workers lets you execute AI-generated code in isolated sandboxes using the Dynamic Worker Loader API.
Previously, if an agent generated code to solve a problem, you had two bad options:
- The Unsafe Route: Use
eval(), which is a massive security risk. - The Slow Route: Use a container-based sandbox (like E2B or Docker), which adds 500ms+ of latency and costs a premium.
Dynamic Workers unlock "Code Mode." Instead of an agent making 20 different tool calls to an API (consuming thousands of tokens), the agent writes a single TypeScript/JavaScript script that performs the logic and calls the APIs locally. Cloudflare has shown this can cut token usage by 81%.
Because these sandboxes are V8 Isolates (the same tech that powers Chrome and the standard Cloudflare Workers), they start in milliseconds and use only a few megabytes of RAM. You can now ship "consumer-scale" agents that are as fast as standard web apps.
When to use it
Use Dynamic Workers when your AI agent needs to perform logic that isn't pre-defined.
- Dynamic Data Processing: When an agent needs to write code to transform a messy JSON blob or perform math that LLMs usually fail at.
- API Orchestration: Instead of 10 round-trips to an LLM for 10 API calls, the agent writes one script to call them all in a loop.
- User-Specific Sandboxes: Giving every user a "plugin" or "macro" environment where they can run AI-generated scripts safely.
- High-Concurrency Tasks: When you need to run thousands of tiny scripts simultaneously without hitting container orchestration limits.
- Latency-Critical Agents: When your agent is part of a real-time chat or UI where a 2-second container boot time is unacceptable.
The full process
Building with Dynamic Workers requires a shift in how you think about AI tools. You aren't just giving the AI a "Search" tool; you are giving the AI a "Coding" tool and a place to run that code.
1. Define the capabilities (RPC Stubs)
Before the agent writes code, you must decide what it is allowed to touch. Dynamic Workers use Remote Procedure Call (RPC) to communicate. You create a "Stub" (a set of functions) in your main Worker and pass it into the sandbox.
The Goal: Define a secure boundary. If the agent code shouldn't touch your database, don't pass the database stub into the Loader.
2. Configure the Loader Binding
You need a paid Cloudflare Workers plan to access the Dynamic Worker Loader. In your wrangler.toml, you will need to set up the binding. (Note: Check the official Cloudflare documentation for the exact current syntax for the experimental loader binding).
3. Shape the Agent Prompt (Code Mode)
You must instruct your LLM (Claude 3.5 Sonnet or GPT-4o are recommended) to output code in a specific format: a standard ES Module.
The Spec:
- It must
export default. - It must accept the parameters you plan to pass (like
envfor your RPC stubs). - It should return a serializable result.
4. Implement the Loader
Once the LLM returns the code string, you use the env.LOADER.load() method. This is the core "vibe coding" step. You take the string and turn it into a live, running worker in one call.
5. Validate and Execute
After loading, you call the entry point of the new worker. You should wrap this in a try/catch because AI-generated code frequently has syntax errors or runtime bugs.
6. Ship and Monitor
Because there are no limits on concurrent sandboxes, you can deploy this to production immediately. Cloudflare handles the scaling from 1 to 1 million sandboxes.
Copy-paste prompts and snippets
The Loader Implementation (Main Worker)
This is how you take the code generated by your AI and run it.
// This runs inside your main Cloudflare Worker
export default {
async fetch(request, env) {
// 1. Imagine 'agentCode' was just generated by Claude/GPT
const agentCode = `
export default {
async runTask(data, env) {
// The agent can use the tools you provided in 'env'
const result = await env.INTERNAL_TOOL.process(data);
return {
message: "Task completed successfully",
processedData: result
};
}
}
`;
try {
// 2. Load the dynamic worker
const dynamicWorker = env.LOADER.load({
compatibilityDate: "2026-03-01",
mainModule: "agent.js",
modules: {
"agent.js": agentCode
},
// 3. Pass restricted tools/APIs to the sandbox
env: {
INTERNAL_TOOL: env.MY_RPC_SERVICE_BINDING
},
// 4. Security: Block all outbound internet access by default
globalOutbound: null,
});
// 5. Execute the code
const result = await dynamicWorker.getEntrypoint().runTask({ some: "data" });
return new Response(JSON.stringify(result));
} catch (err) {
return new Response("Agent code failed: " + err.message, { status: 500 });
}
}
}
The System Prompt for the AI
Use this prompt to ensure the AI generates code compatible with the Dynamic Worker sandbox:
"You are an AI agent acting in 'Code Mode'. Your task is to write a JavaScript ES Module that will run in a Cloudflare Worker sandbox.
Requirements:
- Export a default object with an async function named
runTask(data, env).- Use the
envobject to access authorized tools. Do not attempt to usefetchor external APIs unless told otherwise.- Return a JSON-serializable object.
- Keep the code concise and optimized for V8.
- Only output the code itself, no markdown formatting if requested."
Pitfalls and guardrails
What if the AI generates a loop that never ends?
Isolates have execution time limits. If the agent writes while(true) {}, the Cloudflare Worker platform will kill the isolate once it exceeds the CPU limit of your plan (usually 50ms or 30ms for standard workers). This protects your main application from being hung by the agent.
What if the AI tries to steal my secrets?
This is why the env object is critical. When you call env.LOADER.load(), the env inside the sandbox only contains what you explicitly pass to it. It does not automatically inherit your main worker's environment variables, KV namespaces, or Secrets. If you don't pass it, the agent can't see it.
Can I use Python?
Technically, Workers support Python via Pyodide (Wasm). However, for Dynamic Workers where start-up time is the primary benefit, JavaScript is highly recommended. Loading the Python runtime inside an isolate adds overhead that negates some of the "100x faster" benefits.
Is it really "Unlimited Scalability"?
Unlike sandbox providers like E2B or traditional container clouds that have "concurrent session" limits, Dynamic Workers are an API to the core Cloudflare infrastructure. If Cloudflare can handle the traffic to your site, it can handle the dynamic workers. There is no separate "orchestrator" that gets overwhelmed.
What to do next
- Upgrade your account: Ensure you are on a Workers Paid plan to access the Dynamic Worker Loader API.
- Audit your Tools: Look at your existing MCP (Model Context Protocol) servers. Can you convert them into a simple TypeScript API that can be passed as an RPC stub?
- Start Small: Build a "Data Cleaner" agent. Pass it a messy CSV string and ask the LLM to write a script to normalize it into JSON. This is the safest way to test the loader.
- Lock down networking: Ensure you set
globalOutbound: nullin your loader configuration unless your agent specifically needs to call external URLs.
Sources
- Cloudflare Blog: Sandboxing AI agents, 100x faster
- Technical Documentation: Dynamic Worker Loader API (Search within Cloudflare Docs)

