
PostgreSQL, Part 4: Streaming Replication, Replica Switching, and Patroni Overview
🌐 Machine-translated from Russian. Show original
In this part:
Why the remark#
- Fast server failure recovery: switching in minutes, not recovering from backup in hours.
- Reading from a replica: reports and analytics do not interfere with the main workload.
- Maintenance with minimal downtime: upgraded replica, switched, upgraded the former main server.
⚠️ A replica does not replace a backup. An incorrect
DELETEorDROP TABLEwill instantly be repeated on the replica. Backups from part 3 remain mandatory.
How it works#
The primary server writes WAL and sends it over the network to standbys that apply changes and are read-only. This is physical stream replication: a replica is an exact copy of a cluster of the same major version.
Stand in the article:
| Role | Name | IP |
|---|---|---|
| primary | db01 | 192.168.1.21 |
| standby | db02 | 192.168.1.22 |
On both servers — PostgreSQL 18 from part 1 with the same settings.
Step 1. Main server#
Role for replication:
sudo -u postgres psql -c "CREATE ROLE replicator WITH REPLICATION LOGIN;"
sudo -u postgres psql -c "\password replicator"
/etc/postgresql/18/main/conf.d/50-replication.conf:
wal_level = replica # значение по умолчанию, указываем явно
max_wal_senders = 10
max_replication_slots = 10
wal_keep_size = 1GB
max_slot_wal_keep_size = 50GB # защита: «забытый» слот не заполнит диск
hot_standby = on
In pg_hba.conf:
hostssl replication replicator 192.168.1.22/32 scram-sha-256
sudo systemctl restart postgresql@18-main
sudo ufw allow from 192.168.1.22 to any port 5432 proto tcp
Step 2. Replica#
On db02, stop the cluster and clear the data directory (it will be replaced with a copy from the main one):
sudo systemctl stop postgresql@18-main
sudo -u postgres bash -c 'rm -rf /var/lib/postgresql/18/main/*'
sudo -u postgres pg_basebackup -h 192.168.1.21 -U replicator \
-D /var/lib/postgresql/18/main -X stream -C -S db02 -R -P
sudo systemctl start postgresql@18-main
-C -S db02— create a replication slot on the primarydb02: the primary will not remove the WAL until the replica receives it;-R— writeprimary_conninfotopostgresql.auto.confand create astandby.signalfile.
It's convenient to put the password in ~postgres/.pgpass (permission 600) so you don't have to enter it manually.
Copy your files from conf.d to replica — the settings in /etc pg_basebackup are not transferred.
Step 3. Verification#
On the main one:
SELECT client_addr, state, sync_state,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS lag
FROM pg_stat_replication;
On the line:
SELECT pg_is_in_recovery(); -- true
SELECT status, sender_host FROM pg_stat_wal_receiver;
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;
Create a test table on the main one — it will appear on the replica in a second.
Synchronous or asynchronous#
| Mode | How it works | Price |
|---|---|---|
| Asynchronous (default) | primary does not wait for a replica | in case of a crash, the last transactions (usually fractions of a second) can be lost |
| Synchronous | commit is confirmed after writing to the replica | zero data loss, but the write delay increases, and if the replica is unavailable, the recording **stops |
Synchronous mode is enabled on the main key: synchronous_standby_names = 'ANY 1 (db02, db03)'. With one replica, it is dangerous — its failure will stop recording. Use it with two or more replicas.
Manual failover#
The main server died. On the replica:
sudo -u postgres psql -c "SELECT pg_promote();"
The replica becomes the primary server and accepts the write. Next:
- Switch applications to the new address. It's convenient to use a DNS name (
db.corp.local) or virtual IP in advance — then one record changes. - Do not allow split-brain: the old primary should not return to service as the primary one. Turn it off or block the port.
- Restore the old server with a replica. If it is lagging or disconnected — use
pg_rewind(works with checksums enabled, which in PostgreSQL 18 are enabled by default for new clusters, or whenwal_log_hints = on), otherwise — repg_basebackup.
# на бывшем основном, PostgreSQL остановлен
sudo -u postgres /usr/lib/postgresql/18/bin/pg_rewind \
--target-pgdata=/var/lib/postgresql/18/main \
--source-server="host=192.168.1.22 user=postgres dbname=postgres" -R -P
Manual switching is a normal option for a small company if there is clear instructions and monitoring. If automatic switching is needed, a tool is needed to decide who is the main one.
Replication slots: benefits and risks#
The slot guarantees that WAL will wait for the replica. But if the replica is disabled and forgotten, the main will store WAL until the disk runs out. Protection — max_slot_wal_keep_size (see above) and check:
SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;
Inactive slot unnecessarily — delete: SELECT pg_drop_replication_slot('db02');. In PostgreSQL 18, the idle_replication_slot_timeoutparameter appeared, which automatically invalidates long-idle slots.
Automatic Switching: Patroni Overview#
Patroni is the most common free tool for the PostgreSQL fault-tolerant cluster (current version as of November 2026 — 4.1.x).
| Component | Role |
|---|---|
| etcd (3 nodes) | consistent state storage: who is the main |
| Patroni on each database server | manages PostgreSQL: starts, monitors, selects and elevates the main replica in case of failure |
| HAProxy or vip-manager / keepalived | routes applications to the current main server |
Key teams:
patronictl -c /etc/patroni/config.yml list # состояние кластера и лаг реплик
patronictl -c /etc/patroni/config.yml switchover # плановое переключение
patronictl -c /etc/patroni/config.yml edit-config # изменение общих параметров PostgreSQL
What you need to know before implementation:
- At least 3 etcd nodes are needed (you can use separate small VMs or on the same servers, but better yet, separately) — otherwise, there is no quorum.
- PostgreSQL under Patroni is not run by the standard
postgresql@18-mainservice — it is managed by Patroni. Cluster parameters change throughpatronictl edit-config, not by editingpostgresql.conf. - The
patroniand etcd packages are available in the PGDG and Ubuntu repositories; check the latest versions and instructions in the Patroni documentation. - Automation fails if the network "blinks." Rehearse failures on the stand: main power shutdown, network break, node failure, etc.
If you're not ready to support etcd, Patroni and HAProxy — it's fairer to stick to manual switching with good instructions than to get a complex cluster that no one understands.
Logical replication — in brief#
In addition to physical replication , there is logical replication (CREATE PUBLICATION / CREATE SUBSCRIPTION): changes to individual tables are transmitted, and the subscriber can be another major version. It is used to migrate to a new version with minimal downtime (part 6) and to export part of the data to analytics.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.