Cloud SQL Read Replica Connection in Golang

Hello guys!

I want to ask about handling Cloud SQL with Read Replica in Golang App. So i have golang app that running with Cloud SQL for Postgres as a database. I want to make read replica on my Cloud SQL so i can make the Master and Slave schema. When i make the replica database, it will publish connection name on the replica database. Should i connect to the replica database directly, or is it enough to connect only to the master database?

Thank you!

0 1 87
1 REPLY 1

In your case, if you're setting up a read replica in Cloud SQL for PostgreSQL, it is essential to connect directly to the read replica when you want to perform read operations (queries that don’t modify data). The reason for this is that Cloud SQL treats the read replica as a separate database instance specifically designed for read-heavy workloads, which helps offload queries from the master.

Here’s a general approach you can take:

  1. Write Operations (Master): Continue connecting to your primary (master) instance for all write operations, such as inserts, updates, and deletes.

  2. Read Operations (Replica): For read-heavy workloads, connect directly to the read replica instance by using its unique connection name.

You can manage which database to connect to in your Golang app by implementing logic that routes read and write requests to the correct instance. For example, you might use an environment variable or configuration to define the master and replica connection strings and then route queries accordingly.

If you only connect to the master, read queries will still be handled by the primary instance, potentially negating the benefit of having a read replica.