Contents
- Introduction
- How Agent Substrate and AX work
- Demonstration
- Choosing the right runtime on Google Cloud
- Cleaning up
- Conclusion
- Get started
![]()
A practical guide to isolating long-lived coding agents and keeping credentials outside the sandbox
Introduction
Running AI coding agents on Kubernetes is quite different from running normal web services. A typical API receives a request, does some work, sends back a response, and forgets local state. A coding agent, on the other hand, needs to keep a repository, installed libraries, and test outputs alive across many turns, run code generated by a model, and spend most of its time waiting on model responses, external APIs, or human feedback.
Standard Kubernetes pods (the smallest deployable units in Kubernetes) were not really designed for that pattern, for three main reasons:
- Keeping one dedicated pod running per agent session wastes CPU and memory whenever the agent is sitting idle.
- Spinning up a fresh pod on every turn adds scheduling, image pulls, package installations, and heavy writes to etcd (Kubernetes’s central configuration database) back into every step.
- Standard Linux containers share the host operating system kernel, which leaves a thin wall against untrusted code, while storing API keys as environment variables lets any command inside the container read them.
To address these limitations, two open-source projects from Google divide the problem into two layers. Agent Substrate (github.com/agent-substrate/substrate, Apache 2.0, CNCF Sandbox) provides the underlying runtime for sandboxed agents, disk snapshots, identity, and outbound credential injection. AX, short for Agent Executor (github.com/google/ax, Apache 2.0, agentexecutor.io), sits on top to manage environments, tasks, network rules, and models through simple YAML files.
Terminology note: AX here refers to google/ax (Agent Executor), rather than the “Agent Experience” design term or LangChain’s older AgentExecutor class.
But first, how do these two layers actually separate state from compute and keep secrets out of the sandbox?
How Agent Substrate and AX work
The core idea behind Agent Substrate is to decouple long-lived agent sessions (called actors) from a smaller pool of pre-warmed standby pods (called workers). Instead of asking Kubernetes to launch a new pod every time an agent wakes up, Substrate keeps standby worker pods ready and loads the agent’s saved filesystem right onto an available worker (Figure 1). Frequently changing session records live in PostgreSQL behind Substrate’s own API server rather than overloading etcd. According to the ate.dev documentation, this approach can reach up to 10x higher density than dedicated containers, with core restore times under 500ms.

Security also stays outside the untrusted code by default. Plain Linux containers are not allowed, so every agent runs inside either gVisor (a sandbox that intercepts Linux system calls before they reach the host kernel) or a lightweight virtual machine via Kata (which requires nested virtualization on supported VM types such as n2 or c3). Each agent gets a short-lived identity certificate (SPIFFE) inside an isolated namespace (an atespace). The API server checks permissions on every request, and direct agent-to-agent network traffic is blocked.
API keys also stay outside the sandbox. When an agent makes an approved HTTPS request, an outbound proxy (atenet-egress) intercepts HTTPS traffic outside the sandbox and swaps in the real header from a deny-by-default credential service. On each worker VM, a local helper (atelet) caches snapshots and uploads durable copies to Cloud Storage using short-lived, per-actor tokens rather than broad bucket permissions.
While Substrate can run any standard Docker image (whether built with Agent Development Kit (ADK), LangChain, or a coding CLI), AX makes it much easier to work with day to day. We will use AX v0.4.0-rc.2 below (it is still pre-1.0, so expect occasional API changes) to define four ax.io/v1alpha1 resources (Figure 2):
- Workspace: A locked setup template specifying a container image, Git repositories to clone, inline files such as
AGENTS.md, setup commands, and an optional setup-only network policy. Applying a Workspace builds a reusable disk snapshot so tasks can start warm instead of installing packages every time. - Task: An isolated coding-agent sandbox mapped one-to-one to a Substrate actor. Tasks always start suspended until we wake them up, specify maximum CPU and memory limits, and can enable remote shell access for debugging.
- Gateway: An explicit outbound domain allowlist copied onto a task at creation time (so later edits never surprise running tasks). Without a Gateway, a task has no internet access at all.
- Model: A shared LLM provider configuration linked to a Kubernetes Secret so API keys stay out of plain-text task definitions.

Demonstration
We are now going to walk through a practical demonstration together on Google Kubernetes Engine (GKE). First, we will pre-warm a real open-source Python repository (pallets/flask, tag 3.1.3) with its dependencies once, and verify that a secret header gets injected outside gVisor without handing any real key to the sandbox. Then we will test an offline edit across four suspend and resume cycles, launch a second air-gapped agent from the same snapshot, and measure how much space everything takes in Cloud Storage.
Both companion YAML files, along with detailed troubleshooting notes, are available on my GitHub. In the commands below, swap example-gcp-project for your own billed Google Cloud project ID.
Setting up GKE, Substrate, and AX
First of all, we need Go 1.27+, kubectl, gke-gcloud-auth-plugin, an active gcloud login (gcloud auth login), and Application Default Credentials (gcloud auth application-default login). Let us clone the official GKE installer and Substrate v1.0.0 repositories (using pre-built images avoids compiling from source), then install the kubectl-ate plugin and AX CLI:
git clone --depth 1 https://github.com/ai-on-gke/substrate-gke.git
git clone --depth 1 --branch v1.0.0 https://github.com/agent-substrate/substrate.git substrate-v1.0.0
(cd substrate-v1.0.0 && GOBIN="$HOME/.local/bin" go install ./cmd/kubectl-ate)
curl -fsSL https://raw.githubusercontent.com/google/ax/main/install.sh | AX_VERSION=v0.4.0-rc.2 sh
export PATH="$HOME/.ax/bin:$HOME/.local/bin:$PATH"
Next, we export the configuration variables used across bootstrap, deployment, and cleanup (including Google Service Account names ending in _GSA_NAME and PROJECT_NUMBER for cleanup). Keep BUCKET_NAME at 56 characters or fewer because bootstrap also creates a companion ${BUCKET_NAME}-assets bucket:
export PROJECT_ID="example-gcp-project"
export PROJECT_NUMBER="$(gcloud projects describe "${PROJECT_ID}" --format='value(projectNumber)')"
export GCE_REGION="europe-west2"
export CLUSTER_LOCATION="europe-west2-a"
export NETWORK="default"
export SUBNETWORK="default"
export CLUSTER_NAME="substrate-blog-demo"
export CLUSTER_VERSION="1.37"
export RELEASE_CHANNEL="rapid"
export NODE_POOL_NAME="substrate-node-pool"
export NODE_MACHINE_TYPE="c3-standard-4"
export ENABLE_NESTED_VIRTUALIZATION="false"
export SEPARATE_SYSTEM_NODES="true"
export BUCKET_NAME="snapshot-substrate-example-gcp-project"
export SNAPSHOT_LOCATION="gs://${BUCKET_NAME}/"
export SNAPSHOT_TRANSFER_GSA_NAME="ate-snapshot-transfer"
export NODE_GSA_NAME="ate-gke-node"
# Avoids SSL errors behind some corporate proxies
export CLOUDSDK_STORAGE_PARALLEL_COMPOSITE_UPLOAD_ENABLED="False"
At this point, we run the 9-step bootstrap script (GKE 1.37 or newer is needed for Kubernetes’s stable pod identity certificate API, certificates.k8s.io/v1). This takes around six minutes (346.7 seconds) and creates three separate VM pools (one system node, one PostgreSQL node, and a two-node worker pool with tuned OS limits), keyless IAM bindings (Workload Identity), both storage buckets, and three Cloud Monitoring dashboards. Because the cluster control plane has no public IP, we also turn off gcloud’s default ADC override when fetching credentials:
cd substrate-gke
go -C tools/setup-gcp run . bootstrap
export CLOUDSDK_CONTAINER_USE_APPLICATION_DEFAULT_CREDENTIALS=false
gcloud container clusters get-credentials "${CLUSTER_NAME}" \
--location "${CLUSTER_LOCATION}" --project "${PROJECT_ID}"
Production tip: GKE turns node auto-upgrade on by default. During a planned upgrade, awake agents get 30 minutes to suspend before landing in
ACTOR_STATE_CRASHED(reclaimable Spot VMs can terminate far sooner). In production, avoid Spot VMs and disable auto-upgrade onsubstrate-node-pool.
Now we move into substrate-v1.0.0 and deploy the Substrate control plane with gVisor enabled. Setting ATE_INSTALL_CORDON_SYSTEM_INFRA_COMPONENTS=true keeps Substrate’s management services and PostgreSQL on their reserved VM pools away from untrusted sandboxes, and the --ingress-allowed-spiffe-ids flag allows the AX server and Substrate’s client identity to connect in. This step finishes in roughly 85 seconds:
cd ../substrate-v1.0.0
export ATE_INSTALL_CORDON_SYSTEM_INFRA_COMPONENTS=true
go run ./cmd/ate-setup deploy ate-system \
--credential-provider='{"name":"k8s.io"}' \
--ingress-allowed-spiffe-ids=spiffe://cluster.local/ns/ax-system/sa/ax-server,spiffe://cluster.local/ns/ate-system/sa/atenet-client \
--sandbox-classes=gvisor \
--image-repo ghcr.io/agent-substrate/substrate \
--image-tag v1.0.0
Because bootstrap does not create worker pods automatically, we define a small two-replica workerpool.yaml with 2 vCPUs and 2Gi memory per worker pod (leaving 1,984Mi schedulable after 64Mi of worker overhead, plenty of room for our 1 vCPU / 1Gi Flask task):
We then apply the worker pool (ready in about 6 seconds) and install AX onto our active kubectl cluster (which takes about a minute and opens a local tunnel automatically):
kubectl apply -f workerpool.yaml
ax install
Notice two helpful safety choices built right in. First, ax install configures the credential service to read only Kubernetes Secrets carrying the label ax.io/credential: "true", keeping every other Secret hidden from agents. Second, Substrate rejects mutable container tags like :v0.4.0-rc.2 immediately, requiring an immutable @sha256:... fingerprint so changing an image never breaks stored disk snapshots. In production, also add Kubernetes placement rules for AX’s own pods, since default ax install places them on the worker VM pool.
Pre-warming a Flask repository and verifying network isolation
A great real-world pattern for coding agents is splitting setup-time and runtime network access. Setup needs GitHub and PyPI once to clone code and fetch packages, while the running agent should lose access to package registries and never hold real API keys.
To test secret injection safely without using a real provider key, we create a non-sensitive Kubernetes Secret and deliberately omit the ax.io/credential label at first so we can verify it is blocked by default:
kubectl create secret generic demo-api-creds -n default \
--from-literal=api-key=ax-demo-injected-key-outside-gvisor \
--dry-run=client -o yaml | kubectl apply -f -
Next, save this five-part manifest as ax_demo_manifest.yaml. It declares a setup-only Gateway (GitHub and PyPI), a runtime Gateway (allowing postman-echo.com and swapping the x-api-key header outside gVisor), the pre-warmed Flask 3.1.3 Workspace, a primary pr-agent Task, and a second air-gapped isolated-audit Task with no Gateway at all:
We install pre-built Python wheels directly into /workspace/.deps instead of building a full virtual environment, because creating a virtualenv inside a 1 vCPU gVisor sandbox exceeded the 5-minute ax apply timeout. Wheel-only installation finishes in about 4.5 minutes (269 seconds). If you plan to run Flask 3.1.3’s own test suite, pin pytest==8.4.1 in that line (newer pytest 9 removed an internal helper Flask 3.1.3 expects).
Now we apply the manifest and wake up pr-agent. Because the task references the Workspace without adding an overriding spec.profile, it boots straight from the saved snapshot in just 3.23 seconds, more than 80 times faster than repeating the setup:
ax apply -f ax_demo_manifest.yaml
ax resume task pr-agent
First, let us check inside pr-agent that the environment only holds the dummy "placeholder" key and that setup-only domains (pypi.org and github.com) are now completely blocked:
ax ssh pr-agent -- sh -c '
echo "DEMO_API_KEY=$DEMO_API_KEY"
curl -sS -o /dev/null --max-time 10 https://pypi.org/simple/ || echo "pypi blocked"
curl -sS -o /dev/null --max-time 10 https://github.com || echo "github blocked"
'
Both domains fail immediately with Could not resolve host (exit code 6) and print the blocked lines above. Setup permissions never carry over into runtime.
Next, we call https://postman-echo.com/headers using Python’s built-in urllib (in production, you would point this same rule at endpoints like generativelanguage.googleapis.com or api.github.com). We pre-load the sandbox’s built-in proxy certificate (SSL_CERT_FILE, set automatically inside the container) ahead of opening the connection instead of using curl, because the outbound proxy gives a 1-second window for the TLS handshake and curl can miss it on a 1 vCPU sandbox (full notes are in the companion GitHub README.md):
ax ssh pr-agent -- python3 -c '
import os, ssl, urllib.error, urllib.request
ctx = ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE"))
hdrs = {"User-Agent": "substrate-demo/1.0", "Accept": "application/json",
"x-api-key": os.environ["DEMO_API_KEY"]}
req = urllib.request.Request("https://postman-echo.com/headers", headers=hdrs)
try:
with urllib.request.urlopen(req, context=ctx, timeout=15) as r:
srv = r.headers.get("server")
print(f"HTTP {r.status} server={srv!r}")
print(r.read().decode().strip())
except urllib.error.HTTPError as e:
srv = e.headers.get("server")
print(f"HTTP {e.code} server={srv!r} body={e.read().decode()!r}")
'
Before labeling the Secret, the proxy blocks the request in 19ms without ever contacting postman-echo.com:
HTTP 403 server='envoy' body='egress denied'
Next, we add the single ax.io/credential=true label (no policy edits or pod restarts required). Running the Python check twice, first with x-api-key in hdrs and then with it removed (bracketed labels added below for clarity), shows the swap happened strictly outside gVisor:
kubectl label secret demo-api-creds -n default --overwrite ax.io/credential=true
[LABELED_WITH_PLACEHOLDER_HEADER] HTTP 200 server='envoy'
{"headers":{"host":"postman-echo.com","x-api-key":"ax-demo-injected-key-outside-gvisor","accept":"application/json","user-agent":"substrate-demo/1.0","accept-encoding":"gzip, br","x-forwarded-proto":"https"}}
[LABELED_WITHOUT_HEADER] HTTP 200 server='envoy'
{"headers":{"host":"postman-echo.com","accept":"application/json","user-agent":"substrate-demo/1.0","accept-encoding":"gzip, br","x-forwarded-proto":"https"}}
Inside the container, DEMO_API_KEY stayed "placeholder" the whole time, and requests without x-api-key passed through without any secret attached.
Multi-turn workflow, snapshot fan-out, and suspend/resume latency
Now we can test an offline edit-and-test loop and check that files survive hibernation. One early AX v0.4.0-rc.2 quirk is that restored snapshot files are owned by non-root user 1000, while ax ssh connects as root inside a restricted gVisor sandbox that blocks root from writing inside user-1000 folders like /workspace/flask (so real agent processes should run as user 1000). Writing a quick regression test directly into /workspace lets us verify offline pytest right away:
ax ssh pr-agent -- sh -c '
export PYTHONPATH=/workspace/flask/src:/workspace/.deps
cat > /workspace/test_json_error_regression.py <<'\''PY'\''
from flask import Flask, jsonify
def test_custom_json_404_error_handler():
app = Flask(__name__)
@app.errorhandler(404)
def not_found(err):
return jsonify({"error": "not_found", "code": 404}), 404
resp = app.test_client().get("/missing-endpoint")
assert resp.status_code == 404 and resp.is_json
assert resp.get_json() == {"error": "not_found", "code": 404}
PY
python3 -m pytest -q /workspace/test_json_error_regression.py -o cache_dir=/tmp/pytest_cache
'
The test passes offline in under two seconds. Next, we run four back-to-back ax suspend task pr-agent and ax resume task pr-agent cycles on the 14.96 MiB workspace, adding a marker file after cycle 1 to confirm everything stays intact through cycle 4. Figure 3 and the table below summarize the measured CLI wall-clock timings:


(Both means use standard half-up rounding from the four cycle readings above.)
These end-to-end CLI times are naturally higher than Substrate’s under-500ms core restore figure because they include the remote tunnel round trip, restoring the multi-megabyte workspace, readiness checks, and status updates. Resumes stayed consistent between 3.20s and 3.38s, while suspends took between 0.30s and 2.63s as checkpoints uploaded to Cloud Storage. For production workloads, drive agent turns through the task command or proxy router rather than chaining interactive ax ssh calls over a remote tunnel.
To confirm that two agents can share one pre-warmed snapshot without touching each other’s files, we also wake up isolated-audit (no Gateway attached):
ax resume task isolated-audit
ax ssh isolated-audit -- sh -c '
test ! -e /workspace/test_json_error_regression.py && echo ISOLATED_COPY_OK
curl -sS -o /dev/null --max-time 8 https://postman-echo.com/headers || echo AIR_GAPPED_OK
'
It boots in 3.65 seconds (about 74x faster than building from scratch) on the other worker pod while pr-agent stays running, sees none of pr-agent’s edited files, and cannot reach the internet at all.
Inspecting active actors and Cloud Storage snapshot sizing
Finally, we can inspect the two running actors across our worker pods using kubectl-ate and check how much space a real Python repository takes in Cloud Storage (note gcloud storage du uses --readable-sizes rather than -lh):
kubectl ate get actors -a default
kubectl ate get workers
gcloud storage du --readable-sizes --summarize "gs://${BUCKET_NAME}"
gcloud storage ls -l "gs://${BUCKET_NAME}/**"
Both pr-agent and isolated-audit report ACTOR_STATE_RUNNING, one per worker pod (each using 1Gi of the 1,984Mi available memory). Inside the sandbox, /workspace totaled 14.96 MiB uncompressed (about 3.02 MiB for Flask and 11.94 MiB for .deps/). In Cloud Storage, the entire bucket held 16.47 MiB across 27 objects (24 zstd-compressed files plus 3 metadata manifests):

Three details stand out when planning storage:
- Strong compression: zstd compressed our initial 14.96 MiB workspace nearly 4x down to 3.82 MiB.
- Root overlay counts too: changes to the container’s root filesystem (
rootfs/) still added 3.39 MiB (3.65 MiB onpr-agent), even with pip caching turned off. - Self-contained latest checkpoints: Substrate keeps only the latest checkpoint per actor (not four stacked copies), and never-suspended
isolated-auditadded no storage, though each checkpoint is saved against the base image rather than as a tiny diff over the tagged workspace. At roughly 9.26 MiB each, 1,000 suspended Flask-scale agents would need about 9.0 GiB (9.7 GB decimal) of Cloud Storage in default disk-only mode (full live-memory VM snapshots take significantly more).
Choosing the right runtime on Google Cloud
Setting up three GKE node pools and a snapshot bucket makes the most sense once you are running fleets of stateful, mostly idle agents. For simpler stateless services, lighter options are much easier to operate:

If you would rather experiment on your laptop first before provisioning GKE, running ax local start creates a local Kubernetes-in-Docker cluster via Kind, ax studio opens a local browser UI, and ax promote copies manifests to a remote cluster later without copying sandbox state or Secrets.
Cleaning up
Once you are finished testing, stop the local tunnel and run teardown.sh --all from the parent folder containing substrate-gke so no billable cluster nodes or storage buckets stay behind (full cleanup takes around 11 minutes, or pass --cluster-scoped to keep shared dashboards and service accounts):
cd ..
ax tunnel stop
NO_DEV_ENV=1 ./substrate-gke/tools/setup-gcp/teardown.sh --all
It is always good practice to confirm with gcloud container clusters list and gcloud storage ls afterward that everything was deleted cleanly.
Conclusion
Overall, pairing Agent Substrate with AX gives us a practical way to run long-lived, isolated coding agents on Kubernetes without paying for idle pods or putting API keys inside sandboxes. Doing the dependency setup once in a Workspace makes subsequent agent wakeups and air-gapped copies fast, while Cloud Storage gives us predictable storage sizing per suspended agent. Because AX is still pre-1.0, expect a few rough edges around sandbox CPU budgets, restored file ownership, and TLS handshake timeouts, so remember to pin image digests and test upgrades carefully. If you are interested in trying these manifests on your own repository, the companion code and official documentation are linked below.
Get started
- Companion manifests & full troubleshooting notes: pierpaolo28/Artificial-Intelligence-Projects (Google AI tools/Agent-Substrate-and-AX) containing
workerpool.yamlandax_demo_manifest.yaml. - Agent Substrate repository & docs: github.com/agent-substrate/substrate and ate.dev.
- GKE installer & guide: github.com/ai-on-gke/substrate-gke and the GKE installation guide.
- AX (Agent Executor) repository & docs: github.com/google/ax, agentexecutor.io, github.com/agentexecutor/images, and github.com/agentexecutor/studio.
- Google Cloud announcement: Agent Executor on Google Cloud Blog.
- Upstream Kubernetes SIGs effort: github.com/kubernetes-sigs/agent-sandbox.
Disclaimer: Views and opinions in this post are my own and do not represent Google.
Contacts
If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:
