GCP Cloud SQL: High Availability, Read Replicas, and Migration
Architect production-ready GCP Cloud SQL: HA configuration, Enterprise Plus advanced DR with switchover, read replicas, cross-region disaster recovery, zero-downtime migration, and monitoring..
20+ years shipping production infrastructure and CI/CD at scale. Notes here come from systems that actually shipped.
- ✓Google Cloud Platform account with billing enabled, gcloud CLI installed and configured (version 450+), basic knowledge of SQL (PostgreSQL or MySQL), familiarity with Terraform (optional but recommended), and a production database workload to apply these patterns.
GCP Cloud SQL: High Availability, Read Replicas, and Migration is like having a specialized tool that handles cloud sql so you don't have to build and manage it yourself โ it just works out of the box with Google Cloud's infrastructure.
Youโve just lost a primary database zone. Your app is down, customers are screaming, and your on-call phone is melting. If youโre running Cloud SQL without HA, thatโs your fault. High Availability isnโt a luxuryโitโs the baseline for any production database. But HA alone wonโt save you from read storms or migration nightmares. Thatโs where read replicas and careful migration planning come in. In this article, Iโll show you how to architect Cloud SQL for resilience, scale reads without breaking the bank, and migrate databases with zero downtime. No fluff, just battle-tested patterns from real outages.
High Availability Architecture: How Cloud SQL HA Works
Cloud SQL HA uses a primary instance in one zone and a standby instance in another zone within the same region. Both share the same persistent disk (regional PD) that replicates synchronously across zones. When the primary fails, the standby takes over with no data lossโthe same disk, same IP, same connections. Failover is automatic and typically completes within 60 seconds. However, this is not a multi-region setup. If the entire region goes down, youโre still in trouble. For multi-region DR, you need cross-region replicas. Also note: HA doubles your instance cost (you pay for both primary and standby). But for production, itโs non-negotiable. The standby is idleโyou canโt use it for reads. Thatโs what read replicas are for.
Creating and Managing Read Replicas
Read replicas are copies of your primary instance that serve read traffic. They use asynchronous replication, so thereโs a small lag (typically <1 second). You can create multiple replicas, each in a different zone or even region. Use them to offload reporting, analytics, or read-heavy workloads. Crucially, you can promote a read replica to a standalone instanceโthis is how you perform zero-downtime migrations or recover from regional failures. When creating a replica, choose the same machine type as the primary for consistent performance, or a larger one if the replica will serve heavy read traffic. Monitor replication lag with the cloudsql.googleapis.com/database/replication/lag metric. If lag exceeds your tolerance, scale up the replica or reduce write load on the primary.
Connection Routing: Directing Traffic to Replicas
Cloud SQL does not automatically route read queries to replicas. You must configure your application to use separate connection strings for reads and writes. A common pattern is to use a proxy like ProxySQL or PgBouncer, or implement read/write splitting in your application code. For example, in a Python app using SQLAlchemy, you can create two engine instances: one for the primary (writes) and one for the replica (reads). Use a decorator or middleware to route SELECT queries to the replica engine. Be careful with transactionsโif a read occurs within a write transaction, it must go to the primary to guarantee consistency. Also, ensure your replica can handle the read load; otherwise, it may become a bottleneck.
Zero-Downtime Migration: Promoting a Read Replica
Promoting a read replica turns it into an independent primary instance. This is the cornerstone of zero-downtime migrationsโwhether you're upgrading the database version, moving to a different machine type, or changing regions. The process: create a read replica of your current primary, let it catch up, then promote it. After promotion, the old primary becomes standalone (it still exists). You then redirect your application to the new primary. The key is to ensure the replica is fully caught up before promotion. Use gcloud sql instances describe to check replicaLagโit should be 0 seconds. Also, plan for a brief connection interruption during DNS or connection string update. Use a load balancer or proxy to minimize downtime.
Cross-Region Replicas for Disaster Recovery
A cross-region read replica replicates your primary instance to a different GCP region. This is your best defense against regional outages. The replica uses asynchronous replication, so there will be some data loss (RPO) in a disasterโtypically seconds to minutes. To minimize RPO, use a higher replication tier and monitor lag. In a disaster, promote the cross-region replica to become the new primary. Then update your applicationโs connection string to point to the new region. This process can be automated with Cloud Functions or a managed DR orchestration tool. Remember: cross-region replication incurs network egress costsโmonitor your bill.
Enterprise Plus: Advanced DR with Switchover and Write Endpoints
Cloud SQL Enterprise Plus edition provides advanced disaster recovery features beyond standard HA. The key capabilities are replica failover and switchover with zero data loss and automatic DNS write endpoints. A write endpoint is a global DNS name that always resolves to the current primary instance's IP. When you perform a switchover (planned role reversal between primary and DR replica) or replica failover (unplanned disaster), the write endpoint automatically updatesโno application connection string changes needed. Switchover is planned: the primary stops writes, waits for the DR replica to catch up, then promotes it. This gives zero data loss and sub-second downtime. Replica failover is for disasters: promotes the DR replica immediately with potential seconds of data loss. After failover, the old primary automatically becomes a read replica of the new primary, enabling fallback. Enterprise Plus also offers data cache for faster reads, near-zero downtime maintenance, and a 99.99% SLA (including maintenance). Use Enterprise Plus for any business-critical database where regional DR and zero-downtime maintenance are required. The cost premium over Enterprise is typically 30-50% but eliminates the operational burden of manual DR procedures.
Maintenance Controls: Near-Zero Downtime Operations
Cloud SQL Enterprise Plus provides advanced maintenance controls that minimize downtime. Key features: near-zero downtime maintenance (sub-second failover during patching), configurable maintenance windows, maintenance notifications (email 1+ week in advance), reschedule maintenance capability, and deny maintenance periods (postpone up to 90 days for sensitive periods like Black Friday). Best practices: configure a maintenance window during off-peak hours, apply maintenance to read replicas before the primary to validate, and enable maintenance notifications. For multi-replica setups, use a rolling maintenance strategy: patch one replica, then the next, then the primary last. Always test maintenance in a staging environment at least a week before production. In production, we use the deny maintenance period to block maintenance during month-end processing and promotional events.
Migration Strategies: From On-Prem or Other Clouds
Migrating to Cloud SQL from an external database requires careful planning. The recommended approach is to use Database Migration Service (DMS) for continuous replication with minimal downtime. DMS supports MySQL, PostgreSQL, and SQL Server. It creates a Cloud SQL instance and sets up replication from your source. Once replication is caught up, you promote the Cloud SQL instance and cut over. For smaller databases (< 100 GB), you can also use pg_dump/pg_restore or mysqldump, but this requires downtime. Always test the migration in a staging environment first. Pay attention to character sets, time zones, and stored proceduresโthey may differ between environments.
Monitoring and Alerting for HA and Replicas
Without proper monitoring, your HA setup is a false sense of security. Key metrics to track: replication lag (for replicas), failover events, disk usage, and CPU/memory utilization. Set up Cloud Monitoring dashboards and alerts. For replication lag, alert if it exceeds 10 seconds (or your business tolerance). For HA, monitor the cloudsql.googleapis.com/database/failover metricโit should be 0. If it increments, investigate immediately. Also monitor the standby instance's healthโthough it's idle, its disk must be healthy. Use uptime checks to verify your database endpoints are reachable. Finally, test failover manually at least once per quarter to ensure it works.
Cost Optimization: Balancing HA, Replicas, and Performance
Cloud SQL costs can spiral if you over-provision. HA doubles your compute cost (you pay for standby). Each read replica adds its own compute and storage cost. To optimize: use smaller machine types for replicas if they handle light read traffic. Consider using committed use discounts (1 or 3 years) for predictable workloads. For development/staging, use zonal (non-HA) instances. Also, right-size your storageโCloud SQL bills for provisioned storage, not used. Monitor storage utilization and downsize if needed. Finally, use private IP to avoid egress costs between your application and database in the same VPC.
Common Pitfalls and How to Avoid Them
Pitfall 1: Not testing failover. Many teams assume HA works until it doesn't. Test quarterly. Pitfall 2: Ignoring replication lag. If your app reads from replicas, stale data can cause bugs. Set alerts. Pitfall 3: Using HA for non-critical databases. HA doubles costโuse it only where downtime is unacceptable. Pitfall 4: Overloading a single replica. Distribute read traffic across multiple replicas or use a connection pooler. Pitfall 5: Not planning for regional disasters. HA is zonal; for regional DR, use cross-region replicas. Pitfall 6: Forgetting to update connection strings after promotion. Automate DNS updates or use a proxy that can be reconfigured without code changes.
Automating HA and Replica Management with Infrastructure as Code
Manual database management is error-prone. Use Terraform or Deployment Manager to define your Cloud SQL instances, replicas, and HA settings as code. This ensures consistency across environments and makes disaster recovery reproducible. For example, a Terraform module can create a primary with HA, a cross-region replica, and monitoring alerts. Store state in a remote backend (e.g., GCS) with locking. Use CI/CD to apply changes after review. Also, consider using Config Connector for Kubernetes-native management if you run on GKE.
terraform apply. That's the power of IaC.| File | Command / Code | Purpose |
|---|---|---|
| create-ha-instance.sh | gcloud sql instances create my-db \ | High Availability Architecture |
| create-read-replica.sh | gcloud sql instances create my-db-replica \ | Creating and Managing Read Replicas |
| read_write_routing.py | from sqlalchemy import create_engine | Connection Routing |
| promote-replica.sh | LAG=$(gcloud sql instances describe my-db-replica \ | Zero-Downtime Migration |
| create-cross-region-replica.sh | gcloud sql instances create my-db-dr-replica \ | Cross-Region Replicas for Disaster Recovery |
| create-enterprise-plus.sh | PRIMARY='my-db-enterprise-plus' | Enterprise Plus |
| maintenance-config.sh | gcloud sql instances patch my-db \ | Maintenance Controls |
| migration-with-dms.sh | gcloud database-migration migration-jobs create my-migration \ | Migration Strategies |
| create-alert-policy.sh | gcloud alpha monitoring policies create \ | Monitoring and Alerting for HA and Replicas |
| failover-test.sh | PRIMARY=$(gcloud sql instances describe my-db --format="value(gceZone)") | Common Pitfalls and How to Avoid Them |
| main.tf | resource "google_sql_database_instance" "primary" { | Automating HA and Replica Management with Infrastructure as |
Key takeaways
Common mistakes to avoid
3 patternsIgnoring gcp cloud sql best practices
Over-provisioning without rightsizing analysis
Skipping IAM least-privilege principles
Interview Questions on This Topic
What is GCP Cloud SQL: High Availability, Read Replicas, and Migration and when would you use it in production?
Frequently Asked Questions
20+ years shipping production infrastructure and CI/CD at scale. Notes here come from systems that actually shipped.
That's Google Cloud. Mark it forged?
5 min read · try the examples if you haven't