DEV Community

Cover image for AlloyDB Without Lock-In: Omni Local Parity, pglogical Migration, and Safe Exit

AlloyDB Without Lock-In: Omni Local Parity, pglogical Migration, and Safe Exit

Prove portability before you commit: match production semantics locally with AlloyDB Omni, choose PSA or PSC without peering traps, migrate live with pglogical and Query Plan Management, and keep a tested exit back to stock PostgreSQL.

Series: A five-part, hands-on series (Engineering with AlloyDB: From Express Prototypes to Exit-Ready PostgreSQL) covering AlloyDB from Express prototyping with MCP Toolbox and ADK, through ScaNN vector search and hybrid RAG, zero-trust autonomous agents, disaggregated storage with the Columnar Engine and managed pooling, and finally exit-ready portability.

This is Part 5, the capstone. Across Parts 1 through 4 you moved from a scale-to-zero Express prototype to ScaNN hybrid RAG, secured autonomous agents, and high-concurrency HTAP with disaggregated WAL storage and managed pooling. This closing post tackles the hardest architectural question: how to adopt AlloyDB without trapping your schema, your network, your query plans, or your data inside a one-way door.

The problem: managed speed means nothing if you cannot leave

Adopting a managed cloud database always carries one nagging engineering fear: what happens three years from now if data residency rules shift, multi-cloud mandates arrive, or a workload simply belongs back on self-managed Kubernetes or stock PostgreSQL? Most "PostgreSQL-compatible" cloud databases break portability in four quiet places long before SQL syntax ever differs.

First, development drift: engineers build against vanilla PostgreSQL locally, then discover columnar, vector, or extension behavior diverges in production. Second, network lock-in: a cluster created with Private Services Access (PSA) locks into VPC Network Peering that cannot be changed after creation and fails when consumer organizations share overlapping RFC 1918 CIDRs. Third, cutover blindness: schemas load, row counts match, and then a changed libc collation or flipped query plan degrades p99 latency after DNS flips. Fourth, exit friction: a raw pg_dump full of cloud-specific CREATE EXTENSION statements fails to restore on stock PostgreSQL unless you strip them cleanly.

AlloyDB avoids proprietary wire protocols and storage lock-in by grounding every environment, from an Apple Silicon laptop to Google Cloud to an exit target, on the standard PostgreSQL :5432 contract, pglogical 2.4.8 logical streaming, and portable pg_dump archives.

Be explicit about provenance up front: this post was authored without executing commands against a live Google Cloud AlloyDB cluster. Every CLI flag, database flag, extension version, IAM role, SQL view, and ADK evaluation command below is verified directly against the official AlloyDB, AlloyDB Omni, and Agent Development Kit (ADK) documentation. No cluster timings or fabricated command outputs are invented; schematic SQL and pipeline checks are labeled clearly as documentation-verified patterns to run in your own environment.

What you'll be able to do

By the end of this capstone, structured across all six levels of Bloom's taxonomy, you will be able to:

  • Identify (Recall) the four AlloyDB Omni runtime tracks (Debian 12 bookworm and FIPS-ready -ubi9 containers, macOS Apple Silicon arm64, Kubernetes Operator 1.9.0, and RHEL RPM Orchestrator GA 18.3.0) and the shared PostgreSQL :5432 portability contract.
  • Explain (Understand) why Private Services Access (PSA) VPC peering is immutable after cluster creation and restricted to non-overlapping RFC 1918 ranges, whereas Private Service Connect (PSC) isolates multi-org VPCs and uses regional network attachments for outbound CDC.
  • Configure (Apply) pglogical 2.4.8 (alloydb.enable_pglogical=on, alloydb.logical_decoding=on), WRITE_ENDPOINT DNS abstractions, cross-region switchover vs --failover, Enhanced Backup Vaults, and Query Plan Management (google_plan_management).
  • Diagnose (Analyze) migration and exit blockers before cutover: non-supported libc collations versus ICU locales, rejected shared_preload_libraries edits, pg_restore EXTENSION errors, and WRITE_ENDPOINT / PSC constraints.
  • Decide (Evaluate) when to choose PSA versus PSC, Database Migration Service (DMS) versus manual pglogical, planned switchover versus --failover orchestration, and live pglogical streaming exit versus read-pool pg_dump -F custom archive exit.
  • Build (Create) an automated Cloud Build verification pipeline combining gcloud alloydb clusters import --sql (or pg_restore -L clean.toc for binary .dmp archives), parity checks, Query Plan Management approval/denial gates, and adk conformance / pytest regression gates.

Setup and local reference environment

You can validate the local parity and exit mechanics on a laptop before provisioning cloud infrastructure. You need Docker or Podman (or an Apple Silicon Mac for the native macOS package), standard PostgreSQL client tools (psql, pg_dump, pg_restore), and the gcloud CLI if you target Google Cloud AlloyDB.

# 1. Pull and run AlloyDB Omni container (Debian 12 bookworm or FIPS-ready -ubi9)
#    Check DockerHub google/alloydbomni/tags for the latest minor tag (e.g., 17.10.0,
#    17.10.0-ubi9, or 18.3.0/18.4.0 after requesting PG 18 access via the Omni incentives form)
docker run --name alloydb-omni \
  -e POSTGRES_PASSWORD=omni_dev_password \
  -p 5432:5432 \
  -d google/alloydbomni:18.3.0

# 2. Verify standard PostgreSQL wire protocol connectivity on :5432
psql -h 127.0.0.1 -U postgres -c "SELECT version();"
Enter fullscreen mode Exit fullscreen mode

For production environments, AlloyDB Omni requires a commercial per-vCPU subscription across all environments (development, testing, staging, and production), while evaluation, proof of concept (PoC), and non-commercial development carry no license charge.


Part A: Four-environment PostgreSQL parity with AlloyDB Omni

True portability starts long before you ever migrate out of a cloud. It starts when your laptop, your on-premises Kubernetes clusters, your bare-metal RHEL VMs, and your managed Google Cloud clusters speak the exact same SQL semantics and wire protocol.

Diagram showing 4-environment AlloyDB portability topology across Dev Workstation (AlloyDB Omni containers Debian 12 and FIPS -ubi9, macOS Apple Silicon, standard PG clients), Multi-Cloud/On-Prem (Kubernetes Operator 1.9.0 with HashiCorp Vault and Thales CipherTrust TdeConfig, pgBackRest PITR to S3/GCS, RHEL RPM Orchestrator GA 18.3.0), Google Cloud Managed AlloyDB (Primary, Read Pool up to 20 nodes, pglogical 2.4.8, GCS/DR), and Open-Source Exit (vanilla PostgreSQL subscriber, pg_dump -F custom with TOC stripping, unchanged app tier).

Every environment in the topology shares the PostgreSQL 15 through 18 engine contract on port 5432, ICU and C.UTF-8 collations, and standard pglogical 2.4.8 or pg_dump exit paths.

Look across the four columns in the diagram above. Each column maps to a concrete lifecycle stage:

Environment Packaging & Versions Key Parity Capabilities Operational Boundary
1. Dev Workstation Docker/Podman containers (bookworm & -ubi9), macOS Apple Silicon (arm64) installer PostgreSQL 15 through 18 core, ScaNN + vector, columnar engine, standard clients (psql, SQLAlchemy, psycopg) macOS installer is for non-production dev, testing, and AI prototyping only
2. Multi-Cloud / On-Prem Kubernetes Operator 1.9.0 (EKS, AKS, OpenShift, GKE); RHEL RPM Orchestrator GA 18.3.0 HA failover, read pools, PgBouncer, External KMS TDE (TdeConfig for HashiCorp Vault & Thales CipherTrust Manager), pgBackRest PITR to S3 or GCS Operator 1.9.0 supports PG 18.4, 17.10, 16.14, 15.18; RPM Orchestrator runs RHEL 9 / Rocky Linux 9 via Ansible & alloydbctl
3. Google Cloud Managed AlloyDB for PostgreSQL (PG 15 through 18; PG 18 default for new clusters as of Nov 2026) Disaggregated intelligent storage, active/standby HA, up to 20 read-pool nodes, pglogical 2.4.8, DMS, Cross-Region DR System-managed flags (such as shared_preload_libraries) controlled via alloydb.enable_* flags
4. Open-Source Exit Vanilla PostgreSQL (Linux, K8s, Amazon RDS, Cloud SQL PG) pglogical 2.4.8 subscriber on :5432, or pg_restore from pg_dump -F custom archive Application SQL, schemas, and connection drivers stay unchanged once AlloyDB extensions are stripped

Three concrete engineering details in the Omni stack matter when you plan multi-environment parity:

  • FIPS 140-3 without stale CVE lag. On Red Hat Universal Base Image 9 (-ubi9) container builds, AlloyDB Omni separates the frozen NIST CMVP-validated inner cryptographic boundary (Google BoringCrypto Module for postgres and pgbackrest, plus RHEL 9 OpenSSL FIPS Provider for base OS utilities) from the outer TLS, X.509, ASN.1, and HTTP/2 protocol layers. When the host OS enables FIPS mode (/proc/sys/crypto/fips_enabled = 1), all cryptographic operations route through the validated inner boundary with scram-sha-256 and TLS 1.2+, while Google still patches outer-layer CVEs across minor releases without invalidating the inner FIPS certificate.
  • Operator 1.9.0 and External KMS TDE. Released GA on October 13, 2026, Kubernetes Operator 1.9.0 pairs with DBCluster resource limits for PgBouncer and logrotate-agent, custom pg_hba.conf rules via UserDefinedAuthentication, custom non-cert-manager issuers (such as Venafi), and TdeConfig supporting both HashiCorp Vault and Thales CipherTrust Manager for Transparent Data Encryption (TDE). Combined with pgBackRest PITR archives targeting Amazon S3, GCS, or S3-compatible object stores, your Kubernetes data plane retains zero Google Cloud dependency.
  • Non-container enterprise HA via RPM Orchestrator. For regulated VM or bare-metal estates where container runtimes are disallowed, the Red Hat RPM Orchestrator (18.3.0 GA September 8, 2026; 18.4.0 / orchestrator 1.0.1 GA October 14, 2026) installs directly on RHEL 9 or Rocky Linux 9 ext4/xfs filesystems, automating HA failover, read pools, SELinux policies, and pgBackRest backups through Ansible and alloydbctl.

Predict before you look: Suppose you run AlloyDB Omni containers locally during non-commercial development for free, then promote the exact same Kubernetes Operator 1.9.0 manifests to staging and production. Which environments now require a commercial AlloyDB Omni vCPU subscription?

Answer: All of them. Once you plan for production, Google's licensing policy requires licensing all vCPUs across every environment, including development, testing, staging, and production. Plan your vCPU budget across the entire fleet before crossing into production.


Part B: VPC networking without lock-in: PSA vs PSC

Your network topology is the first decision in AlloyDB that is genuinely hard to undo. Choose wrong at cluster creation, and you lock your application architecture into peering exhaustion or IP collisions.

Side-by-side comparison diagram of Private Services Access (PSA) via permanent VPC Network Peering against Private Service Connect (PSC) with multi-VPC consumer endpoints and regional PSC network attachments for outbound pglogical and postgres_fdw traffic.

PSA trades multi-org flexibility for simple single-VPC peering that cannot be changed after cluster creation; PSC eliminates VPC peering and overlapping CIDR conflicts while supporting controlled outbound replication through regional network attachments.

Panel A: Private Services Access (PSA)

PSA establishes a permanent VPC Network Peering link between your consumer VPC (same project or Shared VPC) and the Google-managed producer VPC via servicenetworking.googleapis.com. You allocate a contiguous private CIDR block (minimum /24 per region, /16 recommended so multi-region clusters and other Google Cloud services do not exhaust IP space).

Two hard constraints govern PSA:

  1. Immutability at creation. Once AlloyDB creates a cluster using PSA, you cannot change its PSA network configuration.
  2. No transitive peering and no PUPI. PSA supports RFC 1918 ranges only (Privately Used Public IPs are rejected), and transitive VPC peering is blocked. If two business units or acquired companies share 10.10.0.0/16, PSA peering collapses.

Panel B: Private Service Connect (PSC)

PSC replaces VPC peering with a producer/consumer attachment model (--enable-private-service-connect at cluster creation). Every primary instance, read pool instance, and secondary instance publishes a unique Service Attachment URL and a pre-generated pscDnsName. Consumer VPCs (even across separate organizations, overlapping 10.10.0.0/16 CIDRs, or PUPI address spaces) connect via forwarding-rule PSC endpoints created either manually or automatically through a Service Connection Policy. Access is gated by --allowed-psc-projects; unapproved projects remain stuck in PENDING.

For outbound operations from AlloyDB back to your consumer network (such as pglogical migration streams or postgres_fdw), PSC uses a regional Network Attachment in your VPC subnet (which must use RFC 1918 IP space):

# 1. Inspect the AlloyDB service-owned project number (needed for ACCEPT_MANUAL attachments)
gcloud alloydb clusters describe CLUSTER_ID \
  --region=REGION_ID \
  --project=PROJECT_ID
# Look for pscConfig.serviceOwnedProjectNumber in the output

# 2. Attach an existing regional PSC Network Attachment (ACCEPT_AUTOMATIC or ACCEPT_MANUAL)
gcloud alloydb instances update INSTANCE_ID \
  --cluster=CLUSTER_ID \
  --region=REGION_ID \
  --project=PROJECT_ID \
  --psc-network-attachment-uri="projects/PROJECT_ID/regions/REGION_ID/networkAttachments/NETWORK_ATTACHMENT_ID"
Enter fullscreen mode Exit fullscreen mode

Keep three documented PSC caveats in your architecture notes:

  • March 1, 2025 cutoff for outbound PSC. AlloyDB instances created prior to March 1, 2025 cannot be updated in-place to add --psc-network-attachment-uri; you must either create a cross-region replica with outbound connectivity enabled and perform a switchover, or backup and restore to a newly created cluster.
  • Private DNS requirements. Inbound AlloyDB Auth Proxy and Language Connectors require a private Cloud DNS zone mapping pscDnsName to the local PSC endpoint IP. Conversely, private DNS resolution is not supported on outbound PSC connections (such as postgres_fdw or dblink).
  • No WRITE_ENDPOINT on PSC. AlloyDB WRITE_ENDPOINT DNS abstractions (Preview) support PSA-configured instances only.

Predict before you look: Two teams in separate projects both use 10.10.0.0/16 and need private connectivity to one AlloyDB cluster, plus you want WRITE_ENDPOINT global DNS failover. Can one networking mode give you both?

Answer: No. Overlapping 10.10.0.0/16 VPCs require PSC, whereas WRITE_ENDPOINT (Preview) currently supports PSA only. With PSC, applications resolve per-consumer pscDnsName records mapped to their local PSC endpoints instead of a PSA WRITE_ENDPOINT.


Part C: Zero-downtime migration, pre-flight blockers, and QPM cutover

An exit-ready cloud migration treats cutover as reversible until production SLOs hold under real load. That requires passing a pre-flight gate before any WAL bytes move, verifying parity on a read pool before traffic flips, pinning execution plans with Query Plan Management (QPM), and keeping a reverse pglogical stream alive during the soak window.

Five-step zero-downtime migration pipeline from Source PostgreSQL through Pre-Flight Audit (locales, shared_preload_libraries, extensions), Snapshot and CDC via pglogical 2.4.8 or DMS, Read-Pool Verification, App Cutover with QPM baseline capture, and Step 5 Reverse-Sync Fallback back to warm standby source.

Cutover is not a cliff edge: Step 1 clears locale and extension blockers, Step 3 verifies parity on a read pool, Step 4 captures and approves execution plans in QPM, and Step 5 keeps a reverse pglogical stream running until the rollback window closes.

Step 1: The pre-flight audit (catch blockers before CDC)

Before configuring DMS or pglogical, check three compatibility boundaries on the source database:

  1. Locales and collations. AlloyDB supports the full set of ICU locales plus ucs_basic, and only two libc locales: C.UTF-8 and en_US.utf8. If your source PostgreSQL database defaults to another libc locale (such as en_GB.UTF-8 or de_DE.UTF-8), data still imports, but ORDER BY sorting semantics can change unless you default the target database to C.UTF-8 and assign explicit ICU collations to sorted columns:
-- Inspect available ICU collations on the target AlloyDB cluster
SELECT collname FROM pg_collation WHERE collprovider = 'i';

-- Pin explicit ICU collation on ORDER BY-sensitive text columns
ALTER TABLE customer_orders
    ALTER COLUMN customer_name
    SET DATA TYPE varchar(255)
    COLLATE "en-US-x-icu";
Enter fullscreen mode Exit fullscreen mode
  1. System-managed shared_preload_libraries. In AlloyDB, modifying shared_preload_libraries directly is rejected because the control plane manages preloaded shared libraries automatically. Instead, enable extensions through their corresponding alloydb.enable_* instance flags (for example alloydb.enable_pglogical, alloydb.enable_pgaudit, alloydb.enable_pg_cron, or alloydb.enable_pg_squeeze).
  2. Supported extensions and decoding plugins. AlloyDB ships pglogical 2.4.8 alongside four logical decoding plugins: pgoutput, wal2json, decoderbufs, and test-decoding. Only members of alloydbsuperuser (including postgres by default) can run CREATE EXTENSION.

Step 2: DMS quick-start vs manual pglogical 2.4.8

You have two paths for Snapshot + CDC ingestion:

  • Database Migration Service (DMS): Handles initial snapshot, continuous CDC, networking, and status tracking for homogeneous sources (self-managed PostgreSQL, Cloud SQL, Amazon RDS, Amazon Aurora) and heterogeneous sources (Oracle/SQL Server with Gemini-powered conversion). In Preview, quick-start migrations automatically provision PSC network attachments, subnets, and connection profiles when the source has a private IP in your VPC. Note one strict IAM rule: required roles (roles/compute.networkAdmin for the migration user and roles/compute.networkViewer for service-DESTINATION_PROJECT_NUMBER@gcp-sa-datamigration.iam.gserviceaccount.com on the source project; roles/datamigration.admin and roles/alloydb.admin for the migration user on the destination project) must be granted directly to accounts, because roles inherited via Google Groups are not supported for quick-start migrations.
  • Self-managed pglogical 2.4.8: Ideal when you want symmetrical, bidirectional control (including Step 5 reverse-sync fallback) across AlloyDB Omni, external VMs, or cross-cloud PostgreSQL. Both alloydb.enable_pglogical and alloydb.logical_decoding default to off and require an instance restart when enabled:
# Enable pglogical and logical decoding on the AlloyDB instance (triggers restart)
# Note: --database-flags overwrites previously set flags; include all existing flags!
gcloud alloydb instances update PRIMARY_INSTANCE_ID \
  --cluster=CLUSTER_ID \
  --region=REGION_ID \
  --project=PROJECT_ID \
  --database-flags=alloydb.enable_pglogical=on,alloydb.logical_decoding=on
Enter fullscreen mode Exit fullscreen mode

Then enable the extension inside the target database as an alloydbsuperuser member:

\c app_db
CREATE EXTENSION IF NOT EXISTS pglogical;

-- Verify installed extension version (2.4.8 on AlloyDB)
SELECT extname, extversion FROM pg_extension WHERE extname = 'pglogical';
Enter fullscreen mode Exit fullscreen mode

Step 3 and Step 4: Read-pool parity and QPM plan capture

Once CDC catches up, run shadow read queries against an AlloyDB Read Pool (up to 20 nodes per cluster) to compare row counts, checksums, replication lag, and p99 latency without touching primary write I/O.

On PSA clusters, you can decouple application connection strings from instance IPs using a WRITE_ENDPOINT (Preview):

# Create a WRITE_ENDPOINT pointing to the AlloyDB primary instance (PSA only)
gcloud beta alloydb endpoints create app-write-ep \
  --project=PROJECT_ID \
  --region=REGION_ID \
  --endpoint-type=WRITE_ENDPOINT \
  --target-instances="projects/PROJECT_ID/locations/REGION_ID/clusters/CLUSTER_ID/instances/PRIMARY_INSTANCE_ID"

# Retrieve dnsConfig.dnsName (strip the trailing period '.' before passing to psql/apps)
gcloud beta alloydb endpoints describe app-write-ep \
  --project=PROJECT_ID \
  --region=REGION_ID
Enter fullscreen mode Exit fullscreen mode

Immediately after cutover, protect against PostgreSQL optimizer plan flips by enabling Query Plan Management (QPM) (Preview). Set google_plan_management.enabled=on (requires restart), create the google_plan_management (1.0) extension, and grant google_plan_management_role:

-- Run on the primary instance (QPM is supported on primary only)
CREATE EXTENSION IF NOT EXISTS google_plan_management;
GRANT google_plan_management_role TO app_dba;

-- Inspect tracked plans and compare average time (total_execution_time / num_executions)
SELECT logical_query_id, plan_id, num_executions,
       total_execution_time / NULLIF(num_executions, 0) AS avg_time,
       left(query, 80) AS query_prefix
FROM google_plan_management.tracked_plans_view
ORDER BY total_execution_time DESC
LIMIT 20;

-- Approve verified plan(s) or deny regressed plan(s)
SELECT google_plan_management.approve_plan(15480571796188147798, 4740866759615354783);
SELECT * FROM google_plan_management.managed_plans_view;
Enter fullscreen mode Exit fullscreen mode

Track QPM's documented boundaries: tracked plans are not enforced until explicitly approved, QPM applies to the primary instance only (not read pools), it cannot be used on partitioned tables or grouping sets, and the repository holds up to 100,000 unique plans with no automatic retention eviction. You can disable steering temporarily without deleting approvals by setting google_plan_management.enable_steer_plans=off.

Step 5: The reverse-sync fallback safety net

Because alloydb.logical_decoding=on and pglogical are active on your new AlloyDB primary, you can run a reverse pglogical subscription from AlloyDB back to the original source PostgreSQL database during your post-cutover soak window. If an unforeseen application SLO regression or unmitigated plan failure hits, you drain writes and repoint DNS back to the warm origin host without losing post-cutover transactions.

Predict before you look: You try to enable pglogical on AlloyDB by passing --database-flags=shared_preload_libraries=pglogical. When that fails, you set --database-flags=alloydb.enable_pglogical=on alone and run CREATE EXTENSION pglogical;. Why does it still fail?

Answer: First, shared_preload_libraries is system-managed and rejected by AlloyDB. Second, pglogical requires both alloydb.enable_pglogical=on and alloydb.logical_decoding=on (followed by instance restart) before CREATE EXTENSION pglogical; succeeds. Also remember gcloud alloydb instances update --database-flags overwrites all previous flags unless you repeat them.


Part D: Cross-region disaster recovery and verifiable exit

An exit-ready architecture separates two distinct failure domains: surviving a regional Google Cloud outage (Cross-Region DR + Immutable Backups), and leaving Google Cloud altogether back to vanilla open-source PostgreSQL.

Dual-lane architecture diagram showing Top Lane: Multi-Region Cloud DR (Region A Primary + Enhanced Backup Vault, WRITE_ENDPOINT DNS abstraction, Region B Secondary Cluster up to 5 secondaries and 20 read nodes each, Planned switchover RPO=0 vs Unplanned failover orchestration Preview) and Bottom Lane: Verifiable Exit to stock PostgreSQL via Path A pglogical publisher streaming or Path B read-pool pg_dump -F custom with pg_restore -l sed extension stripping.

Top lane keeps workloads resilient across Google Cloud regions with planned RPO=0 switchover and --failover orchestration plus immutable Backup Vaults; bottom lane proves you can leave via live pglogical streaming or clean pg_dump archives.

Top lane: Cross-region DR (switchover vs --failover) and Enhanced Backup Vaults

AlloyDB supports up to five asynchronous secondary clusters per primary, each supporting up to 20 read nodes. When you create a secondary cluster (gcloud alloydb clusters create-secondary), AlloyDB copies automated and continuous PITR backup settings (unless --no-enable-automated-backup is passed, or CMEK is used, in which case you must supply a regional Cloud KMS key for the secondary).

Choose the right promotion operation for the event:

  • Planned switchover (GA, RPO=0): Reverses primary and secondary roles with zero data loss and updates all other secondary clusters to follow the new primary. Mandatory rule: stop all write traffic to the primary and confirm lag is 0 before running switchover, or the command can time out waiting on in-flight transactions. Remember to re-enable Advanced Query Insights on the new primary afterward.
  • Unplanned promote vs --failover orchestration (Preview): Standard gcloud alloydb clusters promote detaches the secondary into a standalone primary. Adding --failover (gcloud beta alloydb clusters promote ... --failover, supported only for single-secondary topologies) promotes the secondary, updates WRITE_ENDPOINT DNS immediately, and automatically recreates the original primary as a secondary (RECREATING state) once its region recovers. To guard against split-brain writes during failover, AlloyDB stops writes on the old primary and captures an automatic system backup so you can restore it to a temporary cluster and reconcile any un-replicated transactions manually.
# Planned zero-data-loss switchover (stop writes first!)
gcloud alloydb clusters switchover SECONDARY_CLUSTER_ID \
  --region=SECONDARY_REGION \
  --project=PROJECT_ID

# Unplanned cross-region failover with automatic original-primary recreation (Preview)
gcloud beta alloydb clusters promote SECONDARY_CLUSTER_ID \
  --region=SECONDARY_REGION \
  --project=PROJECT_ID \
  --failover
Enter fullscreen mode Exit fullscreen mode

For ransomware and accidental-deletion protection, pair cross-region replicas with Enhanced backups (GA via Backup and DR Service). Unlike standard AlloyDB backups, enhanced backups reside in a Backup Vault with enforced retention locks (nobody can delete them before expiry, even administrators) and survive source project deletion:

gcloud backup-dr backup-plan-associations create BPA_ID \
  --project=WORKLOAD_PROJECT_ID \
  --location=REGION_ID \
  --resource-type=alloydb.googleapis.com/Cluster \
  --resource="projects/WORKLOAD_PROJECT_ID/locations/REGION_ID/clusters/CLUSTER_ID" \
  --backup-plan="projects/VAULT_PROJECT_ID/locations/REGION_ID/backupPlans/BP_ID"
Enter fullscreen mode Exit fullscreen mode

Bottom lane: Two independent exit paths to stock PostgreSQL

When you want out of Google Cloud entirely, AlloyDB leaves zero proprietary storage or format barriers:

  1. Path A: Live pglogical streaming exit. Because AlloyDB runs pglogical 2.4.8 with alloydb.logical_decoding=on, your AlloyDB primary acts as a standard pglogical publisher streaming WAL changes over :5432 to a vanilla PostgreSQL subscriber (self-managed Linux, Kubernetes, Amazon RDS, or Cloud SQL). Your application drains writes, verifies LSN sync, and cuts over to the open-source subscriber.
  2. Path B: Read-Pool pg_dump -F custom + TOC extension stripping. For cold archive exports or offline exits, run pg_dump against an AlloyDB Read Pool instance to avoid adding I/O pressure to your primary. Before restoring into stock open-source PostgreSQL, strip AlloyDB-specific EXTENSION lines (such as google_columnar_engine, alloydb_scann, google_ml_integration, or google_plan_management) from the custom archive's Table of Contents (TOC):
# 1. Export from a Read Pool IP in PostgreSQL custom binary format
pg_dump -h READ_POOL_IP -U postgres -F custom app_db > app_db.dmp

# 2. Generate a clean TOC that comments out EXTENSION statements
pg_restore -l app_db.dmp | sed -E 's/(.* EXTENSION )/; \1/g' > clean.toc

# 3. Restore cleanly into vanilla PostgreSQL (no AlloyDB extensions required)
pg_restore -h VANILLA_PG_HOST -U postgres -d app_db -L clean.toc app_db.dmp
Enter fullscreen mode Exit fullscreen mode

If you also export global roles across clusters, remember pg_dumpall --globals-only --no-role-passwords because --globals-only without --no-role-passwords requires privileges unavailable in managed AlloyDB.

Predict before you look: Your team exports app_db.dmp from AlloyDB, runs pg_restore -d app_db app_db.dmp straight onto a fresh community PostgreSQL 18 container, and hits ERROR: extension "google_columnar_engine" is not available. What single command fixes the archive without re-dumping?

Answer: Generate a filtered Table of Contents with pg_restore -l app_db.dmp | sed -E 's/(.* EXTENSION )/; \1/g' > clean.toc, then pass -L clean.toc to pg_restore. If your target stock PostgreSQL still needs vector or pglogical, re-create only those open-source extensions explicitly beforehand.


Part E: Automated CI/CD verification gates with QPM and adk conformance

Portability and migration safety collapse if verification happens manually once at cutover. Every schema migration, dump/restore test, and AI agent release needs an automated staging gate that aborts before production traffic is touched.

Five-stage CI/CD verification pipeline: 1. Cloud Build / Git Trigger (schema PR, golden evalset, GCS .sql/.dmp artifact), 2. Cluster Load via gcloud alloydb clusters import, 3. Data Parity Gate (row counts, checksums, ICU collations), 4. Plan Regression Gate (Query Plan Management approve_plan/deny_plan via tracked_plans_view), 5. Conformance Gate (adk conformance and pytest against golden baseline), leading to Automated Promote or Instant Rollback on any gate failure.

Every stage must pass sequentially: data loads deterministically, schema and ICU collations match, QPM guards against query plan regressions, and adk conformance verifies agent SQL behavior against a versioned golden baseline.

Each gate in the pipeline catches a distinct class of migration or schema regression:

  1. Source Trigger & Staging Load (Gates 1 and 2). A Cloud Build trigger runs on schema pull requests or release tags. For plain .sql or compressed .sql.gz artifacts in Cloud Storage (never use Requester Pays buckets, because the AlloyDB Service Agent service-PROJECT_NUMBER@gcp-sa-alloydb.iam.gserviceaccount.com cannot charge requester projects), load into a staging AlloyDB cluster using gcloud alloydb clusters import --sql (requiring roles/alloydb.admin or custom alloydb.clusters.get + alloydb.clusters.import for the caller, plus roles/storage.objectViewer for the AlloyDB Service Agent). For binary custom-format .dmp archives, run pg_restore -L clean.toc from a Cloud Build step or staging VM.
  2. Data Parity Gate (Gate 3). Verify row counts, aggregate checksums, pg_extension versions, and ICU collations (SELECT collname FROM pg_collation WHERE collprovider = 'i') against expected baseline invariants.
  3. Plan Regression Gate (Gate 4). Run synthetic workload queries against the staging primary with google_plan_management.enabled=on, inspect google_plan_management.tracked_plans_view for newly introduced plans or latency regressions, and fail the build or call google_plan_management.deny_plan(...) if an unapproved Seq Scan replaces an approved index scan.
  4. ADK Conformance Gate (Gate 5). If your workload includes SQL-backed AI agents built with the Agent Development Kit (ADK), schema or collation drift can silently break tool calls even when unit tests pass. ADK documents four evaluation paths (adk web UI, pytest with AgentEvaluator.evaluate for fast single-session .test.json unit tests, adk eval CLI for multi-turn evalsets, and adk conformance for regression testing live agents against a recorded golden baseline). Key deterministic criteria require no LLM judge: tool_trajectory_avg_score (default 1.0, matching EXACT, IN_ORDER, or ANY_ORDER) and response_match_score (default 0.8, ROUGE-1).

Here is how those verification gates assemble inside a declarative cloudbuild.yaml pipeline (schematic configuration derived from documented gcloud, QPM SQL, and ADK CLI contracts):

steps:
  # Gate 2: Deterministic staging load from GCS (.sql or .sql.gz)
  - name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
    id: "load-staging-sql"
    args:
      - "gcloud"
      - "alloydb"
      - "clusters"
      - "import"
      - "${_STAGING_CLUSTER}"
      - "--region=${_REGION}"
      - "--database=${_DATABASE}"
      - "--gcs-uri=${_GCS_SQL_URI}"
      - "--user=postgres"
      - "--sql"

  # Gate 3 & Gate 4: Data parity, ICU collation check & QPM plan regression check
  - name: "postgres:18"
    id: "parity-and-qpm-gate"
    entrypoint: "bash"
    args:
      - "-c"
      - |
        set -euo pipefail
        psql "${_STAGING_DSN}" -v ON_ERROR_STOP=1 -f ci/checks/verify_parity_and_collations.sql
        python3 ci/checks/qpm_plan_gate.py --dsn "${_STAGING_DSN}"

  # Gate 5: ADK unit tests (pytest), CLI evalset gate (adk eval), and golden-baseline conformance check
  - name: "python:3.12-slim"
    id: "adk-conformance-gate"
    entrypoint: "bash"
    args:
      - "-c"
      - |
        set -euo pipefail
        pytest tests/agent_sql_unit_tests.py -q
        adk eval agents/sql_assistant evalsets/golden_baseline.evalset.json \
          --config_file_path=evalsets/test_config.json \
          --print_detailed_results
        # Pair with `adk conformance` against recorded golden baseline files before promotion
Enter fullscreen mode Exit fullscreen mode

If any step exits non-zero, Cloud Build halts cutover, denies unapproved query plans, and leaves your reverse-sync pglogical fallback untouched.

Predict before you look: Your team notices production agents hitting new edge cases, so someone suggests rotating out passing cases in golden_baseline.evalset.json each sprint to keep CI runtime flat. Why does that break adk conformance?

Answer: adk conformance compares live behavior against a fixed golden baseline. If you rewrite or rotate existing cases every sprint, you destroy the fixed comparison point and can no longer tell whether a score drop came from a code/schema regression or a harder test set. Append newly discovered failures as new cases while keeping existing evals byte-identical, and split cadence instead (fast .test.json unit checks per commit, full evalsets on staging/nightly runs).


Decision table

If you see... Use... Because...
Local laptop dev or air-gapped CI needing AlloyDB parity AlloyDB Omni container (bookworm or -ubi9) or macOS arm64 Shared PG 15 through 18 core, ScaNN, columnar engine, and :5432 wire contract
Multi-cloud Kubernetes estate with enterprise KMS & S3/GCS PITR AlloyDB Omni Kubernetes Operator 1.9.0 + TdeConfig + pgBackRest Supports HashiCorp Vault & Thales CipherTrust Manager TDE plus S3/GCS WAL archiving
Non-container RHEL 9 / Rocky Linux 9 VMs managed via Ansible AlloyDB Omni RPM Orchestrator (18.3.0+ GA) Native OS ext4/xfs storage, alloydbctl, SELinux, HA failover without Docker/K8s
Simple single-VPC workload needing WRITE_ENDPOINT DNS Private Services Access (PSA) Supports WRITE_ENDPOINT (Preview), simpler direct routing inside non-overlapping RFC 1918
Overlapping consumer CIDRs, multi-org VPCs, or PUPI ranges Private Service Connect (PSC) + Network Attachment Eliminates peering limits/IP collisions; regional attachment enables outbound pglogical/FDW
Homogeneous private-IP migration needing fast setup DMS Quick-Start Migration (Preview) Auto-provisions PSC attachments & CDC (ensure direct IAM roles, no Google Groups)
Need reversible zero-loss fallback after cutover Self-managed pglogical 2.4.8 (alloydb.enable_pglogical=on, alloydb.logical_decoding=on) Streams forward CDC for cutover and reverse CDC back to warm standby origin
Planned regional migration or DR drill with zero data loss gcloud alloydb clusters switchover (after stopping writes) Drains replication lag (RPO=0) and cleanly reverses sync direction
Unplanned primary region outage (single secondary topology) gcloud beta alloydb clusters promote --failover Promotes secondary, updates WRITE_ENDPOINT, and auto-recreates old primary
Ransomware / project-deletion-proof compliance backups Enhanced backups in Backup and DR Vault (GA) Enforced retention locks block deletion and survive source project deletion
Leaving AlloyDB back to stock open-source PostgreSQL pglogical publisher exit OR Read-Pool pg_dump -F custom + sed TOC strip Streams live WAL out or strips AlloyDB EXTENSION entries cleanly via clean.toc
Query plan flips or agent SQL regressions after migration QPM (google_plan_management) + adk conformance / pytest in Cloud Build Pins approved plans on primary and halts promotion on golden-baseline drift

Try it yourself

Build and verify the portability mechanics on your own machine or sandbox project. If you share your results or pipeline templates, tag them with #AlloyDBSprint.

  1. Lab 1: Local AlloyDB Omni parity and clean TOC exit. Start an alloydbomni container (18.3.0 or 18.4.0) and a vanilla postgres:18 container on separate ports (5432 and 5433). On Omni, enable vector and create a small schema with an explicit ICU collation (COLLATE "en-US-x-icu"). Export with pg_dump -F custom, verify what breaks when you restore directly into postgres:18, then apply pg_restore -l | sed -E 's/(.* EXTENSION )/; \1/g' > clean.toc and confirm pg_restore -L clean.toc succeeds cleanly.
  2. Lab 2: Pre-flight blocker and QPM plan guard. Run SELECT collname FROM pg_collation WHERE collprovider = 'i'; and confirm how shared_preload_libraries differs from alloydb.enable_pglogical + alloydb.logical_decoding. On an AlloyDB instance, toggle google_plan_management.enabled=on, run a parameterized query twice (once forcing a sequential scan via SET enable_indexscan = off;, once with index scan on), inspect google_plan_management.tracked_plans_view, and verify deny_plan() blocks the regression plan.
  3. Lab 3: Cloud Build migration & adk conformance gate. Create a .test.json unit fixture and a test_config.json criteria config (setting tool_trajectory_avg_score with match_type: "IN_ORDER") for a read-only SQL assistant agent, wire a cloudbuild.yaml using the 5-stage structure in Part E, intentionally break a column name or collation in staging, and confirm the pipeline exits non-zero before the promotion step runs.

What's next

This post closes the five-part Engineering with AlloyDB: From Express Prototypes to Exit-Ready PostgreSQL series. Every stage in the series builds on the same PostgreSQL foundation:

Part Stage in the Lifecycle Core Capability How It Connects to Exit-Ready Scale
Part 1 Express Prototype & Agents AlloyDB Express (1 to 2 vCPU, scale-to-zero, fast provisioning, one-way HA upgrade, MCP Toolbox, ADK) Same PostgreSQL 18 SQL, ScaNN, and AI functions without upfront cluster commitment
Part 2 Vector Search & Hybrid RAG ScaNN (alloydb_scann) vs. HNSW, adaptive filtering, ai.hybrid_search(), ai.rank(), two-layer evals In-database vector and lexical search without standalone vector store lock-in
Part 3 Autonomous Agent Security PostgreSQL for Agents, Parameterized Secure Views, 5-gate IAM + Model Armor, AI Query Engine, OTel Strict multi-tenant isolation and auditable SQL views backed by standard PostgreSQL roles
Part 4 Storage, HTAP & Pooling Disaggregated WAL storage, Columnar Engine (10.6), Managed Pooling (6432), Zero-ETL Iceberg & BigQuery High concurrency and open-format Apache Iceberg lakehouse tables with zero data lock-in
Part 5 Portability & Exit AlloyDB Omni, PSA vs. PSC, pglogical 2.4.8, CRR DR, Enhanced Vaults, QPM + adk conformance Zero-lock-in parity across laptop, multi-cloud K8s, Google Cloud, and open-source exit

You never need to treat a managed cloud database as a one-way bet. When your local workstation runs the same core engine as production, your network avoids peering dead ends, your cutover keeps a reverse-sync lifeline, and your exit archive restores cleanly onto community PostgreSQL, adopting AlloyDB becomes a pure engineering win with a verified escape hatch.


Sources and further reading

Top comments (0)