adk deploy cloud_run deploys an ADK agent directory to Cloud Run as a container service that runs the ADK API server. Cloud Run flags go after --; this lesson passes --no-allow-unauthenticated to keep the service private and --service-account to run it as a dedicated runtime service account. Here we inspect a private deployment of the docuctl docs assistant, call its session and /run endpoints with an identity token, and examine two failures: the runtime account could not call the model, and a local session disappeared after a new revision.
When you need this. Your application already calls an HTTP agent service and your team operates Cloud Run. You can keep that interface, but the caller’s permission to reach the service, the container’s permission to call the model, and the durability of its sessions are three separate decisions.
After a new revision, the earlier local session is missing
GET /apps/docs_helper/users/dana/sessions/edf2c2c7-a982-426f-b4d5-c6f4f63bd84e
HTTP 404
{"detail": "Session not found"}Lab setup. Download the complete lab ZIP, extract it and open a terminal in adk-cloud-run/. Keep its code, tests and fixtures together. Create the pinned environment for local checks:
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-lock.txtYou can read the saved cloud results without provisioning any services. To run the cloud steps, you need the project access listed in the prerequisites.
1. Deploy a private API-server service
Deploy the agent directory with adk deploy cloud_run, passing Cloud Run flags after -- to set explicit resource limits, a dedicated runtime service account and --no-allow-unauthenticated:
adk deploy cloud_run --project $GOOGLE_CLOUD_PROJECT --region us-central1 \
--service_name docs-helper --app_name docs_helper docs_helper -- \
--no-allow-unauthenticated \
--service-account=docs-helper-run@$GOOGLE_CLOUD_PROJECT.iam.gserviceaccount.com \
--min-instances=0 --max-instances=1 --cpu=1 --memory=512Mi \
--labels=aiml-lesson=deploy-an-adk-agent-to-cloud-runADK copies the agent directory into the build context and generates a Dockerfile whose command starts adk api_server. The deployed process loads docs_helper.root_agent; it does not turn the agent into a separate Cloud Run service for each tool. docs_helper is both the application name passed to this deploy and the name used in the HTTP paths below. Changing the container port or instance count changes how the server is hosted, not the agent’s instruction or tools.
$ /private/tmp/docuctl-adk-venv/bin/adk deploy cloud_run --project vertex-ai-experminent --region us-central1 --service_name docuctl-lab-b67bf640 --app_name docs_helper --session_service_uri memory:// --env GOOGLE_CLOUD_PROJECT=vertex-ai-experminent --env GOOGLE_CLOUD_LOCATION=global --env GOOGLE_GENAI_USE_VERTEXAI=true docs_helper -- --no-allow-unauthenticated --service-account=docuctl-lab-b67bf640@vertex-ai-experminent.iam.gserviceaccount.com --min-instances=0 --max-instances=1 --cpu=1 --memory=512Mi --timeout=120 --concurrency=1 --labels=aiml-lesson=deploy-an-adk-agent-to-cloud-run
Start generating cloud_run source files in /var/folders/8q/3xqw2gjj54vbtxmv1hz753wr0000gn/T/deploy_src/20261025_222921
Copying agent source code...
Copying agent source code completed.
Creating Dockerfile...
Creating Dockerfile complete: /var/folders/8q/3xqw2gjj54vbtxmv1hz753wr0000gn/T/deploy_src/20261025_222921/Dockerfile
Deploying to cloud_run...
Cleaning up the temp folder: /var/folders/8q/3xqw2gjj54vbtxmv1hz753wr0000gn/T/deploy_src/20261025_222921
Building using Dockerfile and deploying container to Cloud Run service [docuctl-lab-b67bf640] in project [vertex-ai-experminent] region [us-central1]
Building and deploying new service...
Validating Service.......done
Uploading sources........INFO: Not using ignore file.
INFO: Uploading [/var/folders/8q/3xqw2gjj54vbtxmv1hz753wr0000gn/T/tmpz3v7re9n/file.zip] to [run-sources-vertex-ai-experminent-us-central1/services/docuctl-lab-b67bf640/1792981765.048481-d592f8ab2ba44ac4aab4df098fbee809.zip]
.done
Building Container.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................done
Creating Revision.........................................................................................................................................................................................................................................................................done
Routing traffic.....done
Done.
Service [docuctl-lab-b67bf640] revision [docuctl-lab-b67bf640-00001-v87] has been deployed and is serving 100 percent of traffic.
Service URL: https://docuctl-lab-b67bf640-913703049174.us-central1.run.app
INFO: Display format: "none"The source build creates an image and may create an upload bucket. Track those resources as well as the service. In this run, the image and the source objects, under a unique prefix, went into an existing shared image repository and upload bucket. Do not delete a shared repository or upload bucket just because a lesson command mentions its name.
2. Separate the caller from the runtime account
Without an identity token, the private service returned HTTP 403 before the agent ran. With the caller accepted, session creation succeeded, but the model request failed because the runtime service account lacked the model prediction permission. These are different requests under different principals.
# 1. Private service without an identity token
GET /list-apps
HTTP 403
# 2. A first temporary deployment lacked model permission
Session creation: HTTP 200
POST /run: HTTP 500
google.genai.errors.ClientError: 403 PERMISSION_DENIED. {'error': {'code': 403, 'message': "Permission 'aiplatform.endpoints.predict' denied on resource '//aiplatform.googleapis.com/projects/vertex-ai-experminent/locations/global/publishers/google/models/gemini-3.8-flash' (or it may not exist). Remediate access with this Troubleshooter URL or share it with your administrator - https://console.cloud.google.com/iam-admin/troubleshooter/summary;errorId=CiQwMWExNzYwNy1lYTBlLTc5OWMtYmQ1My05YTEwODFkNzJkMmQSWXByb2plY3RzL3ZlcnRleC1haS1leHBlcm1pbmVudC9sb2NhdGlvbnMvZ2xvYmFsL3B1Ymxpc2hlcnMvZ29vZ2xlL21vZGVscy9nZW1pbmktMy44LWZsYXNo .", 'status': 'PERMISSION_DENIED', 'details': [{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'IAM_PERMISSION_DENIED', 'domain': 'aiplatform.googleapis.com', 'metadata': {'permission': 'aiplatform.endpoints.predict', 'troubleshooter_url': 'https://console.cloud.google.com/iam-admin/troubleshooter/summary;errorId=CiQwMWExNzYwNy1lYTBlLTc5OWMtYmQ1My05YTEwODFkNzJkMmQSWXByb2plY3RzL3ZlcnRleC1haS1leHBlcm1pbmVudC9sb2NhdGlvbnMvZ2xvYmFsL3B1Ymxpc2hlcnMvZ29vZ2xlL21vZGVscy9nZW1pbmktMy44LWZsYXNo', 'error_info_id': 'CiQwMWExNzYwNy1lYTBlLTc5OWMtYmQ1My05YTEwODFkNzJkMmQSWXByb2plY3RzL3ZlcnRleC1haS1leHBlcm1pbmVudC9sb2NhdGlvbnMvZ2xvYmFsL3B1Ymxpc2hlcnMvZ29vZ2xlL21vZGVscy9nZW1pbmktMy44LWZsYXNo', 'resource': 'projects/vertex-ai-experminent/locations/global/publishers/google/models/gemini-3.8-flash'}}]}}
The first temporary deployment returned the recorded permission failure, and so did early retries after its role changed. The second deployment, which succeeded, granted roles/aiplatform.user to a dedicated account before the container build. That is a broad project role, used for this run; it is not a claim of minimum privilege. Treat a permission failure as a configuration problem: retrying the model call does not add the missing permission.
The caller’s identity token is for the Cloud Run service audience. The runtime account’s credentials are for its outbound calls, including the Gemini request through Vertex AI. Granting the caller permission to invoke Cloud Run does not grant the runtime account model access. Use the account approved for this agent and check its outbound permissions separately.
3. Create a session and call the agent
request.sh asks gcloud for an identity token, creates a session when SESSION is absent, and sends the message to /run. It allocates a per-process temporary response file and exits nonzero after a failed session creation or failed run:
#!/usr/bin/env bash
# Call the private Cloud Run service. Usage: SERVICE_URL=https://... ./request.sh "message"
set -euo pipefail
APP=docs_helper USER_ID=dana
TOKEN=$(gcloud auth print-identity-token)
BODY=$(mktemp)
trap 'rm -f "$BODY"' EXIT
call() { curl --fail-with-body -sS -o "$BODY" -w "HTTP %{http_code} in %{time_total} s\n" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" "$@"; }
SESSION=${SESSION:-}
if [ -z "$SESSION" ]; then
if ! call -X POST "$SERVICE_URL/apps/$APP/users/$USER_ID/sessions"; then cat "$BODY"; exit 1; fi
SESSION=$(jq -r .id "$BODY"); echo "session $SESSION"
fi
if ! call "$SERVICE_URL/run" -d "$(jq -n --arg a $APP --arg u $USER_ID --arg s "$SESSION" --arg m "$1" \
'{app_name: $a, user_id: $u, session_id: $s, run_config: {max_llm_calls: 4}, new_message: {role: "user", parts: [{text: $m}]}}')"; then cat "$BODY"; exit 1; fi
jq -r 'if type == "array" then .[] | .content.parts[]? |
if .functionCall then "call \(.functionCall.name) \(.functionCall.args|tojson)"
elif .functionResponse then "result \(.functionResponse.name)"
elif (.text and (.thought|not)) then "answer \(.text)" else empty end
else . end' "$BODY"After Cloud Run accepts the caller, the ADK API server handles two different operations. The session POST creates a conversation under /apps/docs_helper/users/{user_id}/sessions. The /run body names app_name, user_id and session_id and contains the new message. The server finds that session, obtains a Runner for the application, and calls run_async. The Runner drives the LlmAgent, executes its requested tools and yields Event objects. The session service records the non-partial events; the HTTP handler returns the collected events as a JSON list.
/run_sse instead frames events as server-sent events. That endpoint changes how the caller receives a turn; it does not make the local session store durable. For either endpoint, derive the ADK user ID from the caller’s authenticated application identity. Cloud Run authenticates access to the service; it does not decide which application user owns a supplied user_id.
curl exits 0 whenever the HTTP transport succeeds, even when the server returns HTTP 403 or 500. A shell client that ignores the status code hides those server errors. A client that writes every response to a fixed path such as /tmp/body.json lets concurrent callers overwrite each other’s responses. test_client.py runs request.sh against fake curl and gcloud executables to verify these failure paths offline:
Session creation fails. Stop before constructing the model request. The client prints the failed response and exits nonzero.
The agent request returns an HTTP error. Propagate failure to the calling script; a JSON error body is not an answer.
Two clients overlap. Each client uses its own response file, removed on exit.
test_a_failed_run_exits_nonzero (test_client.HttpClient.test_a_failed_run_exits_nonzero) ... ok
test_failed_session_creation_stops_before_the_model_request (test_client.HttpClient.test_failed_session_creation_stops_before_the_model_request) ... ok
test_simultaneous_clients_have_separate_response_files (test_client.HttpClient.test_simultaneous_clients_have_separate_response_files) ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.550s
OKThese offline tests do not check deployed IAM, revisions or session durability. The cloud recordings above show those, including their failures.
4. Choose a session store that survives replacement
For this deployment, adk deploy cloud_run selects memory:// when no session-service URI or local-storage override is supplied. That creates an InMemorySessionService in each server process. The recorded deploy used that local session storage. After the service moved to a new revision, a request naming the earlier session returned HTTP 404. A container’s filesystem and memory are not a shared, durable conversation store across instances or revisions.
A separate session store is a candidate fix for this loss of history; this lesson did not deploy or test one. To configure it, supply --session_service_uri before the deploy command’s -- separator. The agentengine:// service URI selects VertexAiSessionService; use the managed instance’s full resource name after the scheme, as in agentengine://projects/PROJECT/locations/REGION/reasoningEngines/INSTANCE. Session storage is then configured separately from the Cloud Run service that runs the agent. The runtime account needs access to that instance. The URI supplies its ID to VertexAiSessionService, so the API server can keep the docs_helper application name. The model’s global endpoint is also separate from the session service’s region. Test a session across replacement and across more than one instance before you rely on the store.
Why does my ADK session return 404 after a redeploy?
The recorded deploy kept sessions in memory://, the default when no session-service URI is supplied. Each server process then holds its own InMemorySessionService, and a container’s memory does not carry over to a new revision. In the recorded run, a GET for the earlier session after the revision change returned HTTP 404 with {"detail": "Session not found"}. The --session_service_uri agentengine://... store described above is a candidate fix; this lesson did not deploy or test it.
Clean up resources you created
After recording, the temporary services, images, source objects and dedicated accounts were removed; the existing shared upload bucket and image repository were kept. The saved teardown covers this exercise only; do not reuse it as a bulk-delete script. For your own deployment, compare each resource with the inventory from your create step, remove the service first, and remove an image, bucket or account only when this exercise created it and nothing else uses it.
What’s next
Return to the API-server lesson when debugging the application’s HTTP behavior separately from its cloud identity and hosting layer.
Read the docs assistant
"""The docs assistant on Gemini Enterprise Agent Platform: Gemini through Vertex, recall through Memory Bank."""
import os
from pathlib import Path
from google.adk import Agent
from google.adk.models.google_llm import Gemini
from google.adk.tools import load_memory
from google.genai import types
DOCS = Path(__file__).resolve().parent / "docs"
PAGES = sorted(p.stem for p in DOCS.glob("*.md"))
# The recorded run uses global for this model. Sessions and Memory Bank stay regional
# (GOOGLE_CLOUD_LOCATION), so the model client gets its own location.
MODEL_LOCATION = os.environ.get("DOCS_MODEL_LOCATION", "global")
def read_page(page: str) -> dict:
"""Read one page of the docuctl documentation: config, deploy, rollback or tokens."""
if page not in PAGES:
return {"error": f"No page {page!r}. Pages: {', '.join(PAGES)}."}
return {"page": page, "text": (DOCS / f"{page}.md").read_text(encoding="utf-8")}
INSTRUCTION = """You answer questions from developers about docuctl, the team's deploy CLI.
Read the relevant page with read_page before you answer. Answers depend on the developer's
docuctl major version (1.x or 2.x). If the developer has not said it in this conversation,
call load_memory to look for it in earlier conversations before you ask. Keep the answer
under 80 words."""
root_agent = Agent(
name="docs_helper",
model=Gemini(model="gemini-3.8-flash", client_kwargs={"location": MODEL_LOCATION}),
instruction=INSTRUCTION,
tools=[read_page, load_memory],
generate_content_config=types.GenerateContentConfig(
temperature=0.2, max_output_tokens=1024, thinking_config=types.ThinkingConfig(thinking_level="low")),
)Check your understanding
Read the explanation
Caller invocation permission and the container’s outbound model permission belong to different principals. Check the runtime account separately.
References
Official documentation and installed ADK deployment flags checked October 22, 2026.