The connector can use DNS to identify instances, enabling automatic failover. You can use Cloud SQL Advanced Disaster Recovery write endpoints or your own managed DNS records.
Configure DNS Records
Add a private TXT record to your DNS server.
- Name: The domain name used by your application (e.g.,
prod-db.mycompany.example.com). - Value: The Cloud SQL instance connection name (e.g.,
my-project:region:my-instance).
Warning: Do not use public DNS servers, as this exposes your instance name to the internet.
Automatic Failover Behavior
When the connector is configured with cloudsqlconn.WithDNSResolver(), it periodically polls for changes to the DNS record (default every 30 seconds). If the record changes, the connector closes existing connections to the old instance, forcing the connection pool to reconnect to the new instance specified in the DNS record.
To adjust the polling frequency, use WithFailoverPeriod(d time.Duration). Setting this to 0 disables polling and only checks for changes during new connection attempts.
package main
import (
"database/sql"
"cloud.google.com/go/cloudsqlconn"
"cloud.google.com/go/cloudsqlconn/mysql/mysql"
)
func connect() {
cleanup, err := mysql.RegisterDriver("cloudsql-mysql",
cloudsqlconn.WithDNSResolver())
if err != nil {
// ... handle error
}
defer cleanup()
db, err := sql.Open(
"cloudsql-mysql",
"myuser:mypass@cloudsql-mysql(prod-db.mycompany.example.com)/mydb",
)
// ... etc
}