Setting Up Replication in PostgreSQL
1. Introduction
Replication in PostgreSQL allows you to maintain one or more copies of a database to ensure high availability and data redundancy. It is essential for disaster recovery and load balancing.
2. Key Concepts
- Master-Slave Architecture: One primary server (master) replicates data to one or more secondary servers (slaves).
- Streaming Replication: Allows real-time data replication using a replication stream.
- Logical Replication: Replicates data based on logical changes instead of physical files.
3. Types of Replication
- Streaming Replication
- Logical Replication
- Physical Replication
4. Setting Up Replication
Follow these steps to set up streaming replication in PostgreSQL:
- Configure the Master Server:
- Set Up Authentication:
- Restart the Master Server:
- Create a Base Backup:
- Configure the Replica Server:
- Create a
recovery.conf
file on the Replica: - Start the Replica Server:
Modify the postgresql.conf
file:
wal_level = replica
max_wal_senders = 3
wal_keep_segments = 64
Update the pg_hba.conf
file to allow the replica to connect:
host replication all /32 md5
sudo systemctl restart postgresql
On the Master, run:
pg_basebackup -h localhost -D /var/lib/postgresql/12/main -U -P --wal-method=stream
Modify the postgresql.conf
on the replica:
hot_standby = on
standby_mode = 'on'
primary_conninfo = 'host= port=5432 user= password='
trigger_file = '/tmp/postgresql.trigger.5432'
sudo systemctl start postgresql
5. Best Practices
- Regularly monitor replication lag.
- Test failover procedures periodically.
- Use appropriate hardware resources for both master and replicas.
- Backup your configuration files regularly.
6. FAQ
What is the difference between streaming and logical replication?
Streaming replication transfers the entire data structure, while logical replication allows for selective replication of certain tables or databases.
How can I monitor replication status?
You can use the pg_stat_replication
view to monitor the status of replication.