Hosting Agents: Isolation, Queues, Liveness and Security
Every Agent SDK session is a `claude` CLI subprocess with its own shell, working directory and on-disk transcript, so hosting it means hosting long-lived stateful processes. Know the four session patterns, what lives on local disk and how to persist it, the multi-tenant isolation checklist, how to keep credentials outside the agent's boundary and egress behind a proxy, which isolation technology fits which threat model, how to export OpenTelemetry safely, and how to build liveness, deadlines, cancellation and approvals around an SDK that has no session timeout of its own.
Key points
- 1
query()spawns aclaudeCLI subprocess and talks to it over stdio; one session is one subprocess. Both SDKs bundle a native CLI binary pinned to the SDK version, so you upgrade the CLI by upgrading the SDK. Start sizing at 1 GiB RAM, 5 GiB disk and 1 CPU per agent, then use agents per host = (host RAM - overhead) / measured peak RSS per session. - 2
Session patterns: ephemeral (a container per task), long-running (warm sessions in persistent containers;
streamInput()/startup()/prewarm()in TS,ClaudeSDKClientin Python; route with consistent hashing onsessionId), hybrid (ephemeral containers plus a requiredSessionStore), and multi-agent container (separatecwdand isolated settings per agent). - 3
Local-disk state (transcripts in
~/.claude/projects/or underCLAUDE_CONFIG_DIR,CLAUDE.mdfiles, working-directory artifacts) is lost on restart.SessionStoremirrors transcripts only, writes are best-effort (alert onsystem/mirror_error), and memory files and artifacts need a volume or an object-store sync. - 4
Multi-tenant checklist for a shared container:
settingSources: [],CLAUDE_CODE_DISABLE_AUTO_MEMORY=1(auto memory ignoressettingSources), a per-tenantCLAUDE_CONFIG_DIR, an explicit per-tenantcwdon every call, and per-tenant egress rules at the proxy. In TSenvreplaces the inherited environment (spreadprocess.env); in Python it merges. - 5
Credentials stay outside the boundary. Route model calls through
ANTHROPIC_BASE_URLto a proxy that injects the key (it sees plaintext requests).HTTP(S)_PROXYonly gives the proxy an opaque CONNECT tunnel unless it terminates TLS and its CA is trusted in the agent. Custom tools or MCP servers can forward to an authenticated service outside the container. Authenticate end users at a gateway, never inside the agent. - 6
Hardened container:
--cap-drop ALL,no-new-privileges, a seccomp profile,--read-onlyplustmpfs,--network nonewith a mounted proxy Unix socket, memory, CPU and pids limits, and a non-root user. Read-only mounts still expose.env,.npmrc, keys and cloud credential files, so filter what you mount. - 7
Isolation trade-offs: sandbox runtime (low overhead, shared kernel, no TLS inspection); containers (strength depends on setup, shared kernel); gVisor (userspace syscall interception, up to 10-200x slower on file-heavy I/O); Firecracker microVMs (own kernel, under 125 ms boot, traffic over vsock to a host proxy). The built-in sandboxed Bash tool covers only shell commands; file tools, MCP servers and hooks need a whole-process boundary.
- 8
Inside Claude Code's sandbox,
sandbox.credentialscandenya file or env var ormaskit with a placeholder that the proxy swaps for the real value on allowed hosts. Masking requiresnetwork.tlsTerminateand trusted settings scopes.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1strips recognized credentials from subprocess environments but keeps GitHub tokens and proxy variables. - 9
OpenTelemetry:
CLAUDE_CODE_ENABLE_TELEMETRY=1plus per-signal exporters; traces also needCLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1. Never use theconsoleexporter through the SDK (stdout is the message channel). Export errors are silent unlessCLAUDE_CODE_OTEL_DIAG_STDERR=1. Defaults: metrics every 60 s, traces and logs every 5 s. Spans:claude_code.interaction>llm_request/tool(>blocked_on_user,execution) /hook, with subagent spans nested under the parent's Agent tool span. - 10
Telemetry is structural by default; content needs opt-in (
OTEL_LOG_USER_PROMPTS,OTEL_LOG_TOOL_DETAILS,OTEL_LOG_TOOL_CONTENT,OTEL_LOG_RAW_API_BODIES). The SDK auto-injectsTRACEPARENTwhen a span is active, unless you set it yourself inenv. Per-user IDs inOTEL_RESOURCE_ATTRIBUTESbecome metric labels unlessOTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES=false. - 11
Liveness and limits: there is no top-level session timeout, so add your own wall-clock timer that calls
interrupt()/abort/close()and keepmaxTurnsas a backstop.tool_progressheartbeats arrive about every 30 s during main-agent tool calls,agentProgressSummariesgives subagenttask_progresssummaries, andpingstream events show a gateway is still holding a response.CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MSis a stall watchdog, not a deadline.maxBudgetUsdis a client-side estimate;task_budget/taskBudgetlets the model pace itself. - 12
Approvals:
canUseToolcan stay pending indefinitely, so enforce your own timeout and return a deny with a message. For waits longer than the process lives, use aPreToolUsedeferand resume later (single tool call per turn only). Choose a deployment: Agent SDK to embed the loop in your own infrastructure, Managed Agents (beta,managed-agents-2026-04-01) to have Anthropic host the loop, sandbox and session state (not ZDR-eligible), the raw Messages API for full control, the headless CLI for scripts and pipelines.
Common traps
Thinking a read-only mount or a
Bash(curl *)deny rule handles secrets or egress: reads still leak files, and text-matching rules are bypassed by other binaries. Enforce egress at the network layer and keep credentials outside the boundary.Setting
HTTPS_PROXYand expecting the proxy to add an API key header: without TLS termination it only sees an encrypted tunnel. UseANTHROPIC_BASE_URLfor model calls.Assuming
settingSources: []isolates tenants on its own: auto memory, the shared~/.claude.json/config directory and the shared outbound identity still needCLAUDE_CODE_DISABLE_AUTO_MEMORY,CLAUDE_CONFIG_DIRand per-tenant egress rules.Expecting a
SessionStoreto bring back files andCLAUDE.mdnotes on a new container: it mirrors transcripts only.Relying on
finallyblocks oratexitto clean up CLI subprocesses: an OOM kill (SIGKILL) skips them, so make a container, pod or process group the unit of cleanup.Treating
API_TIMEOUT_MS,BASH_DEFAULT_TIMEOUT_MSor the subagent stall timeout as a session deadline: each guards one narrow thing, and the SDK has no session timeout.Using the
consoleOTel exporter with the SDK, or adding per-user IDs as resource attributes without turning off metric labels: the first corrupts the stdio protocol, the second explodes metric cardinality.Picking Managed Agents for a workload that requires Zero Data Retention: it stores session history server-side and is currently not eligible.
Read the source
Further reading
Suggest a resourceNo extra reading for Hosting Agents: Isolation, Queues, Liveness and Security yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Hosting Agents: Isolation, Queues, Liveness and Security
Ten questions, with the answer and explanation after each one.