Deploy self-hosted workers
Choose how self-hosted sandbox workers claim work and where sessions run, then run an always-on worker or trigger workers from webhooks.
The self-hosted sandboxes quickstart runs one ant CLI worker that polls continuously and runs every session in one process. This page helps you choose a deployment pattern and then covers always-on and webhook-triggered workers.
Choose a deployment pattern
When deploying workers, you need to make two choices: how the worker claims work, and where each session runs.
How the worker claims work:
- Always-on: A long-running process polls the queue continuously. The process makes only outbound HTTPS requests, so you don’t expose an endpoint to Anthropic.
- Webhook-triggered: A handler wakes on
session.status_run_startedand starts polling. This avoids an idle poller, but requires a webhook endpoint that Anthropic can reach.
Where each session runs:
- In process: The worker that claims a session also runs its tool calls, in one shared working directory.
- Sandbox per session: A poller launches a fresh sandbox for each claimed session. Choose this for stronger isolation: a fresh filesystem, resource limits, or per-session network controls. See Run one sandbox per session, which also covers the Helm chart for Kubernetes.
The CLI and SDK workers support different combinations:
| Capability | ant CLI | SDK (Python, TypeScript, Go) |
|---|---|---|
| Always-on polling | Yes | Yes |
| Webhook-triggered | No | Yes |
| Sandbox per session | Yes | Yes |
| Memory stores | Yes, with default sync settings | Yes, with configurable sync |
| Custom tools | No | Yes |
See Self-hosted worker reference for every CLI flag and SDK option.
For more control, call the Environments Work endpoints directly and implement your own worker. Your worker then does what the SDK workers do. Among other things, it acknowledges each work item, sends heartbeats, and downloads the agent’s skills. It runs only the tool calls that the session’s permission policy allows. It returns each result as a user.tool_result or user.custom_tool_result event. At the end, it stops the item. Use the worker’s source in the Python SDK, the TypeScript SDK, or the Go SDK as a reference.
Run an always-on worker
These samples use /workspace as the worker’s working directory. The directory must exist before the worker starts. On a new host, create it and give the worker’s user write access, as in the “Start the worker” step of Run your first session.
On macOS, mkdir can’t create /workspace, because the root volume is read-only. Create ~/workspace instead, as that step shows. In place of /workspace, use the full path that echo ~/workspace prints, because the SDK doesn’t expand ~.
Start a worker that polls the queue continuously. It authenticates with the environment key from the quickstart:
import asyncio
import contextlib
import os
import signal
from anthropic import AsyncAnthropic
from anthropic.lib.environments import EnvironmentWorker
async def main() -> None:
environment_key = os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
environment_id = os.environ["ANTHROPIC_ENVIRONMENT_ID"]
async with AsyncAnthropic(auth_token=environment_key) as client:
worker = EnvironmentWorker(
client,
environment_id=environment_id,
environment_key=environment_key,
workdir="/workspace",
)
task = asyncio.create_task(worker.run())
# Canceling the task, rather than killing the process, lets the worker stop its
# in-flight work item and upload changed memory files before it exits.
loop = asyncio.get_running_loop()
for signum in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(signum, task.cancel)
with contextlib.suppress(asyncio.CancelledError):
await task
asyncio.run(main())Trigger workers from webhooks
Subscribe to session webhooks
In the Claude Console, define a webhook endpoint that listens for
session.status_run_startedevents. See Subscribe to webhooks for details.Export the webhook signing key
Along with the environment ID and key from Run your first session, export the webhook signing key on your handler host. The handler uses it to verify incoming payloads.
export ANTHROPIC_WEBHOOK_SIGNING_KEY="whsec_..."Implement the webhook handler
Start the worker when
session.status_run_startedfires. The handler drains the queue and hands each claimed work item tohandle_item()(in the Python, TypeScript, and Go SDKs). That method downloads skills, runs tool calls, posts results back, and returns.The samples use
/workspaceas the working directory. Before you start the handler, create that directory on the handler host. Make sure that the handler’s user can write to it, as in the “Start the worker” step of Run your first session.PythonTo verify webhook signatures, install the webhooks extra:
pip install "anthropic[webhooks]".import asyncio import os import anthropic import standardwebhooks # installed by the anthropic[webhooks] extra environment_key = os.environ["ANTHROPIC_ENVIRONMENT_KEY"] environment_id = os.environ["ANTHROPIC_ENVIRONMENT_ID"] client = anthropic.AsyncAnthropic( auth_token=environment_key, ) # Canceled by shutdown() so an in-flight work item can upload changed memory files and # remove its store directories before the process exits. inflight: set[asyncio.Task[None]] = set() # Await this from the host's shutdown hook, such as an ASGI lifespan shutdown (the code after # `yield` in a FastAPI lifespan), which uvicorn runs on SIGTERM. uvicorn lets open requests # finish before that hook runs, so set --timeout-graceful-shutdown to bound the wait. async def shutdown() -> None: for task in inflight: task.cancel() await asyncio.gather(*inflight, return_exceptions=True) async def handle(raw: bytes, headers: dict[str, str]) -> tuple[dict[str, str], int]: try: event = client.beta.webhooks.unwrap(raw.decode(), headers=headers) except standardwebhooks.WebhookVerificationError: return {"error": "signature verification failed"}, 401 if event.data.type != "session.status_run_started": return {"status": "ignored"}, 200 task = asyncio.create_task(run_queued_work()) inflight.add(task) task.add_done_callback(inflight.discard) try: # Shielded: a dropped or timed-out delivery must not cancel the item; shutdown() does. await asyncio.shield(task) except asyncio.CancelledError: return {"status": "shutting down"}, 503 return {"status": "ok"}, 200 async def run_queued_work() -> None: async for work in client.beta.environments.work.poller( environment_id=environment_id, environment_key=environment_key, block_ms=None, reclaim_older_than_ms=2000, drain=True, auto_stop=False, ): await client.beta.environments.work.worker(workdir="/workspace").handle_item( work_id=work.id, environment_id=environment_id, session_id=work.data.id, environment_key=environment_key, # The per-session secret is what lets the worker mount the session's memory stores. work_secret=work.secret, )In the Python, TypeScript, and Go SDKs,
handle_item()needs the work item’s secret to mount memory stores. A worker that polls withrun()already has the secret. This handler claims each item itself, so it passes the secret in thework_secretargument. See Forward the work item’s secret.
This handler runs every claimed item in one process, and it runs items from separate webhook deliveries at the same time. Those sessions share one filesystem, including /workspace and /mnt/memory. If your sessions attach the same memory store, see Isolate sessions that share a store.
Next steps
Launch sandboxes with the Helm chart on Kubernetes, a spawn script, or the SDK poller.
Read queue depth, stop sessions and workers cleanly, and fix common failures.
Shared responsibility model for self-hosted sandbox environments.
Availability
Claude API
- Status
- Beta
- API
- Managed Agents
- Beta header
- Requires
- Models
- All models
Claude Platform on AWS
- Status
- Beta
- API
- Managed Agents
- Beta header
- Requires
- Models
- All models
Data handling
Data handling overviewApplicable endpoints
/v1/agents/v1/sessions/v1/environments
Not eligible for ZDR, except for self-hosted Managed Agents. Sessions are stateful resources; transcripts persist until you delete them. Learn more
Not eligible for HIPAA. Applies to all Managed Agents sub-features.
Was this page helpful?