Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

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

  1. Streaming Replication
  2. Logical Replication
  3. Physical Replication

4. Setting Up Replication

Follow these steps to set up streaming replication in PostgreSQL:

  1. Configure the Master Server:
  2. Modify the postgresql.conf file:

    wal_level = replica
    max_wal_senders = 3
    wal_keep_segments = 64
    
  3. Set Up Authentication:
  4. Update the pg_hba.conf file to allow the replica to connect:

    host    replication     all             /32           md5
    
  5. Restart the Master Server:
  6. sudo systemctl restart postgresql
    
  7. Create a Base Backup:
  8. On the Master, run:

    pg_basebackup -h localhost -D /var/lib/postgresql/12/main -U  -P --wal-method=stream
    
  9. Configure the Replica Server:
  10. Modify the postgresql.conf on the replica:

    hot_standby = on
    
  11. Create a recovery.conf file on the Replica:
  12. standby_mode = 'on'
    primary_conninfo = 'host= port=5432 user= password='
    trigger_file = '/tmp/postgresql.trigger.5432'
    
  13. Start the Replica Server:
  14. 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.