PostgreSQL Replication is a powerful feature that allows you to create copies of your database (called replicas) for high availability, data backup, reporting, and scalability purposes. Let's dive into this fascinating topic and understand it from the ground up!
Replication is the process of copying data from a primary database (also known as the master) to one or more secondary databases (or replicas). This helps ensure data consistency and provides a backup in case of failures.
Let's set up a basic replication scenario using PostgreSQL.
Follow the official PostgreSQL installation guide to install PostgreSQL on your system.
On the primary server:
CREATE DATABASE mydatabase;
CREATE USER replicationuser WITH ENCRYPTED PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO replicationuser;Edit the postgresql.conf file on the primary server and add the following lines:
wal_level = logical
max_wal_senders = 5
max_replication_slots = 16
Restart the PostgreSQL service after making the changes.
On the replica server:
Install PostgreSQL if not already done.
Edit the postgresql.conf file and add:
wal_level = logical
wal_keeper_enabled = on
Edit the pg_hba.conf file and add:
host replication replicationuser md5 127.0.0.1/32
host replication all all 127.0.0.1/32 trust
Restart the PostgreSQL service.
On the primary server:
\copy (SELECT pg_create_logical_replication_conf(
'mydatabase', 'replicationuser', 'myreplication', '127.0.0.1', '5432', 'mydatabase')
) TO '/tmp/replication.conf' WITH (FORMAT csv, HEADER true);
\o replication.log
LOG_LINE_PREFIX= 'Primary: '
psql -U replicationuser -d mydatabase -f /tmp/replication.conf
\o -
LOG_LINE_PREFIX= 'Replica: 'On the replica server:
\i /path/to/replication.confOn the primary server:
SELECT * FROM pg_stat_replication;On the replica server:
SELECT * FROM pg_stat_replication;What is the primary purpose of replication in PostgreSQL?
How can you set up replication between two PostgreSQL servers?