Deploying a database for production at Google Cloud scale is not a single command.
It is a contract between the engine's published availability semantics, the topology the engineer chooses at create time, the IAM and connectivity surface that wraps it, the automation that recreates it on demand, and the monitoring that proves the contract holds.
This section walks the deployment surface for the five managed engines that dominate the certification scope: Cloud SQL, AlloyDB, Spanner, Bigtable, and Firestore.
Each subsection below picks one operational lever and works through the provisioning command set, the testing discipline, the trade-offs, and the failure modes the engineer must rehearse before declaring an instance production-ready.
The six subsections that follow trace the lifecycle in the order an engineer hits it:
- provision the HA topology;
- rehearse failover and DR before the workload arrives;
- configure multi-region replication for the posture the workload demands;
- size read replicas against measured traffic;
- codify the whole stack so it is reproducible;
- and instrument the result so on-call sees degradations before users do.
Decision Tree: Choosing the HA Posture per Engine
Provisioning high availability database solutions in Google Cloud
HA provisioning starts with engine-specific creation flags. Each managed database service models HA differently, so the engineer cannot reuse the same flag name across the fleet. The discipline is to pin the HA posture into the create-time call so that the resource cannot exist in a half-configured state.
For Cloud SQL, regional HA is set through --availability-type=REGIONAL at instance create. The flag puts the standby in a different zone of the same region, replicates synchronously through the underlying regional persistent disk, and exposes a single instance endpoint that the failover process re-points.
The standby is not user-accessible: connections always route through the primary writer. Setting the flag at create time is the supported path; flipping a zonal instance to regional later through gcloud sql instances patch --availability-type=REGIONAL works but triggers a rebuild that can take tens of minutes.
gcloud sql instances create ordersdb-prod \
--database-version=POSTGRES_15 \
--region=us-central1 \
--availability-type=REGIONAL \
--edition=ENTERPRISE_PLUS \
--tier=db-perf-optimized-N-8 \
--storage-type=SSD \
--storage-size=500 \
--storage-auto-increase \
--enable-point-in-time-recovery \
--backup-start-time=02:00 \
--maintenance-window-day=SUN \
--maintenance-window-hour=4 \
--maintenance-release-channel=production \
--network=projects/host-prod/global/networks/db-vpc \
--no-assign-ip \
--disk-encryption-key=projects/keys-prod/locations/us-central1/keyRings/sql/cryptoKeys/orders
For AlloyDB, the cluster and instance are separate resources.
The cluster owns regional metadata and the encryption key, and the primary instance carries the HA toggle through its --availability-type=REGIONAL flag.
Adding --read-pool-node-count on a separate read-instances create call lights up the read pool.
AlloyDB's primary always runs with a standby when REGIONAL is set; you cannot mix zonal primary with a read pool that expects regional resilience.
gcloud alloydb clusters create orders-cluster \
--region=us-central1 \
--network=projects/host-prod/global/networks/db-vpc \
--kms-key=projects/keys-prod/locations/us-central1/keyRings/alloydb/cryptoKeys/orders \
--automated-backup-window=02:00 \
--continuous-backup-recovery-window-days=14
gcloud alloydb instances create orders-primary \
--cluster=orders-cluster \
--region=us-central1 \
--instance-type=PRIMARY \
--cpu-count=16 \
--availability-type=REGIONAL \
--database-flags=password.encryption=scram-sha-256
Spanner does not need an HA flag. Every instance is replicated across three zones at minimum (regional configurations) or three or more regions (multi-region configurations). The deployment lever is processing-unit count and the --config value: regional-us-central1 is single-region with zone HA, while nam-eur-asia1 is multi-region with synchronous Paxos quorum across three continents. The trade-off is write latency.
gcloud spanner instances create orders-prod \
--config=regional-us-central1 \
--processing-units=2000 \
--description="Orders OLTP production" \
--edition=ENTERPRISE_PLUS
Bigtable expresses HA through cluster count. A single-cluster instance is zonal. Adding a second cluster in a different zone of the same region gives zonal failover with eventual consistency replication. Adding a cluster in a different region gives cross-region replication. App profiles control routing.
gcloud bigtable instances create events-prod \
--display-name="Events ingestion" \
--cluster-config=id=events-c1,zone=us-central1-a,nodes=6,autoscaling-min-nodes=4,autoscaling-max-nodes=12,autoscaling-cpu-target=70 \
--cluster-config=id=events-c2,zone=us-east4-a,nodes=6,autoscaling-min-nodes=4,autoscaling-max-nodes=12,autoscaling-cpu-target=70
gcloud bigtable app-profiles create primary-routing \
--instance=events-prod \
--route-to=events-c1 \
--transactional-writes
Firestore Native picks its HA posture at database creation through the location: a regional location like us-central1 replicates across three zones; a multi-region location like nam5 or eur3 replicates across multiple regions with strong consistency for read-after-write within a region and eventual consistency across regions for some operations.
gcloud firestore databases create \
--database=orders \
--location=nam5 \
--type=firestore-native \
--kms-key-name=projects/keys-prod/locations/nam5/keyRings/firestore/cryptoKeys/orders \
--delete-protection
💡 Exam Trap:
--availability-type=ZONALon Cloud SQL or AlloyDB looks cheaper, but the instance has no standby. Failover is not possible, only restore from backup. The exam will frame this as "we need HA" and the cost-optimization wrong answer will be the ZONAL flag.
💡 Exam Trap: Spanner has no HA flag because every instance is HA by default at the config it was created in. A question that asks how to "enable HA" on a Spanner regional instance is a trap: the regional config already replicates across three zones.
📊 Limit: Cloud SQL Enterprise Plus failover RTO is documented at under 60 seconds for most workloads; Cloud SQL Enterprise is documented at under 120 seconds. AlloyDB regional failover is documented at under 60 seconds. Spanner failure recovery within a regional config is automatic and sub-second.
⚠️ Anti-Pattern: Creating a Cloud SQL instance as zonal and planning to promote it to regional later under traffic. The conversion rebuilds storage and pauses writes. Pin the HA posture at create time.
🎯 Scenario: A team needs a Postgres 15 OLTP database for an orders ledger with a 99.99% availability SLO and a 50 ms p95 read SLO at 8 vCPU peak load. The right deployment is Cloud SQL Enterprise Plus, REGIONAL availability, db-perf-optimized-N-8 tier, Data Cache enabled, PITR on, with a cross-region read replica in us-east4 sized at the same tier for DR. Wrong path: a single ZONAL instance with manual snapshots, which cannot meet four nines and has no warm read path.
Decision Anchor: Choose Cloud SQL REGIONAL when the workload is single-region OLTP that fits Postgres, MySQL, or SQL Server semantics; choose AlloyDB REGIONAL when the workload is Postgres-compatible and benefits from the columnar engine or AlloyDB AI extensions; choose Spanner multi-region when global strong consistency is non-negotiable; choose Bigtable multi-cluster when latency-sensitive wide-column workloads need zonal or regional failover; choose Firestore multi-region for document workloads that must survive a regional outage.
The Terraform equivalent of the Cloud SQL provisioning pins the same flags and adds explicit dependency on the network and KMS key. This is the recommended path for any environment beyond a one-off experiment, because it captures HA as code and lets the engineer recreate the topology in a recovery scenario.
resource "google_sql_database_instance" "orders_prod" {
name = "ordersdb-prod"
database_version = "POSTGRES_15"
region = "us-central1"
deletion_protection = true
encryption_key_name = google_kms_crypto_key.sql.id
settings {
tier = "db-perf-optimized-N-8"
edition = "ENTERPRISE_PLUS"
availability_type = "REGIONAL"
data_cache_config { data_cache_enabled = true }
backup_configuration {
enabled = true
start_time = "02:00"
point_in_time_recovery_enabled = true
transaction_log_retention_days = 7
}
ip_configuration {
ipv4_enabled = false
private_network = data.google_compute_network.db_vpc.id
}
maintenance_window {
day = 7
hour = 4
update_track = "stable"
}
}
depends_on = [google_kms_crypto_key_iam_member.sql_admin]
}
💡 Exam Trap: A Cloud SQL HA instance still needs PITR enabled separately. HA gives zonal failover for the live instance; PITR gives recovery from logical corruption. Both are required for the typical four-nines SLO with a one-hour RPO.
⚠️ Anti-Pattern: Storing the Cloud SQL admin password in the Terraform state by passing it as a
root_passwordliteral. Use Secret Manager, fetch through a data source, and rotate the secret out of band. The state file is not a vault.
Testing high availability and disaster recovery strategies periodically
A standby that has never failed over is a hypothesis, not a guarantee.
HA testing is a scheduled operational duty, not a one-time validation, and the cadence depends on workload criticality.
For four-nines workloads a quarterly schedule is typical; for less critical tiers a semi-annual schedule is common.
The mechanics differ per engine, and the runbook codifies preconditions, success gates, and rollback.
For Cloud SQL, the failover command is gcloud sql instances failover, which promotes the standby to primary and demotes the former primary to a standby role after recovery.
The command takes seconds to start and the instance endpoint moves DNS to the new primary; existing connections drop and reconnect.
gcloud sql instances failover ordersdb-prod \
--async
gcloud sql operations wait OPERATION_ID \
--project=PROJECT_ID
psql "host=ordersdb-prod.PROJECT.us-central1.sql.goog \
user=app dbname=orders sslmode=verify-ca" \
-c "select pg_is_in_recovery(), inet_server_addr();"
The wait command surfaces failover completion. Verification is more than the gcloud call returning success:
- The engineer must confirm read-write traffic resumes.
- Replication lag on cross-region replicas catches back up.
- The new primary holds the same row count as the source of truth.
- Application metrics return to baseline.
How it works
For AlloyDB, the equivalent operation is gcloud alloydb instances failover on the primary instance of a regional cluster.
- The standby in the alternate zone becomes the new primary.
- The read pool re-points.
- The cluster endpoint stays the same.
gcloud alloydb instances failover orders-primary \
--cluster=orders-cluster \
--region=us-central1
gcloud alloydb operations list \
--region=us-central1 \
--filter="metadata.target=projects/PROJECT_ID/locations/us-central1/clusters/orders-cluster/instances/orders-primary"
For Spanner, in-region failover is automatic and not user-triggered. The DR rehearsal model is different: the engineer tests recovery from a backup or a cross-region copy, validates version_retention_period semantics, or in a multi-region instance simulates a region-level read-only fallback.
There is no gcloud spanner instances failover because the leader replica is elected by the protocol per split, not per instance.
For Bigtable, failover testing means changing the app profile routing policy. A multi-cluster app profile with --route-any lets the client read from either cluster. A single-cluster app profile pins to one cluster, and the rehearsal flips it to the alternate cluster to validate the failure path.
gcloud bigtable app-profiles update primary-routing \
--instance=events-prod \
--route-to=events-c2 \
--transactional-writes \
--force
💡 Exam Trap: A Bigtable app profile with multi-cluster routing does not give transactional writes across clusters. The
--transactional-writesflag is mutually exclusive with multi-cluster routing because writes commit per-cluster. Questions that ask for "single-row atomic writes with multi-cluster availability" usually expect the answer "use single-cluster routing with a failover plan."
For Firestore, regional outage is simulated through application-level testing because the engine handles cross-zone failover internally for regional locations and cross-region failover transparently for multi-region locations.
The rehearsal validates that the application code retries the SDK call on the documented retriable error codes (UNAVAILABLE, DEADLINE_EXCEEDED, ABORTED) and that observed read-after-write semantics still match the location class.
In practice
DR rehearsals extend HA testing with restore from backup.
- Cloud SQL clones a PITR target into a new instance with
gcloud sql instances clone. - AlloyDB uses
clusters restorefrom continuous backup. - Spanner uses
databases restorefrom a backup.
Each restores into a NEW database or instance: there is no in-place restore.
gcloud sql instances clone ordersdb-prod ordersdb-restore-test \
--point-in-time="2025-04-15T03:00:00Z"
gcloud alloydb clusters restore orders-restore-test \
--region=us-central1 \
--source-cluster=projects/PROJECT_ID/locations/us-central1/clusters/orders-cluster \
--point-in-time="2025-04-15T03:00:00Z" \
--kms-key=projects/keys-prod/locations/us-central1/keyRings/alloydb/cryptoKeys/orders
gcloud spanner databases restore --instance=orders-prod-recovery \
--backup=projects/PROJECT_ID/instances/orders-prod/backups/orders-2025-04-15 \
--restore-db=orders-recovery
📊 Limit: Cloud SQL automated backups can retain between 1 and 365 days; PITR retention is bound by
--retained-transaction-log-days, which ranges from 1 to 7 days. AlloyDB continuous backup retains up to 35 days. Spanner backups can retain up to 1 year, andversion_retention_periodfor PITR ranges from 1 hour to 7 days.
Use the wall-clock timer on every rehearsal. The rehearsal output feeds the actual measured RTO and RPO into the runbook so the SLO commitment is grounded in measurement instead of a vendor promise.
import time
from google.cloud import sql_v1
def measured_failover(project, instance):
client = sql_v1.SqlInstancesServiceClient()
start = time.monotonic()
op = client.failover(project=project, instance=instance, body={})
while True:
status = client.get(project=project, instance=instance).state
if status == "RUNNABLE":
elapsed = time.monotonic() - start
return elapsed
time.sleep(2)
🎯 Scenario: A platform team owns 14 Cloud SQL instances at four-nines SLO. The on-call recorded a real failover at 95 seconds during a zonal outage, but the SLO assumed 60 seconds. The investigation found the workload kept long-running transactions open and the standby waited for the WAL apply to catch up. The fix: enforce
statement_timeoutand add a synthetic transaction-age alert. Quarterly failover testing exists precisely so the team learns this before customers do.
⚠️ Anti-Pattern: Treating "the runbook says the standby is in zone B" as proof the standby is healthy. The standby state is observable through
gcloud sql instances describeundersettings.backupConfigurationand the replication lag metriccloudsql.googleapis.com/database/replication/replica_lag. Watch the metric, not the runbook claim.
Decision Anchor: Schedule failover and DR rehearsals at a cadence proportional to SLO criticality. Choose a quarterly cadence for four-nines workloads and a semi-annual cadence for three-nines workloads.
Run rehearsals in the same window every quarter, in a low-traffic period that still has live customer traffic, because rehearsing in an idle environment does not catch the workload-driven failure modes.
💡 Exam Trap: Spanner does not need a failover test because the cluster handles replica failure automatically. The DR test for Spanner is a backup restore or a point-in-time recovery test, not a failover command. Questions that ask "how do we test Spanner failover" expect the restore answer, not a failover command.
# dr-rehearsal-quarterly.yaml - Cloud Workflows definition
main:
params: [args]
steps:
- capture_baseline:
call: googleapis.monitoring.v3.projects.timeSeries.query
args:
name: projects/${args.project}
body:
query: "fetch cloudsql_database | metric 'cloudsql.googleapis.com/database/up' | within 5m"
result: baseline
- trigger_failover:
call: googleapis.sqladmin.v1.instances.failover
args:
project: ${args.project}
instance: ${args.instance}
result: op
- wait_for_completion:
call: sys.sleep
args:
seconds: 60
- verify_health:
call: googleapis.sqladmin.v1.instances.get
args:
project: ${args.project}
instance: ${args.instance}
result: post_state
- record_results:
call: googleapis.bigquery.v2.jobs.insert
args:
projectId: ${args.project}
body:
configuration:
query:
query: "INSERT INTO ops.dr_rehearsals VALUES (...)"
useLegacySql: false
Setting up multi-regional replication for databases
Key points
Multi-regional replication divides into two categories:
- synchronous, where every write commits in every region before acknowledging
- asynchronous, where the primary acknowledges locally and ships changes to remote regions on its own timeline
Each engine sits at a different point on this axis.
The deployment cost, the consistency contract, and the failure semantics flow from the choice.
Spanner multi-region configurations replicate synchronously through Paxos quorum.
The nam6 config places voting replicas in three United States regions; eur3 spans Belgium and Netherlands; nam-eur-asia1 spans three continents.
Every write needs a quorum across the voting replicas, which adds the inter-region round-trip to write latency.
The trade is hard: there is no way to "make Spanner multi-region faster" without dropping a voting replica.
gcloud spanner instances create orders-global \
--config=nam-eur-asia1 \
--processing-units=4000 \
--description="Orders global tier" \
--edition=ENTERPRISE_PLUS
gcloud spanner instances list-instance-configs --filter="name~nam"
The list-instance-configs call surfaces the Spanner multi-region configs available in the project, which is the supported way to discover which placements are permitted by the org policy. The output names the leader region for each config; placing the bulk of writer traffic in the leader region reduces tail latency.
📊 Limit: Spanner multi-region configurations carry write latency typically in the 50 ms to 200 ms range for single-row writes, dominated by the cross-region Paxos round-trip. Spanner regional configurations carry write latency typically under 10 ms.
Cloud SQL cross-region replication is asynchronous. A cross-region read replica streams logical changes from the primary region. RPO is bounded by replication lag; RTO is bounded by promotion time plus DNS or connection-string rewiring.
gcloud sql instances create ordersdb-replica-east \
--master-instance-name=ordersdb-prod \
--region=us-east4 \
--availability-type=REGIONAL \
--tier=db-perf-optimized-N-8 \
--storage-type=SSD \
--storage-size=500 \
--disk-encryption-key=projects/keys-prod/locations/us-east4/keyRings/sql/cryptoKeys/orders \
--replica-type=READ
Promotion of a cross-region replica to a standalone primary is permanent; the replica becomes a writable instance and the source instance no longer replicates to it. After promotion the application must be re-pointed; cross-region read replicas attached to the original primary do not become attached to the promoted replica.
gcloud sql instances promote-replica ordersdb-replica-east
💡 Exam Trap: A promoted replica is a new primary, not a new replica of the original. If the rehearsal expects the original primary to become the new replica of the new primary, the engineer must set up a new replica explicitly after promotion. The "reverse" path is not automatic.
AlloyDB cross-region replication uses a secondary cluster. A secondary cluster sits in another region, runs read-only by default, and accepts a promotion call to become a standalone primary cluster. The replication is asynchronous, similar in semantics to Cloud SQL cross-region replicas, but the cluster scope means the secondary contains every database from the source cluster.
gcloud alloydb clusters create-secondary orders-cluster-dr \
--region=us-east4 \
--primary-cluster=projects/PROJECT_ID/locations/us-central1/clusters/orders-cluster \
--kms-key=projects/keys-prod/locations/us-east4/keyRings/alloydb/cryptoKeys/orders
gcloud alloydb instances create orders-dr-reader \
--cluster=orders-cluster-dr \
--region=us-east4 \
--instance-type=READ_POOL \
--read-pool-node-count=2 \
--cpu-count=8
Promotion of an AlloyDB secondary cluster is gcloud alloydb clusters promote orders-cluster-dr, which severs the replication link and turns the secondary into a standalone primary cluster.
Bigtable replication runs through the multi-cluster topology defined at instance create.
- Adding a cluster in a remote region copies data asynchronously.
- The engineer configures replication consistency through app profiles.
- Single-cluster routing keeps reads strongly consistent on the cluster they hit.
- Multi-cluster routing gives high availability with eventually-consistent reads across clusters.
gcloud bigtable clusters create events-eu \
--instance=events-prod \
--zone=europe-west1-b \
--num-nodes=6 \
--autoscaling-min-nodes=4 \
--autoscaling-max-nodes=12 \
--autoscaling-cpu-target=70
gcloud bigtable app-profiles update primary-routing \
--instance=events-prod \
--route-any \
--no-transactional-writes
The replication semantics for Bigtable across clusters are eventually consistent.
A row written to cluster A becomes visible on cluster B after a propagation delay that depends on cluster load. Strong consistency requires single-cluster routing.
Firestore expresses multi-regional replication through the location selection at database creation.
Multi-region locations nam5 and eur3 are the supported placements; both maintain strongly-consistent reads within their participating regions and tolerate a region outage transparently.
gcloud firestore databases create \
--database=global-orders \
--location=eur3 \
--type=firestore-native \
--kms-key-name=projects/keys-prod/locations/eur3/keyRings/firestore/cryptoKeys/orders
📊 Limit: Firestore multi-region locations cannot be migrated to a different location after creation. The engineer must export, recreate the database in the new location, and import. The
delete-protectionflag is independent of this limitation.
💡 Exam Trap: "Multi-region" in Spanner means synchronous Paxos; "multi-region" in Cloud SQL or AlloyDB means an asynchronous replica or secondary cluster; "multi-region" in Bigtable means asynchronous cross-cluster replication with app-profile-driven consistency; "multi-region" in Firestore means a built-in multi-region location with internal strong consistency guarantees. The same word means different replication contracts per engine.
Replication Topology Across Engines
🎯 Scenario: A trading platform demands global write availability with a 99.999% SLO and tolerates 100 ms of write latency. Spanner multi-region
nam-eur-asia1is the only managed engine that meets the consistency contract at that SLO. A Cloud SQL primary plus cross-region replica posture would either lose data on regional outage (async replication gap) or require dual-writes that violate single-source-of-truth semantics.
⚠️ Anti-Pattern: Using a Cloud SQL cross-region read replica as a "hot standby" with sub-second RPO. Cloud SQL replication is asynchronous; the lag during incidents can extend to minutes. If the contract is RPO under 1 second, the answer is Spanner, not Cloud SQL replicas.
Decision Anchor: Choose Spanner multi-region when the contract demands synchronous cross-region durability or write availability through a regional outage. Choose Cloud SQL cross-region replicas or AlloyDB cross-region secondary clusters when the workload is regional-primary and the cross-region copy serves as a warm DR target with documented async lag.
Choose Bigtable multi-cluster when wide-column workloads need cross-region distribution with app-profile-controlled consistency. Choose Firestore multi-region locations when document workloads need transparent regional resilience.
The Terraform module that pins a Cloud SQL primary plus cross-region replica plus the IAM and KMS bindings looks like this:
module "ordersdb" {
source = "./modules/cloud-sql-ha"
project = "orders-prod"
primary_region = "us-central1"
replica_regions = ["us-east4"]
database_version = "POSTGRES_15"
tier = "db-perf-optimized-N-8"
edition = "ENTERPRISE_PLUS"
data_cache_enabled = true
pitr_enabled = true
pitr_retention_days = 7
kms_key_per_region = {
"us-central1" = "projects/keys-prod/locations/us-central1/keyRings/sql/cryptoKeys/orders"
"us-east4" = "projects/keys-prod/locations/us-east4/keyRings/sql/cryptoKeys/orders"
}
iam_policy = local.ordersdb_iam
}
Assessing requirements for read replicas
Read replica sizing is a math problem with three inputs: measured read QPS at peak, per-node QPS budget for the chosen tier, and headroom for replica restart, replica lag, and traffic spikes.
The formula is replicas = ceiling( peak_read_qps / per_node_qps_budget * (1 + restart_headroom + lag_headroom) ).
The engineer derives per_node_qps_budget from load tests against the chosen tier, not from a vendor table.
For Cloud SQL Postgres read replicas, the per-node QPS budget depends on the tier and the workload shape.
A db-perf-optimized-N-8 instance under a typical read-heavy OLTP workload sustains roughly 2,000 to 4,000 reads per second per replica, depending on average row size and index coverage.
- Restart headroom of 1.5x accounts for the time a replica spends rebuilding cache after a maintenance event.
- Lag headroom of 1.2x accounts for the spike when one replica falls behind and routing shifts to the others.
gcloud sql instances create ordersdb-replica-1 \
--master-instance-name=ordersdb-prod \
--region=us-central1 \
--availability-type=REGIONAL \
--tier=db-perf-optimized-N-8 \
--storage-type=SSD \
--storage-size=500 \
--disk-encryption-key=projects/keys-prod/locations/us-central1/keyRings/sql/cryptoKeys/orders \
--replica-type=READ
Routing matters. A Cloud SQL Postgres deployment with three read replicas exposes the primary endpoint and per-replica endpoints; the application or proxy (PgBouncer, pgcat) routes read queries across the replica set.
Without a routing layer the application connects to one replica directly and the load distribution is single-point.
AlloyDB read replicas are read pool nodes, not separate instances. A single read pool can hold up to 20 nodes, each running the same data. The cluster endpoint plus the read pool endpoint give the application separate URLs for writer and reader traffic. Scaling the read pool is a single command.
gcloud alloydb instances update orders-read-pool \
--cluster=orders-cluster \
--region=us-central1 \
--read-pool-node-count=8
📊 Limit: AlloyDB read pools support up to 20 nodes per pool. Multiple pools per cluster are supported. Read pool nodes inherit the columnar engine setting of the primary, which keeps analytical query performance consistent across the read fleet.
Spanner does not have separate read replicas as a deployment concept. Every node in a Spanner instance serves both reads and writes, and the engineer scales by adding processing units. Read-only replicas are baked into multi-region configurations: nam6 has read-only replicas in regions outside the voting quorum. The deployment lever is --processing-units (or --nodes), not a replica count.
gcloud spanner instances update orders-prod \
--processing-units=4000
Bigtable scales reads through cluster node count and through multi-cluster routing. A two-cluster instance with multi-cluster routing roughly doubles read capacity; adding clusters in additional zones or regions adds linear read throughput at the cost of asynchronous replication.
gcloud bigtable clusters update events-c1 \
--instance=events-prod \
--num-nodes=12 \
--autoscaling-min-nodes=8 \
--autoscaling-max-nodes=24
Firestore Native scales reads automatically through the managed storage layer. The per-collection limits are the relevant ceilings: per-document write throughput is bounded at roughly one write per second sustained per document, and per-database operations are bounded by the regional or multi-regional location's documented quota. There is no replica-count knob.
💡 Exam Trap: Spanner read-only replicas exist only in multi-region configurations. A question that asks "how do we add read replicas to a regional Spanner instance to scale reads" expects the answer "increase processing units," not "add a read replica," because regional Spanner does not expose read-only replicas as a separate deployable.
Read replica routing requires application changes. PgBouncer in front of Cloud SQL routes writes to the primary and reads to a replica set; the application uses two connection strings or PgBouncer's prepared-transaction routing. Without this layer the application connects to the primary for everything and the replicas idle.
# pgbouncer.ini fragment for read-write split routing
[databases]
orders_writer = host=ordersdb-prod.PROJECT.us-central1.sql.goog port=5432 dbname=orders pool_mode=transaction
orders_reader = host=ordersdb-replica-pool.example.com port=5432 dbname=orders pool_mode=transaction
Replica lag is the operational ceiling on stale reads. A 200 ms lag is unnoticeable for many workloads; a 30 second lag is a customer-visible problem for any workload that reads its own writes. The application either tolerates lag (eventually-consistent reads, retry on miss) or sends critical reads to the primary (SET TRANSACTION READ ONLY on the primary plus a replica-affinity annotation on non-critical reads).
📊 Limit: Cloud SQL replication lag is exposed through
cloudsql.googleapis.com/database/replication/replica_lag, in seconds. Alert at 30 seconds for warning and 300 seconds for paging. AlloyDB exposes replication lag throughalloydb.googleapis.com/instance/postgres/replication_lag. Spanner exposes per-replica staleness throughspanner.googleapis.com/instance/leader_percentageandreplication/delay_seconds.
🎯 Scenario: An e-commerce team's checkout page reads "last 10 orders" from a Cloud SQL read replica. During a sale the replica lag jumps to 45 seconds and customers see "your recent order is missing." The fix: tag the "last 10 orders" query as primary-affinity through the routing proxy, accepting the latency hit during peak so the customer-visible correctness contract holds. Read replicas are not free; they trade lag for capacity.
⚠️ Anti-Pattern: Adding read replicas without a routing layer and expecting the application to magically distribute reads. The instance endpoint always resolves to the primary. The engineer must configure either a connection-string-per-replica pattern, a PgBouncer routing layer, or an application-level driver feature like PgJDBC's
targetServerType=preferSecondary.
Decision Anchor: Choose AlloyDB read pool when the workload is Postgres-compatible and benefits from a single horizontal scale knob. Choose Cloud SQL cross-region read replicas when the read-heavy workload also needs cross-region resilience.
Choose Spanner processing-unit scaling when the workload is on Spanner and the scale knob is a single number, not a replica count. Choose Bigtable multi-cluster routing when the workload is wide-column and read distribution can tolerate eventually-consistent semantics.
# Read-affinity wrapper around psycopg
from contextlib import contextmanager
import psycopg
WRITER_DSN = "postgresql://app@orders-writer/orders?sslmode=verify-ca"
READER_DSN = "postgresql://app@orders-reader/orders?sslmode=verify-ca"
@contextmanager
def get_conn(role: str):
dsn = WRITER_DSN if role == "writer" else READER_DSN
with psycopg.connect(dsn) as conn:
yield conn
def list_recent_orders(customer_id: int):
with get_conn("writer") as conn: # primary-affinity for read-after-write
return conn.execute(
"select id, total from orders where customer_id = %s order by id desc limit 10",
(customer_id,),
).fetchall()
def list_product_reviews(product_id: int):
with get_conn("reader") as conn: # replica-affinity for stale-tolerant
return conn.execute(
"select rating, body from reviews where product_id = %s",
(product_id,),
).fetchall()
Automating database instance provisioning
A production database is provisioned through code, reviewed through pull requests, and applied through a release pipeline.
Manual gcloud is reserved for break-glass operations and verification. Three automation surfaces matter for the certification:
- Terraform with the Google provider
- Config Connector for GKE-managed control planes
- Cloud Deploy plus Cloud Build for the release pipeline
Workflows orchestrates ordered provisioning when multiple resources have dependencies that exceed Terraform's apply granularity.
A Terraform module for an HA Cloud SQL Postgres instance with a cross-region read replica is the canonical example.
The module pins the HA flag, the encryption key, the network, the PITR retention, and the labels that downstream monitoring and billing exports rely on.
Output values expose the primary endpoint, the replica endpoint, the IAM service account, and the Secret Manager secret IDs.
variable "name" { type = string }
variable "primary_region" { type = string }
variable "replica_regions" { type = list(string) default = [] }
variable "tier" { type = string default = "db-perf-optimized-N-8" }
variable "edition" { type = string default = "ENTERPRISE_PLUS" }
resource "google_sql_database_instance" "primary" {
name = var.name
database_version = "POSTGRES_15"
region = var.primary_region
deletion_protection = true
encryption_key_name = var.kms_key_per_region[var.primary_region]
settings {
tier = var.tier
edition = var.edition
availability_type = "REGIONAL"
data_cache_config { data_cache_enabled = true }
backup_configuration {
enabled = true
start_time = "02:00"
point_in_time_recovery_enabled = true
transaction_log_retention_days = 7
}
ip_configuration {
ipv4_enabled = false
private_network = var.private_network
}
maintenance_window {
day = 7
hour = 4
update_track = "stable"
}
insights_config {
query_insights_enabled = true
query_string_length = 4500
record_application_tags = true
record_client_address = true
}
user_labels = {
tier = "primary"
sla = "four-nines"
owner = "orders-platform"
environment = "prod"
}
}
}
resource "google_sql_database_instance" "replica" {
for_each = toset(var.replica_regions)
name = "${var.name}-replica-${each.key}"
database_version = google_sql_database_instance.primary.database_version
region = each.key
master_instance_name = google_sql_database_instance.primary.name
deletion_protection = true
encryption_key_name = var.kms_key_per_region[each.key]
replica_configuration {
failover_target = false
}
settings {
tier = var.tier
edition = var.edition
availability_type = "REGIONAL"
user_labels = {
tier = "replica"
sla = "four-nines"
owner = "orders-platform"
environment = "prod"
}
}
}
Config Connector exposes the same resources through Kubernetes Custom Resource Definitions. A platform team that already runs GKE and uses Kubernetes-native promotion (GitOps with Argo CD or Cloud Deploy with Kubernetes targets) can declare the database alongside the application.
apiVersion: sql.cnrm.cloud.google.com/v1beta1
kind: SQLInstance
metadata:
name: ordersdb-prod
namespace: orders
spec:
databaseVersion: POSTGRES_15
region: us-central1
settings:
tier: db-perf-optimized-N-8
edition: ENTERPRISE_PLUS
availabilityType: REGIONAL
backupConfiguration:
enabled: true
pointInTimeRecoveryEnabled: true
startTime: "02:00"
transactionLogRetentionDays: 7
ipConfiguration:
ipv4Enabled: false
privateNetworkRef:
name: db-vpc
dataCacheConfig:
dataCacheEnabled: true
encryptionKMSCryptoKeyRef:
external: projects/keys-prod/locations/us-central1/keyRings/sql/cryptoKeys/orders
Cloud Build plus Cloud Deploy wraps the Terraform plan and apply in a tested pipeline. The pipeline runs terraform plan on pull requests, posts the diff as a PR comment, and applies on merge to the protected branch through a service account with roles/cloudsql.admin, roles/alloydb.admin, roles/spanner.admin, roles/bigtable.admin, and roles/firestore.serviceAgent scoped to the target project.
# cloudbuild.yaml for the database platform pipeline
steps:
- id: terraform-init
name: hashicorp/terraform:1.9.5
entrypoint: terraform
args: ["init", "-backend-config=bucket=orders-tf-state-prod"]
dir: terraform/orders-prod
- id: terraform-plan
name: hashicorp/terraform:1.9.5
entrypoint: terraform
args: ["plan", "-out=tfplan", "-var-file=prod.tfvars"]
dir: terraform/orders-prod
- id: policy-check
name: openpolicyagent/conftest:latest
args: ["test", "tfplan", "--policy", "policies/", "--namespace=database"]
dir: terraform/orders-prod
waitFor: ["terraform-plan"]
- id: terraform-apply
name: hashicorp/terraform:1.9.5
entrypoint: terraform
args: ["apply", "-auto-approve", "tfplan"]
dir: terraform/orders-prod
waitFor: ["policy-check"]
serviceAccount: projects/orders-prod/serviceAccounts/db-platform@orders-prod.iam.gserviceaccount.com
options:
logging: CLOUD_LOGGING_ONLY
Workflows orchestrate multi-step provisioning that does not fit cleanly into Terraform's apply graph. For example, creating a Spanner instance, waiting for it to become RUNNABLE, creating databases, applying schema, granting IAM, and registering it with a service catalog: each step has a discrete success criterion and a discrete failure handler.
main:
params: [args]
steps:
- create_instance:
call: googleapis.spanner.v1.projects.instances.create
args:
parent: projects/${args.project}
body:
instanceId: ${args.instance}
instance:
config: projects/${args.project}/instanceConfigs/regional-us-central1
displayName: ${args.display_name}
processingUnits: 2000
edition: ENTERPRISE_PLUS
result: instance_op
- wait_for_runnable:
call: googleapis.spanner.v1.projects.instances.operations.get
args:
name: ${instance_op.name}
result: op_state
next: check_state
- check_state:
switch:
- condition: ${op_state.done == true}
next: create_database
next: wait_for_runnable
- create_database:
call: googleapis.spanner.v1.projects.instances.databases.create
args:
parent: projects/${args.project}/instances/${args.instance}
body:
createStatement: "CREATE DATABASE `${args.database}`"
databaseDialect: GOOGLE_STANDARD_SQL
💡 Exam Trap: Terraform
deletion_protection = trueongoogle_sql_database_instanceblocksterraform destroy. It does NOT blockgcloud sql instances delete. For full destroy protection, combine the Terraform setting with an organization policy that deniescloudsql.instances.deleteoutside a tightly-scoped service account.
⚠️ Anti-Pattern: Storing the Terraform service account JSON key on a developer laptop. Use Workload Identity Federation for CI/CD, or run Terraform from Cloud Build with an attached service account. Long-lived keys are the most common compromise path documented in incident reviews.
📊 Limit: Cloud Deploy targets support custom canary phases; the database deployment use case typically configures a single phase with a verification step that runs schema migration and HA checks before promoting the change to the next environment.
🎯 Scenario: A platform team needs to spin up an isolated database environment per pull request for integration testing. The Terraform module exposes a
pr_numbervariable; the Cloud Build pipeline calls the module with--var=pr_number=$_PR_NUMBERand provisions a Cloud SQL zonal instance with PITR off and a 24-hour TTL labeledpurpose=pr-ephemeral. A nightly Workflows job deletes labeled instances older than 24 hours. The full pattern is Terraform plus Cloud Build plus Workflows, not a manual gcloud script.
⚠️ Anti-Pattern: Using
terraform importrepeatedly to bring drift back into state. Drift is a signal that someone bypassed the pipeline. Investigate, repair the underlying access control, and document the break-glass operation in a runbook. Importing drift hides the failure.
Decision Anchor: Choose Terraform for greenfield database deployments and for teams running infrastructure-as-code at scale. Choose Config Connector when the platform already runs GKE with GitOps and the team wants databases declared next to the workloads that use them.
Use Workflows when the provisioning sequence has discrete ordered steps with per-step success criteria. Use Cloud Build plus Cloud Deploy as the release pipeline regardless of the chosen IaC tool.
# Break-glass verification commands that should NEVER be the primary provisioning path
gcloud sql instances describe ordersdb-prod --format=json | jq '.settings.availabilityType, .settings.backupConfiguration.pointInTimeRecoveryEnabled'
gcloud alloydb clusters describe orders-cluster --region=us-central1 --format=json | jq '.continuousBackupConfig.enabled'
gcloud spanner instances describe orders-prod --format=json | jq '.processingUnits, .config'
gcloud bigtable instances describe events-prod --format=json | jq '.clusters[].location, .clusters[].nodeCount'
Configuring monitoring for highly available databases
Monitoring an HA database is not the same as monitoring a single instance. The engineer measures four pillars:
- instance availability (is the primary serving traffic)
- replication topology health (is the standby or replica in the expected state)
- replication lag against budget (is the asynchronous copy within the RPO contract)
- customer-observed error rate (does the application see retriable failures within the SLO)
Each pillar maps to a Cloud Monitoring metric, an SLI, an alert policy, and a dashboard panel.
Cloud Monitoring exposes per-engine metrics under predictable namespaces: cloudsql.googleapis.com, alloydb.googleapis.com, spanner.googleapis.com, bigtable.googleapis.com, and firestore.googleapis.com.
The vital metric for instance availability is the up series (Cloud SQL: cloudsql.googleapis.com/database/up; AlloyDB: alloydb.googleapis.com/instance/state).
Replication lag is replication/replica_lag for Cloud SQL and instance/postgres/replication_lag for AlloyDB.
Spanner exposes leader fraction and CPU; Bigtable exposes per-cluster CPU and storage; Firestore exposes operation counts and error rates per type.
An SLI for instance availability is the ratio of successful health-check probes to total probes over a window.
The SLO commits to a numeric availability target (99.95%, 99.99%, 99.999%) and the alert policy fires on burn-rate windows that catch both fast and slow burns.
# Cloud Monitoring SLO definition for Cloud SQL availability
displayName: "ordersdb-prod availability"
serviceLevelIndicator:
basicSli:
availability: {}
location: ["us-central1"]
goal: 0.9995
rollingPeriod: "2592000s" # 30 days
# Burn-rate alert policy: fast-burn 14.4x for 1h window, slow-burn 6x for 6h window
displayName: "ordersdb-prod SLO burn"
conditions:
- displayName: "Fast burn 1h window"
conditionThreshold:
filter: |
select_slo_burn_rate(
"projects/orders-prod/services/sql-orders/serviceLevelObjectives/availability",
"3600s"
)
comparison: COMPARISON_GT
thresholdValue: 14.4
duration: "600s"
- displayName: "Slow burn 6h window"
conditionThreshold:
filter: |
select_slo_burn_rate(
"projects/orders-prod/services/sql-orders/serviceLevelObjectives/availability",
"21600s"
)
comparison: COMPARISON_GT
thresholdValue: 6.0
duration: "1800s"
combiner: OR
notificationChannels:
- projects/orders-prod/notificationChannels/orders-oncall-pagerduty
Replication lag alerts use a different shape. The lag metric is a gauge in seconds; the alert fires when the gauge crosses an absolute threshold for a sustained window. The threshold pair "warning at 30 seconds, page at 300 seconds" covers most async workloads; tighter contracts demand tighter thresholds.
displayName: "ordersdb-prod replica lag"
conditions:
- displayName: "Replica lag over 300 seconds"
conditionThreshold:
filter: |
metric.type="cloudsql.googleapis.com/database/replication/replica_lag"
resource.type="cloudsql_database"
metadata.user_labels.tier="replica"
metadata.user_labels.environment="prod"
comparison: COMPARISON_GT
thresholdValue: 300
duration: "300s"
aggregations:
- alignmentPeriod: "60s"
perSeriesAligner: ALIGN_MAX
combiner: OR
notificationChannels:
- projects/orders-prod/notificationChannels/orders-oncall-pagerduty
📊 Limit: Cloud Monitoring alignment periods range from 60 seconds to 1 hour for built-in aligners. The shortest practical alert latency is in the 30-second to 90-second range depending on the alignment period plus the duration of the conditional window.
Synthetic checks complement metric-based monitoring. A Cloud Monitoring uptime check that runs a SQL select 1 through a public proxy (or an authenticated probe through a Cloud Run service inside the VPC) captures the customer-observed availability from a vantage point outside the data plane. For private-IP databases, the probe runs as a Cloud Run job inside the VPC.
# Cloud Run synthetic probe for AlloyDB
import os
import time
import psycopg
from google.cloud import monitoring_v3
PROJECT = os.environ["PROJECT_ID"]
DSN = os.environ["ALLOYDB_DSN"]
def write_metric(value: float):
client = monitoring_v3.MetricServiceClient()
series = monitoring_v3.TimeSeries()
series.metric.type = "custom.googleapis.com/alloydb/synthetic_probe_latency"
series.resource.type = "global"
point = series.points.add()
point.interval.end_time.seconds = int(time.time())
point.value.double_value = value
client.create_time_series(name=f"projects/{PROJECT}", time_series=[series])
def probe():
t0 = time.monotonic()
with psycopg.connect(DSN, connect_timeout=5) as conn:
conn.execute("select 1").fetchone()
write_metric(time.monotonic() - t0)
if __name__ == "__main__":
probe()
Cloud Logging exclusion filters keep the log buckets focused. A Cloud SQL primary writes verbose connection logs by default; the engineer routes severity-INFO logs to a Cloud Storage archive bucket with a 30-day retention policy and keeps the _Default bucket trimmed to severity-WARNING and above, which preserves the alerting signal without paying for noise.
gcloud logging sinks create cloudsql-archive \
storage.googleapis.com/projects/orders-prod/buckets/cloudsql-log-archive \
--log-filter='resource.type="cloudsql_database" AND severity<WARNING' \
--include-children
Dashboards group the four pillars in a single view per database. The dashboard layout uses scorecards for SLI burn rate, stacked-area charts for replication lag across replicas, time-series for CPU and memory, and a heatmap for slow-query duration distribution. A team owning multiple databases templates the dashboard and renders one instance per database through Terraform's google_monitoring_dashboard resource.
resource "google_monitoring_dashboard" "ordersdb" {
dashboard_json = templatefile("${path.module}/dashboards/cloudsql-ha.json.tpl", {
instance_id = google_sql_database_instance.primary.name
project_id = var.project
replicas = [for r in google_sql_database_instance.replica : r.name]
})
}
Quota monitoring rounds out the picture. A Cloud SQL or AlloyDB project tracks quota consumption through serviceruntime.googleapis.com/quota/allocation/usage and serviceruntime.googleapis.com/quota/rate/net_usage. An alert at 80% consumption gives operations a window to request a quota increase before traffic growth blocks new connections or new instances.
displayName: "Cloud SQL connection quota at 80 percent"
conditions:
- displayName: "Connection quota usage over 80 percent"
conditionThreshold:
filter: |
metric.type="serviceruntime.googleapis.com/quota/allocation/usage"
resource.type="consumer_quota"
metric.label.quota_metric="sqladmin.googleapis.com/connection_count"
comparison: COMPARISON_GT
thresholdValue: 0.80
duration: "600s"
aggregations:
- alignmentPeriod: "300s"
perSeriesAligner: ALIGN_MEAN
combiner: OR
💡 Exam Trap: Replication lag alerts on a Cloud SQL primary's
upmetric do not catch a stuck replica. The lag metric is per-replica. Alerts must filter on the replica label, not the primary.
💡 Exam Trap: A Cloud Monitoring uptime check from the public internet against a private-IP Cloud SQL instance fails because the probe cannot reach the private endpoint. The supported pattern is a synthetic probe running as a Cloud Run service or Cloud Run job inside the VPC.
📊 Limit: Cloud Monitoring metric retention is documented at 24 months for built-in metrics and at user-controlled retention for custom metrics. SLO-derived metrics inherit the underlying SLI's retention.
🎯 Scenario: A team owns an AlloyDB cluster with a cross-region secondary at us-east4. The on-call wakes to an alert that the secondary's replication lag has crossed 5 minutes. The dashboard shows primary CPU at 95% and a long-running write transaction on the primary. The root cause: a maintenance job ran outside the deny-maintenance period and consumed write capacity. The fix: kill the maintenance job, validate lag returns to baseline, then schedule the job inside the deny-maintenance window for next time. The monitoring caught the issue 12 minutes before the secondary would have fallen outside the RPO budget.
⚠️ Anti-Pattern: Alerting on every metric. Alert fatigue is the silent killer of HA monitoring; the on-call learns to ignore the page. Build SLI-derived alerts with burn-rate windows that page only on customer-impacting incidents, and keep secondary metrics on dashboards for diagnostic context, not for alerting.
Decision Anchor: Choose SLO-based alerts (burn-rate on a measured availability SLI) for customer-impacting paging, and absolute-threshold alerts for finite resources (quotas, disk capacity, replication lag in seconds). Both shapes belong in the alert policy fleet; the engineer maps the workload contract to the SLO and the platform contracts to the absolute thresholds.
Monitoring Coverage Across HA Pillars
The closing operational discipline is the on-call runbook. For every alert policy, the runbook documents:
- the symptom the alert detects,
- the diagnostic queries (Cloud Logging filters, Cloud Monitoring metric queries, gcloud describe commands),
- the remediation steps,
- and the rollback criterion.
A monitoring stack without runbooks is a paging system, not an operations system.
With runbooks, the on-call resolves incidents in tens of minutes instead of hours, and post-incident reviews feed back into both the alerts and the runbooks.
# Snippet from the orders-platform runbook for replication-lag pages
# 1. Confirm lag is real:
gcloud monitoring metrics list --filter='metric.type="cloudsql.googleapis.com/database/replication/replica_lag"'
# 2. Identify the lagging replica:
gcloud sql instances list --filter="masterInstanceName=ordersdb-prod" --format="table(name,region,state)"
# 3. Check primary write rate (often the cause):
gcloud monitoring time-series list \
--filter='metric.type="cloudsql.googleapis.com/database/postgresql/transaction_count"' \
--interval-end-time=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
--interval-start-time=$(date -u -d '-15 minutes' +"%Y-%m-%dT%H:%M:%SZ")
# 4. If the primary is saturated, scale or kill long transactions; the replica will catch up.
# 5. If the primary is fine but the replica is stuck, restart the replica:
# gcloud sql instances restart ordersdb-replica-east
# 6. If restart does not help, recreate the replica from the latest snapshot.
The monitoring pillar closes the deployment loop.
The engineer designed the topology, provisioned it, rehearsed failover, sized the read fleet, codified the whole stack in Terraform, and now confirms through measured signals that the contract holds.
The four pillars give a defensible answer to the question "are we meeting the SLO," and the runbooks give a defensible answer to "what do we do when we are not."
Without both, HA is a marketing claim, not an operational reality. ---
