SuperAPI AI Directory

database-replication-setup

Data & analytics

View repository

Updated 10-16 09:34

About this skill

Database Replication Expert

Database replication systems expert with deep knowledge of master-slave, master-master replication architectures, and clustered solutions.

Basic principles of replication

Types of replication

  • Asynchronous: High performance, possible data loss during failures
  • Synchronous: Guaranteed data consistency, increased latency
  • Semi-synchronous: Balance between performance and consistency
  • Master-Slave: Read scaling, backup
  • Master-Master: Geographic distribution, high availability

Setting up MySQL replication

Master configuration

[mysqld]
server-id = 1
log-bin = mysql-bin
binlog-format = ROW
sync_binlog = 1

CREATE USER 'repl_user'@'%' IDENTIFIED BY 'secure_password';
GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'%';

Slave configuration

[mysqld]
server-id = 2
relay-log = relay-bin
read_only = 1

CHANGE MASTER TO
    MASTER_HOST='master-server',
    MASTER_USER='repl_user',
    MASTER_PASSWORD='secure_password',
    MASTER_LOG_FILE='mysql-bin.000001',
    MASTER_LOG_POS=154;

START SLAVE;

PostgreSQL streaming replication

Primary server

# postgresql.conf
wal_level = replica
max_wal_senders = 3
max_replication_slots = 3
CREATE USER repl_user REPLICATION LOGIN PASSWORD 'secure_password';

Standby server

pg_basebackup -h primary-server -D /var/lib/postgresql/main -U repl_user -v -P

# postgresql.conf
primary_conninfo = 'host=primary-server port=5432 user=repl_user password=secure_password'

MongoDB Replica Set

rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "mongo1:27017", priority: 2 },
    { _id: 1, host: "mongo2:27017", priority: 1 },
    { _id: 2, host: "mongo3:27017", arbiterOnly: true }
  ]
});

Replication monitoring

MySQL

SHOW SLAVE STATUS\G;
# Проверка: Slave_IO_Running, Slave_SQL_Running, Seconds_Behind_Master

PostgreSQL

SELECT client_addr, state, sent_lsn, replay_lsn,
       pg_wal_lsn_diff(sent_lsn, replay_lsn) AS lag_bytes
FROM pg_stat_replication;

Failover strategies

Automatic switching with HAProxy

listen mysql-cluster
    bind *:3306
    option mysql-check user haproxy_check
    server mysql-1 mysql1:3306 check weight 1
    server mysql-2 mysql2:3306 check weight 1 backup

Best practices

  • Use SSL/TLS for replication traffic
  • Monitor replication lag
  • Test failover procedures regularly
  • Document recovery procedures