DEV Community

Cover image for AlloyDB Express to Production HA: Prototyping Agent Apps with MCP Toolbox and ADK

AlloyDB Express to Production HA: Prototyping Agent Apps with MCP Toolbox and ADK

Provision PostgreSQL 18 in seconds with scale-to-zero, split coding-agent access across Remote MCP and local MCP Toolbox, keep Cloud Run connectors alive with lazy refresh, and graduate to 99.99% HA without changing a connection string.

Series: A five-part, hands-on engineering series for builders taking PostgreSQL and AI agent workloads from first prototype to exit-ready production on Google Cloud AlloyDB. Part 1 covers AlloyDB Express provisioning, dual MCP planes for coding agents, ADK on Cloud Run, and the one-way upgrade to Regional HA. Part 2 builds hybrid RAG with ScaNN vs. HNSW indexes, filtered vector search, Reciprocal Rank Fusion, and two-layer RAG evaluation. Part 3 hardens autonomous database agents with five-gate IAM, Model Armor, AI Query Engine smart batching, and OpenTelemetry trace diagnostics. Part 4 scales HTAP with disaggregated WAL storage, the Columnar Engine, managed connection pooling, and zero-ETL Iceberg and BigQuery pipelines. Part 5 validates portability with PSA vs. PSC networking, zero-downtime migration, cross-region disaster recovery, and CI/CD exit gates.

This is Part 1.

The problem: prototypes stall on infrastructure, or break on graduation

When you start an AI agent prototype, you want a real PostgreSQL 18 database with pgvector and ScaNN vector search in seconds, not a 10-minute cluster provisioning wait and an always-on 8 vCPU bill while your laptop is closed. At the same time, two shortcuts routinely derail prototypes before they ever reach production.

First, developers wire a coding agent or LLM directly to the database with a raw connection string or an unrestricted execute_sql tool, exposing multi-tenant tables to prompt injection, unbounded queries, and connection exhaustion. Second, when traffic arrives on Cloud Run, the default Python connector spins up a background certificate-refresh loop that starves under request-based CPU throttling and fails on the second request with an mTLS error. Worse, when your database hits prototype caps, moving off a sandbox tier often forces a dump-and-restore migration and new connection strings.

AlloyDB Express (Preview) eliminates that false choice between throwaway local databases and heavy production clusters, provided you understand its hard guardrails, its dual Model Context Protocol (MCP) planes, and the exact mechanics of its serverless connectors and one-way HA upgrade.

Be clear on provenance before running anything below: this post was written from the official AlloyDB product documentation and the Google Cloud agentic architecture reference set, without executing commands against a live Google Cloud project. Every gcloud flag, REST endpoint, MCP tool name, IAM role, database flag, regional constraint, and Python API signature comes verbatim from those documents. Any sample SQL responses or schema examples are illustrative syntax templates, not captured cluster telemetry.

What you'll be able to do

By the end of this guide, mapped across Bloom's taxonomy from recall to system construction, you will be able to:

  • Identify AlloyDB Express specifications, its 7 supported regions, the 12-month monthly free tier, locked GUC flags (max_connections=200), and the 17 Remote MCP tools versus the 30 Gemini CLI alloydb extension tools.
  • Explain how Express scale-to-zero and auto-resume work, how tools.yaml isolates LLM reasoning from raw SQL, and why refresh_strategy="background" fails under Cloud Run CPU throttling.
  • Configure an Express cluster via gcloud, REST, or Remote MCP, connect Antigravity (serverUrl vs. command) and Gemini CLI (alloydb + alloydb-observability), and wire an ADK agent on Cloud Run with refresh_strategy="lazy".
  • Diagnose four silent failure modes: non-C4A 1-vCPU upgrade rejections, legacy httpUrl / url fields in mcp_config.json, multi-tenant leaks from bare execute_sql, and expired mTLS certificates in throttled Cloud Run containers.
  • Decide between keeping 1 vCPU, resizing in place to 2 vCPUs (--cpu-count=2), spinning up a 30-day 8-vCPU free trial cluster, or executing the irreversible --no-enable-express upgrade to Production HA.
  • Build a prototype stack combining AlloyDB Express, declarative tools.yaml in Secret Manager, and an ADK agent on Cloud Run ready for zero-code-change production graduation.

Setup

To run the commands in this post against your own environment, you need:

  • A Google Cloud project with billing enabled and the AlloyDB API (alloydb.googleapis.com) active. If you plan to use Private Service Connect (PSC) or VPC connectivity, also enable compute.googleapis.com, cloudresourcemanager.googleapis.com, and servicenetworking.googleapis.com.
  • Google Cloud CLI (gcloud) with the beta component installed (gcloud beta alloydb ... commands are required for --enable-express, --no-enable-express, and gcloud beta alloydb connect), or Cloud Shell.
  • Python 3.11 or later for Agent Development Kit (ADK) and google-cloud-alloydb-connector (pg8000 or asyncpg).
  • Node.js (for npx -y @toolbox-sdk/server) or the standalone MCP Toolbox for Databases binary (toolbox v0.15.0 or later), plus Gemini CLI (gemini) or Antigravity if you are wiring coding agents.
  • Application Default Credentials (gcloud auth application-default login) and the minimum IAM roles for your persona: roles/alloydb.admin for cluster lifecycle, roles/alloydb.client plus roles/serviceusage.serviceUsageConsumer for connector and proxy access, and roles/mcp.toolUser for the AlloyDB Remote MCP server.

Part A: The AlloyDB Express mental model, from 2-second boot to 1-way HA exit

Three tiers compared: Express vs. Free Trial vs. Standard AlloyDB

Most teams confuse AlloyDB Express with the older 30-day AlloyDB free trial cluster. They solve completely different problems.

End-to-end architecture showing Developer Workstation coding agents connecting via stdio to Local MCP Toolbox and via Streamable HTTP to the Remote MCP Control Plane, Application Users hitting an ADK Cloud Run app with lazy mTLS and Vertex AI, and AlloyDB Express upgrading in-place to Standard AlloyDB HA

Walk the numbers in order: Steps 1 and 3 route coding agents through the Local MCP Data Plane; Steps 2 and 4 route through the Remote MCP Control Plane; Steps 5 and 6 govern runtime user traffic through ADK and Cloud Run; Step 7 executes the one-way graduation to HA.

As the architecture diagram shows, AlloyDB Express sits inside your chosen region alongside your serverless ADK runtime and serves as the drop-in predecessor to Standard AlloyDB HA. Compare all three options before you pick a region or create a cluster:

Capability AlloyDB Express (Preview) AlloyDB Free Trial Cluster Standard AlloyDB (Production HA)
Primary use case Rapid prototyping, dev, and AI coding-agent workflows 30-day evaluation of 8-vCPU enterprise capabilities Full production transactional, analytical, and agent workloads
Provisioning time ~2 seconds (Public DNS) or ~20 seconds (PSC) Within a few minutes Within a few minutes
Compute shape 1 vCPU (4 GB) or 2 vCPU (8 GB) zonal primary (1:4 RAM) Fixed 8 vCPU zonal primary + max 1 read pool (8 vCPU) Up to 288 vCPU primary (1:8 RAM) + up to 20 read pool nodes
Provisioned behavior Scales to zero on idle ($0 idle compute, ~20s resume) Always provisioned for 30 days (+15-day grace period) Always provisioned
Storage limit Auto-scales up to 20 GB (writes blocked at 20 GB) Auto-scales up to 1 TB Auto-scales up to 128 TiB (16 TiB default quota)
High availability & DR None (zonal primary only; no read pools or CRR) None (no HA, no CRR, no backup/restore) Regional HA auto-failover; up to 5 cross-region secondary clusters
Backups & SLA No backups, no PITR, no SLA No backups, no SLA (one final backup on expiry) Continuous PITR, automated/on-demand backups, 99.99% HA SLA
PostgreSQL versions PostgreSQL 18 only Standard AlloyDB supported versions PostgreSQL 14, 15, 16, 17, and 18
Connectivity Public DNS and Private Service Connect (no public IP) Private services access / standard cluster networking Public IP, Private Service Connect, and private services access
Pricing & free tier Usage-based per second; 50 CUs + 2 GB/mo free for 12 months; no CUDs $0 cluster/instance compute for 30 days (egress and final backup billed) Hourly compute + used storage; 1-year and 3-year CUDs apply
Supported regions 7 regions: asia-east1, asia-east2, asia-northeast1, asia-southeast1, australia-southeast1, europe-west2, us-west1 10 trial regions (includes us-central1, europe-west1, europe-west4, etc.) Broad AlloyDB regional catalog
Automation & exit Console, gcloud, REST, Remote MCP (no Terraform); 1-way upgrade 1 per project lifecycle; instant upgrade to paid (2 to 128 vCPU) Console, gcloud, REST, Terraform, Config Connector; no downgrade to Express

Two details in that table save real surprises later. First, Express runs PostgreSQL 18 exclusively and includes full AlloyDB AI capabilities even at 1 vCPU (4 GB RAM): ScaNN vector search, the vector (pgvector) extension, natural language query generation, and SQL functions to generate embeddings and invoke Gemini models. Second, the free tier gives each billing account 50 compute units (CUs) and 2 GB of storage per month for the first 12 months. A 1 vCPU instance consumes 1 CU per active hour (billed per second), while a 2 vCPU instance consumes 2 CUs per active hour. Idle time burns zero CUs, though stored data up to the 20 GB cap continues to accrue storage charges beyond the 2 GB monthly free allowance.

Provisioning, scale-to-zero, and locked guardrails

Predict before you look: you create an AlloyDB Express cluster using gcloud beta alloydb clusters create --enable-express and immediately create its primary instance with --cpu-count=2 to give vector index builds extra RAM. What happens, and which connectivity path is open by default?

Six-step AlloyDB Express operational lifecycle from cluster and 1-vCPU primary creation through postgres bootstrap, active 1-to-2 vCPU queries, scale-to-zero at $0 idle compute, ~20-second auto-resume with minor patching, and irreversible graduation to Standard AlloyDB HA

Step 1 enforces cpuCount=1 on creation; Step 3 allows resizing to 2 vCPUs; Steps 3 to 5 loop automatically on idle timeouts and incoming queries until Step 6 graduates the cluster.

Two creation traps catch first-time gcloud and REST users off guard:

  1. Creation requires --cpu-count=1. Specifying any CPU count other than 1 when creating an AlloyDB Express primary instance fails. Create it at 1 vCPU (4 GB RAM) first, then resize to 2 vCPUs (8 GB RAM) in Step 3 if your workload needs more memory.
  2. Default connectivity depends on the tool you used. Creating an Express cluster in the Google Cloud console turns on both Public DNS on the primary instance and Private Service Connect (PSC) on the cluster. Creating via gcloud, the REST API, or the AlloyDB Remote MCP server turns on only PSC at the cluster level by default, leaving Public DNS off (publicDnsEnabled: false) until you explicitly enable it on the instance.

Here is the gcloud beta sequence to provision an Express cluster with both Public DNS and an allowlisted PSC consumer project:

# 1. Create the AlloyDB Express cluster (PostgreSQL 18, PSC enabled by default)
gcloud beta alloydb clusters create express-agent-cluster \
    --region=europe-west2 \
    --password="CHANGE_TO_STRONG_PASSWORD" \
    --enable-express \
    --project=PROJECT_ID

# 2. Create the zonal primary instance (must start with --cpu-count=1)
gcloud beta alloydb instances create express-primary \
    --cluster=express-agent-cluster \
    --region=europe-west2 \
    --instance-type=PRIMARY \
    --cpu-count=1 \
    --enable-public-dns \
    --allowed-psc-projects=PROJECT_ID \
    --project=PROJECT_ID
Enter fullscreen mode Exit fullscreen mode

Wait roughly 2 seconds for Public DNS or 20 seconds for PSC endpoints to accept connections. In Step 2 of the lifecycle diagram, AlloyDB initializes the default postgres user (with password complexity enforcement on by default) and the default postgres database. If you provision via the Remote MCP server's create_instance tool instead of gcloud, the tool omits cpu_count (defaulting to 1 vCPU / 4 GB), leaves public_dns_enabled as false unless specified, and automatically turns on data_api_access: ENABLED and db_iam_authentication: true.

Once idle, Express scales compute down to zero ($0 compute charges). When a new client connection or SQL query arrives, the instance resumes in roughly 20 seconds across both Public DNS and PSC, and Google applies minor PostgreSQL 18 version updates and security patches automatically during wake-up or low-usage windows.

To keep a 4 GB or 8 GB node from crashing with out-of-memory (OOM) errors, Express locks five database flags regardless of what you pass in --database-flags:

  • max_connections is fixed at 200 (updates to this flag have no effect).
  • google_plan_management.managed_plans_pool_size_in_mb is fixed at 10.
  • google_columnar_engine.memory_size_in_mb is fixed at 400.
  • google_columnar_engine.enable_auto_columnarization is fixed at false.
  • google_db_advisor.enable_columnar_advisor is fixed at false.

Because Express supports all AlloyDB PostgreSQL extensions, loading heavy extensions or building large indexes on a 1 vCPU / 4 GB node can still hit OOM. When that happens and your storage remains under 20 GB, scale in place to 2 vCPUs / 8 GB:

gcloud alloydb instances update express-primary \
    --cluster=express-agent-cluster \
    --region=europe-west2 \
    --cpu-count=2 \
    --project=PROJECT_ID
Enter fullscreen mode Exit fullscreen mode

Part B: Wiring coding agents through dual MCP planes (Antigravity and Gemini CLI)

Skills, rules, hooks, and MCP servers are four distinct axes

Before wiring a coding agent to AlloyDB, separate the four extension mechanisms documented in the Antigravity and Agent Platform architecture so you never solve a reachability problem with prose or an enforcement problem with a prompt:

Mechanism Role in coding agent Loading / enforcement
MCP server Supplies live external context (schemas, metrics) and executable actions (create_cluster, execute_sql) Local stdio (command) or remote HTTP (serverUrl)
Skill (SKILL.md) Teaches multi-step procedures (such as running database migrations or scaffolding ADK apps) Progressive disclosure: only name and third-person keyword description load at startup; invoke explicitly with /<skill-name>
Rule (AGENTS.md / .agents/rules/*.md) States coding invariants and constraints (for example, "never drop a column in one deploy") Advisory model-mediated context; rules in .agents/rules/*.md require YAML frontmatter with snake_case trigger (always_on, model_decision, glob, manual) or they are silently discarded
Hook (hooks.json) Runs deterministic shell commands at PreToolUse, PostToolUse, PreInvocation, PostInvocation, or Stop Code execution outside model discretion; cannot be bypassed by prompts

When your agent needs to inspect PostgreSQL tables or provision an Express cluster, that is an MCP server job. And for AlloyDB, there are two distinct MCP planes with very different security and performance properties.

Dual MCP topology connecting Antigravity IDE/CLI/SDK and Gemini CLI to the Google-managed AlloyDB Remote MCP Control Plane (17 tools over stateless Streamable HTTP 2026-07-28 with OAuth 2.0 and optional Model Armor) and the self-hosted MCP Toolbox / Gemini CLI Data Plane (pooled PostgreSQL wire protocol on port 5432)

Keep the split clear across Steps 1 to 5: Steps 1 and 4 route Antigravity control-plane lifecycle and Data API calls through Google's managed HTTPS endpoint; Steps 2, 3, and 5 route application SQL and observability through local or Cloud Run MCP Toolbox and Gemini CLI extensions.

Control plane: AlloyDB Remote MCP Server (17 tools)

The AlloyDB Remote MCP server is enabled automatically when you enable alloydb.googleapis.com. It exposes a global Streamable HTTP endpoint (https://alloydb.googleapis.com/mcp) and regional Preview endpoints (https://alloydb.REGION_ID.rep.googleapis.com/mcp) implementing the stateless MCP version 2026-07-28 core (header-routed via MCP-Protocol-Version and x-mcp-header with no session handshake or Mcp-Session-Id).

Three operational details matter here:

  1. OAuth 2.0 and IAM only (no API keys). Callers need roles/mcp.toolUser plus resource roles (roles/alloydb.admin to create clusters/instances/users, roles/alloydb.databaseUser or roles/alloydb.admin to run execute_sql, and roles/alloydb.viewer for read-only inspection and execute_sql_read_only on PG 17+). Reserve roles/alloydb.client for Data Plane connectors, Auth Proxy, and MCP Toolbox; Remote MCP calls check roles/alloydb.admin, roles/alloydb.databaseUser, or roles/alloydb.viewer alongside roles/mcp.toolUser. The OAuth scope is https://www.googleapis.com/auth/alloydb.
  2. Exact 17-tool catalog and guardrails. The remote server exposes list_clusters, create_cluster, get_cluster, list_instances, restore_cluster, create_backup, create_instance, get_instance, update_instance, create_user, get_user, list_users, execute_sql, execute_sql_read_only, export_data, import_data, and get_operation. Notice two hard limits: create_user only creates IAM-based users (no built-in password users), and execute_sql truncates responses larger than 10 MB. Also note that executing SQL through the Remote MCP server sends traffic across the internet (via Google's HTTPS endpoint and Data API) even if your instance only uses a private IP.
  3. Optional Model Armor protection. You can wrap remote MCP calls with Model Armor floor settings (--google-mcp-server-enforcement-type=INSPECT_AND_BLOCK) to scan prompts and responses, though Google advises enabling prompt-injection filters only when MCP traffic carries natural language data, and warns that enabling Model Armor logging logs the full payload.

You can verify the remote tool catalog without even authenticating (tools/list requires no auth):

curl -X POST https://alloydb.googleapis.com/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2026-07-28' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
Enter fullscreen mode Exit fullscreen mode

Data plane: Local MCP Toolbox and Gemini CLI (alloydb + observability)

For low-latency application SQL, offline local testing, built-in user authentication, or VPC-private connection pooling over PostgreSQL wire port 5432, you use the open-source MCP Toolbox for Databases (@toolbox-sdk/server or the toolbox v0.15.0+ Go binary) or the Gemini CLI alloydb extension.

Gemini CLI integrates directly with two extensions:

  • alloydb (gemini extensions install https://github.com/gemini-cli-extensions/alloydb): bundles 30 tools across database operations (13 tools including database_overview, list_tables, execute_sql, get_query_plan, list_locks), resource management (10 tools including create_cluster, create_instance, create_user for both built-in and IAM users, wait_for_operation), and health/maintenance (7 tools including list_top_bloated_tables, list_invalid_indexes, long_running_transactions). It uses ADC by default, or ALLOYDB_POSTGRES_USER / ALLOYDB_POSTGRES_PASSWORD, and supports ALLOYDB_POSTGRES_IP_TYPE="private".
  • alloydb-observability: exposes get_system_metrics and get_query_metrics. When using MCP Toolbox's prebuilt alloydb-postgres-observability config in an IDE, you gain 5 deeper insights tools (get_advanced_aggregated_query_stats, get_advanced_aggregated_wait_event_stats, get_advanced_time_series_query_stats, get_advanced_time_series_wait_event_stats, and get_index_recommendations), requiring roles/monitoring.viewer and roles/databaseinsights.viewer.

Configuring Antigravity and Claude Code without the httpUrl trap

Predict before you look: you add the AlloyDB Remote MCP server to your repository's .agents/mcp_config.json in Antigravity using "httpUrl": "https://alloydb.googleapis.com/mcp", restart the CLI, and nothing connects. Why?

In Antigravity (~/.gemini/config/mcp_config.json globally, or .agents/mcp_config.json per workspace, which the Antigravity Python SDK also auto-discovers), every server entry must declare exactly one of two transport keys: command for local stdio servers or serverUrl for remote Streamable HTTP / SSE endpoints. Legacy keys like url or httpUrl are not supported and fail silently. In Antigravity CLI, run /mcp to inspect live status rings, view connection logs, and reload configs.

Here is a valid workspace .agents/mcp_config.json wiring both planes simultaneously (Step 1 Remote Control Plane + Step 2 Local Data Plane):

{
  "mcpServers": {
    "alloydb-remote-control": {
      "serverUrl": "https://alloydb.googleapis.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_OAUTH_ACCESS_TOKEN"
      }
    },
    "alloydb-postgres": {
      "command": "npx",
      "args": ["-y", "@toolbox-sdk/server", "--prebuilt", "alloydb-postgres", "--stdio"],
      "env": {
        "ALLOYDB_POSTGRES_PROJECT": "PROJECT_ID",
        "ALLOYDB_POSTGRES_REGION": "europe-west2",
        "ALLOYDB_POSTGRES_CLUSTER": "express-agent-cluster",
        "ALLOYDB_POSTGRES_INSTANCE": "express-primary",
        "ALLOYDB_POSTGRES_DATABASE": "postgres",
        "ALLOYDB_POSTGRES_USER": "postgres",
        "ALLOYDB_POSTGRES_PASSWORD": "YOUR_PASSWORD"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

For Claude Code, place the local MCP Toolbox configuration in .mcp.json at the project root using the downloaded toolbox binary (./PATH/TO/toolbox with ["--prebuilt", "alloydb-postgres", "--stdio"]), and optionally pair it with uvx google-agents-cli setup (which installs agents-cli, ADK Python packages, and 7 ADK lifecycle skills into Antigravity, Claude Code, or Codex). Keep database invariants (like CONCURRENTLY index creation) in .agents/rules/alloydb-migrations.md using snake_case trigger: model_decision, and multi-step setup checklists in .agents/skills/alloydb-express-setup/SKILL.md:

---
name: alloydb-express-setup
description: "Provisions AlloyDB Express clusters, configures least-privilege IAM and database roles, and validates MCP Toolbox toolsets. Use when setting up or upgrading AlloyDB Express prototypes."
---

# AlloyDB Express Prototype Workflow
1. Verify region supports C4A if 1-vCPU in-place HA upgrade is planned (`asia-east1`, `asia-southeast1`, `europe-west2`).
2. Create cluster with `--enable-express`, then primary instance with `--cpu-count=1`.
3. Create a dedicated read-only PostgreSQL role before exposing tables via `tools.yaml`.
Enter fullscreen mode Exit fullscreen mode

Part C: Securing the agent data plane with declarative tools.yaml and ADK

Why prebuilt execute_sql breaks in multi-tenant production

A coding assistant on your laptop benefits from open-ended execute_sql when you are exploring schemas. An end-user customer-facing ADK agent does not. The Google Cloud secure-MCP guidance calls direct LLM-to-database SQL generation an unacceptable risk across three vectors: SQL injection, data exfiltration, and operational inefficiency (runaway queries or connection floods).

Consider a multi-tenant Orders table where your agent's service account has read permission across the whole table. If you only give the agent execute_sql and tell it in the system prompt "only query the logged-in user's orders", a prompt injection attack can override that instruction and dump every customer's rows.

The production pattern is the Action-Selector pattern implemented through custom MCP Toolbox for Databases declarations in tools.yaml. Instead of letting the LLM write SQL, you declare pre-approved, parameterized SQL queries where sensitive filters (or tenant IDs passed by your application backend) are bound outside prompt control.

tools.yaml organizes access into three sections:

  1. sources: names each database backend (using kind: alloydb-postgres inside a sources: block, or type: alloydb-postgres beneath kind: source in flat resource configs, with project, region, cluster, instance, database) and references credentials via runtime environment substitution (${SECRET_ALLOYDB_PASSWORD}), never hardcoded strings.
  2. tools: defines each named function, its LLM-facing description, target source, parameters, and parameterized statement. Note the syntax rule across databases: AlloyDB (PostgreSQL) uses positional $1 placeholders, whereas Spanner uses @customer_id named placeholders.
  3. toolsets: groups tool names into role-based collections (claims_investigation_toolset, orders_readonly_toolset) so one Toolbox server can enforce segregation of duties across multiple agents.
# tools.yaml (store in Secret Manager; never bake secrets into container images)
sources:
  express-orders-db:
    kind: alloydb-postgres
    project: PROJECT_ID
    region: europe-west2
    cluster: express-agent-cluster
    instance: express-primary
    database: appdb
    user: toolbox_reader
    password: ${SECRET_ALLOYDB_PASSWORD}

tools:
  lookup_active_order:
    source: express-orders-db
    description: Look up active orders for a verified customer account ID.
    parameters:
      - name: customer_id
        type: integer
        description: Authenticated customer ID supplied by application context.
    statement: |
      SELECT order_id, status, total_cents, updated_at
      FROM orders
      WHERE customer_id = $1 AND status <> 'ARCHIVED'
      ORDER BY updated_at DESC
      LIMIT 10;

toolsets:
  customer_support_toolset:
    - lookup_active_order
Enter fullscreen mode Exit fullscreen mode

Two layers of least privilege protect this query: IAM (roles/alloydb.client) controls who can connect to the AlloyDB instance, while PostgreSQL GRANT SELECT on orders to toolbox_reader controls what the Toolbox can do once connected. Even if the Toolbox process were compromised, toolbox_reader cannot run DROP TABLE or UPDATE.

Storing tools.yaml in Secret Manager and testing tools directly

When deploying MCP Toolbox to Cloud Run as a private middleware service, never bake tools.yaml or passwords into the Docker image. Instead, store both in Google Cloud Secret Manager and mount them via --set-secrets: tools.yaml mounts as a file volume (for example /apps/toolbox/tools.yaml or /app/tools.yaml matching --config), while SECRET_ALLOYDB_PASSWORD mounts as an environment variable substituted at container startup. When a developer adds a new query to tools.yaml, you update the Secret Manager version and run gcloud run services update toolbox with no container rebuild.

Before connecting an LLM, test the Toolbox endpoint directly using toolbox_core (with an IAM identity token when deployed with --no-allow-unauthenticated). Two intentional error signatures confirm your controls are active:

  • Calling without a Bearer ID token returns "Your client does not have permission to get URL" (proving Cloud Run IAM enforcement works).
  • Calling lookup_active_order without customer_id returns "Missing required parameter" (proving parameter validation works).

Then wire the verified toolset into an ADK agent (google.adk.agents.Agent + ToolboxSyncClient):

import os
from google.adk.agents import Agent
from toolbox_core import ToolboxSyncClient

TOOLBOX_URL = os.environ["TOOLBOX_URL"]

# Load only the role-scoped toolset for this agent
toolbox = ToolboxSyncClient(TOOLBOX_URL)
tools = toolbox.load_toolset("customer_support_toolset")

support_agent = Agent(
    name="orders_support_agent",
    model="gemini-2.5-flash",
    instruction=(
        "You are a customer order assistant. Answer strictly from tool results. "
        "Never guess order statuses."
    ),
    tools=tools,
)
Enter fullscreen mode Exit fullscreen mode

(Note: when calling a private Cloud Run Toolbox service deployed with --no-allow-unauthenticated, pass client_headers={"Authorization": auth_methods.get_google_id_token(TOOLBOX_URL)} to ToolboxSyncClient, or auth_methods.aget_google_id_token(TOOLBOX_URL) to async ToolboxClient, and grant the ADK agent's service account roles/run.invoker, never roles/alloydb.client.)

Part D: Deploying ADK + AlloyDB Express on Cloud Run without auth crashes

Why refresh_strategy="background" breaks on Cloud Run

If your Cloud Run ADK application connects directly to AlloyDB Express via the AlloyDB Python Connector (google-cloud-alloydb-connector with pg8000 or asyncpg) for session state, pgvector retrieval, or fast in-process queries, you will hit one of the subtlest serverless bugs in Google Cloud.

Predict before you look: you deploy your ADK FastAPI server to Cloud Run with default CPU allocation ("CPU is only allocated during request processing") and Connector() initialized at module import. The first request succeeds. Twenty minutes of idle traffic later, the next user request fails with a TLS handshake / authentication error. Why?

Two-lane sequence diagram comparing Failure Mode refresh_strategy="background" (where Cloud Run freezes CPU between requests, stalling the background refresh thread so the ephemeral mTLS cert and IAM token expire and fail Request 2) against Serverless Pattern refresh_strategy="lazy" (which checks freshness synchronously inside connect(), refreshes credentials on demand when CPU is unthrottled, and connects cleanly over PSC or Public DNS)

Match your connector refresh mode to your runtime billing model: request-based CPU throttling on Cloud Run freezes background threads between requests.

By default, Connector() and AsyncConnector() use refresh_strategy="background". On Request 1, the connector fetches a short-lived ephemeral mTLS client certificate and IAM token from alloydb.googleapis.com, then schedules an asynchronous background refresh timer. The moment Cloud Run finishes returning HTTP 200, it throttles or freezes the container's CPU until the next request arrives. The background refresh thread starves, the ephemeral certificate expires in memory, and Request 2 hands an expired certificate to AlloyDB Express.

The fix is a one-line constructor parameter: refresh_strategy="lazy". With lazy refresh, no idle background thread runs between requests. When Request 2 arrives, Cloud Run unthrottles CPU, connect() checks cached certificate freshness synchronously on-demand, fetches a fresh mTLS certificate and IAM token if expired, and opens an encrypted connection.

Here is the production Cloud Run connector factory for asyncpg + SQLAlchemy using IPTypes.PUBLIC (for Public DNS over Express without VPC peering) or IPTypes.PSC (for Private Service Connect inside a custom VPC) and IAM database authentication:

import os
import sqlalchemy
import sqlalchemy.ext.asyncio
from google.cloud.alloydbconnector import AsyncConnector, IPTypes


async def create_serverless_alloydb_engine() -> (
    tuple[sqlalchemy.ext.asyncio.engine.AsyncEngine, AsyncConnector]
):
    """Creates a Cloud Run-safe async SQLAlchemy pool for AlloyDB Express."""
    inst_uri = os.environ["ALLOYDB_INSTANCE_URI"]
    # Format: projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>
    # Drop the .gserviceaccount.com suffix for IAM service accounts (per AlloyDB IAM auth rules)
    db_user = os.environ["ALLOYDB_IAM_USER"]  # e.g., adk-agent@my-project.iam
    db_name = os.environ.get("ALLOYDB_DB", "postgres")

    # CRITICAL on Cloud Run with request-based CPU throttling:
    # use refresh_strategy="lazy" so certs refresh inside active request scope.
    connector = AsyncConnector(refresh_strategy="lazy")

    async def getconn():
        return await connector.connect(
            inst_uri,
            "asyncpg",
            user=db_user,
            db=db_name,
            ip_type=IPTypes.PUBLIC,  # Switch to IPTypes.PSC for VPC-private prod
            enable_iam_auth=True,
        )

    engine = sqlalchemy.ext.asyncio.create_async_engine(
        "postgresql+asyncpg://",
        async_creator=getconn,
        execution_options={"isolation_level": "AUTOCOMMIT"},
        pool_size=5,
        max_overflow=2,
    )
    return engine, connector
Enter fullscreen mode Exit fullscreen mode

Keep one Express-specific latency interaction in mind: if both your Cloud Run service and your AlloyDB Express instance scaled to zero during an idle period, the first incoming prompt pays Cloud Run container cold start + lazy mTLS certificate fetch + ~20 seconds for AlloyDB Express auto-resume. Set HTTP client timeouts and ADK tool retry policies above 25 to 30 seconds during prototyping, or upgrade to always-on AlloyDB when sub-second P99 tail latency after idle periods becomes a requirement.

Local developer connections: Auth Proxy vs. allowlisted psql

From your workstation during local development, you have three clean ways to reach an Express instance over Public DNS:

  1. Zero-allowlist encrypted tunnel (gcloud beta alloydb connect): Starts a local Auth Proxy and opens psql without opening CIDR rules (--public-ip resolves Express's underlying public endpoint automatically, and --auto-iam-authn authenticates via your gcloud identity):
   gcloud beta alloydb connect express-primary \
       --cluster=express-agent-cluster \
       --region=europe-west2 \
       --public-ip \
       --auto-iam-authn \
       --project=PROJECT_ID
Enter fullscreen mode Exit fullscreen mode

(Or run ./alloydb-auth-proxy "projects/PROJECT_ID/locations/europe-west2/clusters/express-agent-cluster/instances/express-primary" --public-ip standalone.)

  1. Direct psql over Public DNS: Public DNS rejects all client IPs by default. First allowlist your CIDR block (note that --authorized-external-networks overwrites the entire list on every update, rather than appending), retrieve networkInfo.publicDnsName, and connect via standard URI:
   gcloud alloydb instances update express-primary \
       --cluster=express-agent-cluster \
       --region=europe-west2 \
       --authorized-external-networks=203.0.113.10/32 \
       --project=PROJECT_ID

   DNS_NAME=$(gcloud beta alloydb instances describe express-primary \
       --cluster=express-agent-cluster \
       --region=europe-west2 \
       --format="value(networkInfo.publicDnsName)" \
       --project=PROJECT_ID)

   psql "postgresql://postgres@${DNS_NAME}/postgres"
Enter fullscreen mode Exit fullscreen mode
  1. Private Service Connect (--psc / IPTypes.PSC): Keeps all database traffic inside your VPC without touching the public internet, provided you allowlisted your consumer project via --allowed-psc-projects.

Part E: Guardrails, the C4A region gate, and the irreversible exit to HA

When to resize vs. when to graduate

Predict before you look: you built a 1 vCPU AlloyDB Express prototype in us-west1 (express-agent-cluster). Your dataset just crossed 18 GB and your team needs automated backups and Regional HA, so you run gcloud beta alloydb clusters update express-agent-cluster --region=us-west1 --no-enable-express. What happens?

Decision flowchart starting from Hard Express Guardrails (50 CUs + 2 GB/mo free, 20 GB write block, 1:4 RAM, max_connections=200, 7 regions, no backups/HA/SLA) through three decision gates: Decision 1 (Hit hard boundary?), Decision 2 (Need >4 GB RAM / 2 vCPU leading to reversible 2-vCPU resize), and Decision 3 (1 vCPU in non-C4A region requiring mandatory 2-vCPU resize pre-step) before Outcome C one-way upgrade to Standard AlloyDB

Follow the three gates before running --no-enable-express: Decision 3 (the C4A region gate) determines whether a 1-vCPU instance can upgrade directly or must resize to 2 vCPUs first.

That us-west1 command fails with this exact error:

Upgrading to AlloyDB is not supported for 1-vCPU instances in location "us-west1". Please update the instance to use 2 vCPUs and try the upgrade again.
Enter fullscreen mode Exit fullscreen mode

Why? Because in Standard AlloyDB, 1-vCPU instances are only offered on the Arm-based C4A (Google Axion) machine series (c4a-highmem-1). Cross-referencing AlloyDB's 7 Express regions against C4A regional availability reveals a critical planning split:

AlloyDB Express Region Supports C4A? Can 1-vCPU Express upgrade directly?
asia-east1 Yes Yes (upgrades in place directly at 1 vCPU)
asia-southeast1 Yes Yes (upgrades in place directly at 1 vCPU)
europe-west2 Yes Yes (upgrades in place directly at 1 vCPU)
asia-east2 No No (must resize to --cpu-count=2 first)
asia-northeast1 No No (must resize to --cpu-count=2 first)
australia-southeast1 No No (must resize to --cpu-count=2 first)
us-west1 No No (must resize to --cpu-count=2 first)

If you are in one of the four non-C4A Express regions (us-west1, asia-east2, asia-northeast1, australia-southeast1), run the 2-vCPU resize first, then run --no-enable-express:

# Mandatory pre-step for 1-vCPU instances in non-C4A regions (e.g., us-west1)
gcloud alloydb instances update express-primary \
    --cluster=express-agent-cluster \
    --region=us-west1 \
    --cpu-count=2 \
    --project=PROJECT_ID

# Irreversible one-way graduation to Standard AlloyDB
gcloud beta alloydb clusters update express-agent-cluster \
    --region=us-west1 \
    --no-enable-express \
    --project=PROJECT_ID
Enter fullscreen mode Exit fullscreen mode

Know exactly what changes when that command completes:

  • Preserved with zero app rewrites: Your data, schemas, extensions, user credentials, Public DNS name, Private Service Connect endpoints, and current vCPU count stay intact.
  • Upgraded memory and scale ceilings: Your instance moves from the Express 1:4 memory ratio to AlloyDB's 1:8 vCPU-to-memory ratio (8 GB RAM at 1 vCPU, 16 GB RAM at 2 vCPUs), with compute scalable up to 288 vCPUs. The 20 GB storage cap is removed (16 TiB default quota, expandable up to 128 TiB).
  • Enterprise capabilities turned on: You can now configure Regional HA (99.99% uptime SLA at 2 or more vCPUs; 1-vCPU C4A HA instances have no SLA), up to 20 read pool nodes, cross-region replication (up to 5 secondary clusters), continuous PITR, automated/on-demand backups, and Terraform or Config Connector management.
  • Two permanent commitments: Scale-to-zero turns off (billing shifts to always-on AlloyDB hourly compute), and you cannot downgrade back to AlloyDB Express. Also note that you cannot convert to Customer-Managed Encryption Keys (CMEK) as part of the in-place upgrade.

Decision table

If you see... Use... Because...
Rapid prototype, hackathon, or intermittent coding-agent DB under 20 GB AlloyDB Express (--enable-express, 1 vCPU) ~2s Public DNS boot, 50 CUs + 2 GB/mo free (12m), $0 compute when idle
Need an 8-vCPU sandbox for 30 days with 1 TB storage and read pool testing AlloyDB Free Trial Cluster $0 compute for 30 days in 10 trial regions without Express's 20 GB / 2 vCPU cap
OOM errors on vector index builds while storage stays <= 20 GB and zonal SLA is fine gcloud alloydb instances update --cpu-count=2 Doubles RAM to 8 GB (1:4) while keeping scale-to-zero and reversibility
Remote MCP server in .agents/mcp_config.json silently fails to connect Replace url or httpUrl with serverUrl Antigravity requires serverUrl for remote Streamable HTTP / SSE; legacy keys are dropped
Multi-tenant ADK agent needs read-only access to user-owned rows Custom tools.yaml via MCP Toolbox ($1 parameters + least-privilege PG role) Prevents prompt-injected execute_sql from reading other tenants' rows
Cloud Run ADK app works on request 1, then fails after idle periods with mTLS error Connector(refresh_strategy="lazy") / AsyncConnector(refresh_strategy="lazy") Request-based CPU throttling stalls background cert-refresh threads between requests
Need backups, PITR, Regional HA (99.99% SLA), max_connections > 200, or > 20 GB gcloud beta alloydb clusters update --no-enable-express One-way in-place graduation preserving DNS, PSC, schemas, and data (resize to 2 vCPUs first in non-C4A regions)

Try it yourself

  1. Test the C4A region gate and scale-to-zero lifecycle. Provision an AlloyDB Express cluster in europe-west2 (a C4A region) using gcloud beta alloydb clusters create --enable-express, attach a --cpu-count=1 primary with --enable-public-dns, and connect via gcloud beta alloydb connect ... --public-ip --auto-iam-authn. Inspect the locked flags with SHOW max_connections; and SHOW google_columnar_engine.memory_size_in_mb;. Leave it idle, observe it scale to zero in Cloud Monitoring (alloydb.googleapis.com/instance/cpu/average_utilization), and time the ~20-second auto-resume on your next query. Clean up with gcloud alloydb clusters delete ... --force unless graduating.
  2. Verify both MCP planes and both Toolbox safety errors. Add both https://alloydb.googleapis.com/mcp (serverUrl) and @toolbox-sdk/server (command) to .agents/mcp_config.json, then verify connectivity in Antigravity CLI with /mcp. Define lookup_active_order in tools.yaml, deploy Toolbox to Cloud Run with --no-allow-unauthenticated and --set-secrets, and run two negative integration tests via toolbox_core: omit the IAM Bearer token to verify "Your client does not have permission to get URL", and omit customer_id to verify "Missing required parameter".
  3. Reproduce and fix the Cloud Run lazy-refresh trap. Deploy a minimal FastAPI + AsyncConnector health endpoint to Cloud Run with default CPU throttling ("CPU is only allocated during request processing"). Compare AsyncConnector() (background refresh) against AsyncConnector(refresh_strategy="lazy") across a 20+ minute idle gap, and inspect alloydb.googleapis.com/cluster/storage/usage plus the Cloud Run service logs in Logs Explorer to confirm clean on-demand certificate renewal.

If you build a prototype on this stack, share what you shipped with #AlloyDBSprint.

What's next

You now have a working PostgreSQL 18 prototype on AlloyDB Express, dual MCP planes for your coding agents, a declarative tools.yaml safety boundary, and a serverless ADK connection pattern that survives Cloud Run CPU throttling without breaking when you graduate to Regional HA.

In Part 2, we fill that database with embeddings and build production Hybrid RAG on AlloyDB AI: comparing ScaNN (alloydb_scann) against HNSW (pgvector) trees and scalar quantization, understanding iterative filtered vector search, combining dense and BM25 lexical signals with Reciprocal Rank Fusion plus semantic reranking, and wiring a two-layer RAG evaluation and drift loop.

Sources and further reading

Top comments (0)