Sub topic 3
Preparing the primary: wal_level, max_wal_senders, pg_hba.conf and the replication role
This chapter prepares the primary server so a standby can connect and stream WAL from it. It assumes you can start and stop a PostgreSQL server, edit postgresql.conf and pg_hba.conf, use psql, and handle basic Linux networking such as hosts, ports and firewalls. The previous chapters covered WAL and the walsender/walreceiver architecture, so this chapter goes straight to configuration.
Four things must be right on the primary before a standby can connect:
- The server writes enough information to WAL (
wal_level). - The server has capacity to serve replication clients (
max_wal_senders). - A role exists that is allowed to replicate.
- The network and
pg_hba.conflet that role in.
The checklist at a glance
Each failure produces a different message. When something goes wrong later, the message tells you which check failed.
Create the replication role
A standby needs a role with the REPLICATION attribute. Do not reuse a superuser for this. A dedicated role limits the damage if its password leaks, because REPLICATION lets the role read all WAL (and so all data) but does not let it run ordinary queries against tables.
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'change-me';LOGIN is required because roles cannot connect by default. Replace the placeholder password before using this anywhere real. Avoid typing real passwords into SQL that ends up in shell history or server logs. In psql you can create the role without a password and then run \password replicator, which hashes the password on the client side.
The role is cluster-wide, so you do not create it per database. You can check it with:
SELECT rolname, rolreplication, rolcanlogin
FROM pg_roles
WHERE rolname = 'replicator';Both rolreplication and rolcanlogin should be t.
Set wal_level
wal_level controls how much information the server writes to WAL. It has three values:
| Value | What it records | Streaming replication possible? |
|---|---|---|
| `minimal` | Only what crash recovery needs | No |
| `replica` | Enough for WAL archiving and physical replication, including read-only queries on a standby | Yes |
| `logical` | Everything in `replica`, plus the information needed for logical decoding | Yes |
The default has been replica since PostgreSQL 10, so on a modern installation you may already have the right value. Check rather than assume:
SHOW wal_level;Setting wal_level = logical also works for physical standbys. It writes somewhat more WAL, so choose it only when you also need logical replication. A standby that runs with hot_standby = on refuses to start if the primary was running with minimal, so a standby can fail on a server where someone tuned wal_level down for bulk-load speed.
Set max_wal_senders and related limits
Each standby connection is served by one walsender process. max_wal_senders caps how many can exist at once. The default is 10 since PostgreSQL 12 (it was 0 in version 9.6 and earlier, and 10 from version 10). Since version 12, walsender slots are counted separately from max_connections, so you do not need to raise max_connections to make room for them.
Size it to cover more than your standby count:
- One walsender per standby.
- One more per running
pg_basebackup. With-X stream(used in this tutorial),pg_basebackupopens two connections, so it can use two walsenders. - A little headroom, so a standby that reconnects can get a slot while the primary has not yet noticed that its old connection died.
That last point is a common cause of failed reconnects. A standby that loses its network connection may reconnect before the primary has timed out the old one. For a short time the old and new sessions both hold slots.
A related parameter is max_replication_slots, which limits how many replication slots can exist. It defaults to 10. You will use slots in a later chapter, but the default is fine for now.
Finally, give lagging standbys some extra WAL to catch up from. wal_keep_size tells the primary to keep at least that much WAL in pg_wal even when it is no longer needed locally. It exists in PostgreSQL 13 and later (earlier versions called it wal_keep_segments, counted in 16 MB files).
Edit postgresql.conf
# postgresql.conf on the primary
listen_addresses = '*'
wal_level = replica
max_wal_senders = 10
wal_keep_size = '1GB'listen_addresses = '*' makes the server listen on every network interface. The default is localhost, which only accepts connections from the same machine, and it is the most common reason a first standby cannot connect. If your host has several interfaces, you can list only the address the standby will use, for example listen_addresses = '10.0.0.5'. Doing so keeps the server off networks that do not need it.
wal_keep_size is a floor, not a guarantee. A standby that falls behind by more than 1 GB of WAL, and that is not using a slot or an archive, can lose the WAL it needs and must be rebuilt. Replication slots, covered later, solve this, but they bring disk-growth risks of their own.
Edit pg_hba.conf
pg_hba.conf decides which clients can connect, from where, and how they authenticate. Replication connections need their own line, and the database column uses the keyword replication:
# pg_hba.conf on the primary (replication connections use the pseudo-database "replication")
host replication replicator 10.0.0.0/24 scram-sha-256Read the fields from left to right: connection type, database, user, client address, and authentication method.
replicationis a keyword, not a database name. It matches physical replication connections, which are not attached to any database. A line withallin the database column does not match them. If you want to allow normal queries as well, you need a separate line.10.0.0.0/24should be the smallest network that covers your standbys. Use a single address such as10.0.0.12/32where you can.scram-sha-256is the recommended password method. The role's stored password must also be a SCRAM hash. Since PostgreSQL 14password_encryptiondefaults toscram-sha-256. On older versions, checkSHOW password_encryption;before creating the role, or the stored MD5 hash will not work with a SCRAM line.pg_hba.confis read from the top and the first matching line wins. If an earlierrejectortrustline covers the same network, your new line is never reached. Place the replication line above any broader rules that would match first.
If you need encryption in transit, use hostssl instead of host and set up ssl = on. WAL contains all your data, so sending it across an untrusted network without TLS exposes everything.
Apply the changes
Settings differ in how they take effect:
| Change | How to apply |
|---|---|
| `listen_addresses` | Restart |
| `wal_level` | Restart |
| `max_wal_senders` | Restart |
| `wal_keep_size` | Reload |
| `pg_hba.conf` | Reload |
Because three of these need a restart, make them all at once and restart once. Then confirm the values took effect:
sudo systemctl restart postgresql
psql -U postgres -c "SHOW wal_level;" -c "SHOW max_wal_senders;" -c "SHOW listen_addresses;"The unit name differs by distribution (for example postgresql@16-main on Debian and Ubuntu). If you only change pg_hba.conf later, SELECT pg_reload_conf(); is enough. Afterwards, check pg_hba_file_rules for syntax errors, since a bad line is silently skipped on reload:
SELECT line_number, type, database, user_name, address, auth_method, error
FROM pg_hba_file_rules
WHERE database::text LIKE '%replication%' OR error IS NOT NULL;Test before building the standby
You can check the whole path from the standby host, without taking a backup. A connection that sets replication=true speaks the replication protocol, and IDENTIFY_SYSTEM is a harmless command that returns the cluster's system identifier, current timeline and WAL position:
psql "host=primary.example.com user=replicator replication=true" -c "IDENTIFY_SYSTEM;"If this returns a row, the network, pg_hba.conf, the password and the role attribute are all correct. If it fails, the error message points to the failing step in the diagram above. This is much faster than diagnosing the same problem from inside a failed pg_basebackup run.
Common errors
FATAL: no pg_hba.conf entry for replication connection from host ...: thereplicationkeyword line is missing, the address does not match, or ahostsslline applies to a connection that does not use TLS.FATAL: must be superuser or replication role to start walsender: the role lacks theREPLICATIONattribute. Fix it withALTER ROLE replicator REPLICATION;.FATAL: number of requested standby connections exceeds max_wal_senders: all slots are in use. Raise the value and restart, or look for stale connections.connection refused:listen_addressesis stilllocalhost, the server was not restarted, or a firewall blocks port 5432.password authentication failed: the password is wrong, or the stored hash type does not match thepg_hba.confmethod.
Exercise
You set wal_level = replica, max_wal_senders = 10 and listen_addresses = '*' in postgresql.conf, added host replication replicator 10.0.0.0/24 scram-sha-256 to pg_hba.conf, and ran SELECT pg_reload_conf();. A standby on 10.0.0.12 still gets "connection refused". What is the most likely cause, and what is the fix?
Show answer
listen_addresses only takes effect after a full server restart, and a reload does not apply it. The server is probably still listening on localhost only, which causes "connection refused". Restart PostgreSQL, then confirm with SHOW listen_addresses; and re-run the IDENTIFY_SYSTEM test from the standby host. If the error persists after the restart, check that a firewall is not blocking port 5432. A missing pg_hba.conf entry would produce a "no pg_hba.conf entry" error instead, not "connection refused".
Exercise
Why does a line host all replicator 10.0.0.0/24 scram-sha-256 not allow the standby to stream WAL?
Show answer
The special database value all does not match physical replication connections. Those connections require a line with the keyword replication in the database column.