Deploy an authenticated ADK agent to Cloud Run
Deploy the agent as one authenticated Cloud Run service with its own service identity, managed credentials, health checks, persistent sessions and rollback.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.
In short
Cloud Run runs your ADK agent as a container that scales with traffic, and ADK can build and deploy it for you with adk deploy cloud_run or you can deploy your own FastAPI entry point with gcloud run deploy. A production setup is private (callers need an identity token), runs as its own service account with only the roles it needs, reads secrets from Secret Manager and keeps sessions in a database rather than in container memory. Every deploy creates a new revision, so rolling back means sending traffic to the previous one.
Think of it like this: Cloud Run is a locked office with a staff badge reader: only people with a badge get in, and the agent inside has its own badge that opens only the rooms it needs.
Explained simply
So far the agent runs on your laptop. To let others use it, you put it on a server that is always reachable. Cloud Run is a Google Cloud service that takes your code, packs it into a container (a sealed box with your code and everything it needs) and runs as many copies as traffic needs, down to zero when nobody calls.
Being reachable is not the same as being public. You want only your own front end or teammates to call the agent. Cloud Run can require a signed identity token on every request and reject everyone else before your code even runs.
The agent also needs its own identity to call Gemini and its database. Instead of using your personal login or a broad default account, you create a service account just for the agent and give it only the permissions it needs.
Finally, conversations must survive restarts. Containers come and go, so sessions go into a database. And because every deploy creates a new numbered revision, you can always send traffic back to the last good one in seconds. Cloud Run, Cloud SQL and Gemini calls are paid services with free tiers; to practise without a bill, run the same container locally with Docker and SQLite.
Press Play on a diagram to walk through it one step at a time.
- Caller to Cloud Run: POST /run_sse with Bearer identity token1POST /run_sse with Bearer identity token
- 2IAM check: caller has roles/run.invokerCloud Run to Cloud Run: IAM check: caller has roles/run.invoker
- Cloud Run to ADK agent: Forward request to a container instance3Forward request to a container instance
- ADK agent to Cloud SQL / Gemini: Load session; call model as the service account4Load session; call model as the service account
- Cloud SQL / Gemini to ADK agent: Session events and model reply5Session events and model reply
- ADK agent to Caller: Stream events back as SSE6Stream events back as SSE
- 1Enable APIs
Run, Cloud Build, Agent Platform, Secret Manager, Cloud SQL Admin
- 2Create identity
support-agent-sa with least-privilege roles
- 3Store secret
Session DB URL in Secret Manager
- 4Deploy
gcloud run deploy --source, private, own service account
- 5Smoke test
Identity token, /list-apps, one /run_sse call
- 6Record revision
Note the name for rollback
In depth
Two ways to deploy
The quick way is adk deploy cloud_run, which generates a Dockerfile and a FastAPI entry point, builds the image and deploys it. It needs --project and --region and the agent folder, and accepts --service_name, --session_service_uri, --artifact_service_uri and --with_ui (which also ships the dev web UI; leave it off in production). Anything after a lone -- is passed to gcloud, for example -- --no-allow-unauthenticated. If you do not pass it, the CLI may ask whether to allow unauthenticated invocations; the default answer N keeps the service private.
The controlled way is your own main.py that calls get_fast_api_app from google.adk.cli.fast_api, a Dockerfile, a pinned requirements file and gcloud run deploy --source. This lets you add a health route, read the session URL from a secret and pin google-adk==2.15.1. Use it for anything you will maintain.
- adk deploy cloud_run: fast, generated files
- gcloud run deploy --source: your own main.py and Dockerfile
- Leave --with_ui off in production
- Default service port from adk deploy is 8000; your own image should read PORT
Identity: who may call, and who the agent is
There are two identities. The caller's identity decides who may invoke the service. With --no-allow-unauthenticated, Cloud Run checks that the caller holds roles/run.invoker on the service and presents a Google-signed identity token. A developer gets one from gcloud auth print-identity-token; a backend running on Google Cloud fetches one for its own service account with the service URL as the audience.
The agent's identity is the service account the container runs as, set with --service-account. Create one per agent, such as support-agent-sa, and grant it roles/aiplatform.user to call Gemini on Agent Platform, roles/cloudsql.client for the session database, and roles/secretmanager.secretAccessor only on the secrets it reads. No keys are downloaded: the container gets short-lived credentials from the metadata server automatically.
- Callers
- roles/run.invoker on the service only
- Front-end backend's own service account
- support-agent-sa (runtime)
- roles/aiplatform.user
- roles/cloudsql.client
- secretAccessor on session-db-url only
- Deployer
- roles/run.sourceDeveloper
- roles/iam.serviceAccountUser on support-agent-sa
Sessions, secrets and health
If you do not give a session service URI, the server uses in-memory sessions, and every restart or new instance starts empty. Use DatabaseSessionService through a SQLAlchemy URL with an async driver, for example postgresql+asyncpg with Cloud SQL for PostgreSQL. Connect over the Cloud SQL Unix socket by adding --add-cloudsql-instances, and put the full URL, which contains the database password, in Secret Manager. Mount it with --set-secrets SESSION_DB_URL=session-db-url:latest so it arrives as an environment variable.
Cloud Run checks a new instance before sending it traffic. By default this is a TCP startup probe on the port. Add a small HTTP route such as /healthz in main.py and configure it as the startup probe in the service settings, so an instance that cannot start the app gets no traffic. Keep the probe cheap: no model calls.
- memory:// sessions are lost on restart
- postgresql+asyncpg URL from Secret Manager
- --add-cloudsql-instances for the socket
- Health route must not call the model
Revisions and rollback
Every deploy or configuration change creates a new revision with a name such as support-agent-00012-abc. By default the newest healthy revision gets all traffic. Old revisions stay available, so rollback is a traffic change, not a rebuild: gcloud run services update-traffic support-agent --to-revisions support-agent-00011-xyz=100. List revisions with gcloud run revisions list --service support-agent.
Rollback restores code and settings, but not data. If a new version changed how it writes state, for example new keys in session state, the old version must still read those sessions. Keep state changes backward compatible for at least one release, and test the rollback before you need it.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Build and deploy the service~50m
- 2Require authenticated invocations~50m
- 3Run as a dedicated service account~50m
- 4Store sessions outside the container~50m
- 5Roll back to a previous revision~50m
Key points
- Deploy with --no-allow-unauthenticated; callers then need roles/run.invoker and an identity token.
- Create a dedicated service account and grant it only roles/aiplatform.user plus access to the secrets and database it uses.
- Put the database URL and any API key in Secret Manager and mount them with --set-secrets, never in the image or source.
- Without a session service URI the container keeps sessions in memory, and they vanish when an instance stops.
- Each deploy is a new revision; gcloud run services update-traffic moves traffic back in seconds.
Key terms
Tap a card to flip it. 0/6 known
Examples
gcloud run deploy support-agent --source . --region europe-west1 \
--no-allow-unauthenticated \
--service-account support-agent-sa@<project-id>.iam.gserviceaccount.com \
--set-secrets SESSION_DB_URL=session-db-url:latest \
--add-cloudsql-instances <project-id>:europe-west1:support-sessions \
--set-env-vars GOOGLE_GENAI_USE_ENTERPRISE=TRUE,GOOGLE_CLOUD_PROJECT=<project-id>,GOOGLE_CLOUD_LOCATION=europe-west1
TOKEN=$(gcloud auth print-identity-token)
curl -H "Authorization: Bearer $TOKEN" "$SERVICE_URL/list-apps"Private service, own identity, secret-backed session database, then an authenticated smoke test.
A maintainable main.py for Cloud Run
Prerequisites: the agent package support_agent in the same folder, google-adk==2.15.1 and asyncpg in requirements. Step 1: build the FastAPI app with get_fast_api_app, reading the session URL from the environment so the secret never sits in code. Step 2: add a cheap health route. Step 3: in the Dockerfile, start it with uvicorn main:app --host 0.0.0.0 --port $PORT so it listens on the port Cloud Run provides. Expected evidence: locally with SESSION_DB_URL=sqlite+aiosqlite:///./sessions.db, GET /healthz returns ok and /list-apps lists support_agent.
import os
from google.adk.cli.fast_api import get_fast_api_app
app = get_fast_api_app(
agents_dir=os.path.dirname(os.path.abspath(__file__)),
session_service_uri=os.environ["SESSION_DB_URL"],
allow_origins=["https://support.example.com"],
web=False,
)
@app.get("/healthz")
def healthz():
return {"status": "ok"}Smoke test, then clean up
Step 1: get an identity token and create a session for a test user. Step 2: send one message to /run_sse with streaming off and check that the final event contains an answer about T-1001. Step 3: confirm in Cloud SQL or by fetching the session that it persisted. Cleanup when practising: delete the service, the secret and the Cloud SQL instance so nothing keeps billing. Rollback instead of cleanup in a real project: send traffic to the previous revision.
TOKEN=$(gcloud auth print-identity-token)
H="Authorization: Bearer $TOKEN"
curl -X POST -H "$H" "$SERVICE_URL/apps/support_agent/users/user-a/sessions/s-1"
curl -X POST -H "$H" -H "Content-Type: application/json" "$SERVICE_URL/run_sse" -d '{
"app_name": "support_agent", "user_id": "user-a", "session_id": "s-1",
"new_message": {"role": "user", "parts": [{"text": "Status of T-1001?"}]},
"streaming": false}'
# cleanup (practice project only)
gcloud run services delete support-agent --region europe-west1
gcloud secrets delete session-db-url
gcloud sql instances delete support-sessionsQuick reference
- Private service: --no-allow-unauthenticated; callers need roles/run.invoker
- Own identity: --service-account support-agent-sa@PROJECT_ID.iam.gserviceaccount.com
- Secrets: --set-secrets SESSION_DB_URL=session-db-url:latest
- Sessions: async SQLAlchemy URL such as postgresql+asyncpg or sqlite+aiosqlite
- Smoke test: curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" URL/list-apps
- Rollback: gcloud run services update-traffic SERVICE --to-revisions REV=100
- adk deploy cloud_run passes flags after -- straight to gcloud
Common mistakes
- Answering y to the allow unauthenticated prompt, which makes the agent and your model bill public.
- Leaving the default compute service account in place, which usually has far broader rights than the agent needs.
- Testing with one instance and in-memory sessions, then losing conversations when Cloud Run scales or restarts.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a dedicated service account for the agent and grant it permission to call Gemini on Agent Platform.
- Exercise 2medium
Store the session database URL as a secret and let only the agent's service account read it.
- Exercise 3hard
Write a rollback runbook for the agent service, including how to check that old code can still read new sessions.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need to write a Dockerfile?
- Not with adk deploy cloud_run or gcloud run deploy --source, which build one for you. Write your own when you need pinned versions, a non-root user or a custom health route.
- Why does my curl call return 403?
- The service is private and the request has no valid identity token, or your account lacks roles/run.invoker on the service. Add the Bearer token from gcloud auth print-identity-token.
- Can I use SQLite for sessions on Cloud Run?
- Only for experiments. The file lives in the instance's memory-backed file system, so it is lost on restart and not shared between instances.
- Can I practise without paying?
- Run the same container locally with Docker and a SQLite session URL. Cloud Run has a free tier, but Cloud SQL and Gemini calls are billed.