Middle+
Tell about master-slave replication — when you refer to master, when to slave?
sobes.tech AI
Answer from AI
In master-slave replication, the primary database (master) handles data writing and updating, while the replicas (slaves) are responsible for reading. This allows load distribution and improves performance.
Requests to the master occur when write operations (INSERT, UPDATE, DELETE) need to be performed so that changes are centrally stored and then replicated to the slaves.
Data reading is usually directed to the slave to offload the master and ensure scalability. However, when the most recent data is needed, requests may be directed to the master, as replication can have delays.
An example in Go using a database with read/write separation:
type DB struct {
master *sql.DB
slaves []*sql.DB
}
func (db *DB) QueryRead(query string, args ...interface{}) (*sql.Rows, error) {
// Select one of the slaves for reading
slave := db.slaves[0] // simplified
return slave.Query(query, args...)
}
func (db *DB) ExecWrite(query string, args ...interface{}) (sql.Result, error) {
// All writes go to the master
return db.master.Exec(query, args...)
}
This approach helps efficiently utilize resources and maintain data integrity.