Setting up PostgreSQL streaming replication

A practical guide to building hot standby replicas with streaming replication, covering roles, pg_hba.conf, pg_basebackup, replication slots, standby.signal and health checks.

On this page

Setting up PostgreSQL streaming replication for hot standby servers

Streaming replication lets a standby server receive write-ahead log (WAL) from the primary as it is generated, so the standby holds a current copy of the data and can serve read-only queries. Teams need it when a single PostgreSQL primary cannot be lost without an outage: the standby keeps a second copy of the data ready, and it can take read traffic off the primary. PostgreSQL supports both hot standby servers that answer queries and two replication modes, asynchronous and synchronous, where a commit waits for standbys. Choosing between them is a decision about data loss tolerance and write latency that should be made before the cluster is built.

PostgreSQL does not detect a failed primary or promote a standby on its own. Its failover documentation states that external tools are needed to detect the failure and notify the standby, so this page covers the replica layer only: creating the replication role, the pg_hba.conf entries that let the standby connect, the base backup, replication slots, standby.signal, and the health checks that show the standby is keeping up. Automation belongs to the failover tooling pages in this group, and the high availability documentation is the reference for the feature set this page relies on.

Before you start, confirm the exact PostgreSQL version you will run against the supported list in the versioning policy, and make sure the primary and every standby run the same major version. Plan who will own the replication role credentials, which network paths the standby needs to the primary, and how much WAL the primary must retain while a standby is offline. Those answers determine the settings you will check after the standby is online, and they are harder to change once applications depend on the cluster.

Which replication options fit your cluster design

Asynchronous replication is the default fit when write latency matters more than zero data loss on failover. The primary reports a commit as successful once its own WAL is flushed, and standbys catch up afterward, so a standby can lag behind and a failover can lose the most recent commits. PostgreSQL supports this mode alongside synchronous replication as described in the high availability documentation.

  • Latency: Commits do not wait for a network round trip to any standby, so write latency tracks the primary alone.
  • Data loss window: Transactions not yet received by the standby at the moment of failure can be lost, so define an acceptable loss window in writing.
  • Lag monitoring: Lag becomes the main health signal, so alert on replay lag and on whether the standby is still streaming.
  • Failover tooling: PostgreSQL does not detect a dead primary on its own, so an external tool must promote a standby.
  • Cross-site use: Asynchronous links suit WAN distances where waiting for a remote acknowledgment would stall every commit.

Confirm the maximum data loss your business accepts, the network latency between nodes and whether your failover tool or your runbook will decide which standby to promote.

Key configuration settings for the primary and standby

This table compares the settings that enable streaming replication on the primary and the standby, and says when each one applies. Read it as a checklist: the primary needs WAL level, sender and slot limits, and the standby needs its connection string, slot name and read-only setting. Confirm the default value of each setting for your supported PostgreSQL version before you change it.

SettingWhere it appliesPurposeWhen it fits
wal_levelPrimarySets how much information is written to WAL. Streaming replication needs at least the replica level.Set on every primary that will have standbys. Logical level is only needed for logical replication or CDC consumers.
max_wal_sendersPrimarySets how many concurrent WAL sender processes the primary can run, including base backups.Size it for each standby, plus spare capacity for pg_basebackup and any logical subscribers.
max_replication_slotsPrimary and standbySets how many replication slots can exist. Slots preserve WAL that a standby still needs.Set at least as high as the number of standbys using slots, plus any logical consumers that use slots.
hot_standbyStandbyAllows read-only queries to run on the standby while it replays WAL.Enable when the standby will serve reads or when it may be promoted with clients reconnecting quickly.
primary_conninfoStandbyGives the connection string the standby uses to reach the primary, including the replication role.Required on every standby. Confirm the role, host, TLS mode and password source match your pg_hba.conf entries.
primary_slot_nameStandbyNames the replication slot on the primary that this standby uses.Use when the standby should hold WAL on the primary through a slot. Each standby needs its own slot name.
synchronous_standby_namesPrimaryLists the standbys that a commit waits for when synchronous replication is active.Leave empty for asynchronous replication. Set only after you have chosen a quorum or priority design and tested standby failure.

Step-by-step build of a streaming replica

This sequence turns a running primary into a hot standby that receives WAL over a dedicated replication connection and can serve read-only queries. Each step ends with a check, so a failed step is caught before the next one depends on it.

  1. Create a replication role with a SCRAM password

    On the primary, a database administrator creates a dedicated login role with the REPLICATION attribute and no other privileges, then sets its password. Confirm that password_encryption is set to scram-sha-256 before setting the password, because MD5 password authentication is deprecated in PostgreSQL 18. The check is a query against pg_roles showing rolreplication as true for the role, and a stored password hash that begins with the SCRAM marker rather than an MD5 hash.

  2. Restrict access with a pg_hba.conf entry

    Add a line to the primary's pg_hba.conf that matches the replication pseudo-database, the replication role, the standby's address and the SCRAM method, and nothing wider. Keep the address to a single host or a narrow subnet, and confirm the file's rule order so that no earlier broad rule matches first. The check is that pg_hba_file_rules shows the new line with no error, and that a connection attempt from any other host is rejected.

  3. Set primary parameters and reload the configuration

    Set the parameters the standby needs on the primary, including wal_level set to replica or higher, a max_wal_senders value that leaves room for every standby, and a max_replication_slots value that covers the slot you plan to create. Some of these settings require a restart, so check which ones are context-dependent in the documentation for your version before you change anything. The check is that SHOW wal_level, SHOW max_wal_senders and SHOW max_replication_slots return the intended values, and that a restart, where needed, completed cleanly.

  4. Create a physical replication slot

    Create a physical replication slot on the primary with pg_create_physical_replication_slot, using a name that identifies the standby. The slot makes the primary keep the WAL the standby still needs, so a standby that is briefly offline can catch up without a fresh base backup. The check is a query against pg_replication_slots showing the slot as present, of type physical, and not active yet. Review the retention implications before you rely on it, because an abandoned slot will keep WAL on the primary's disk.

  5. Seed the standby with pg_basebackup

    On the standby host, with an empty data directory and the same major version as the primary, run pg_basebackup with the -R flag so it writes connection settings into postgresql.auto.conf, and with the -S option naming the slot created earlier. Use -X stream so WAL needed during the copy arrives with the backup, and supply the replication role's password through a secure method rather than on the command line. The check is that the command exits without error and that the data directory contains the base files and a pg_wal directory.

  6. Confirm standby.signal and the connection settings

    Inspect the standby's data directory to confirm that a file named standby.signal exists, which tells PostgreSQL to start as a standby rather than a primary. Then check that postgresql.auto.conf holds the primary_conninfo entry and the primary_slot_name entry that -R wrote. Remove any stray recovery.signal file, since it would change startup behavior. The check is that both files are present and the primary_slot_name matches the slot you created, with the password handled by a secure mechanism rather than stored in plain text in a file that other users can read.

  7. Start the standby and confirm it accepts read queries

    Start the standby service, then review its server log for a line showing it entered hot standby and connected to the primary. Run a read-only query on the standby and attempt a write, which should fail with a read-only transaction error. This confirms hot standby is active and the standby is protected from accidental writes. The check is that SELECT pg_is_in_recovery() returns true on the standby and that the query against replicated data returns current rows.

  8. Verify replication with pg_stat_replication and pg_stat_wal_receiver

    On the primary, query pg_stat_replication and confirm a row exists for the standby with a state of streaming and a sync_state appropriate to your design, which is async unless you configured synchronous replication. On the standby, query pg_stat_wal_receiver and confirm the status is streaming and that the received and written LSNs advance when you write a test row on the primary. Record the replay lag figures as your baseline. The check is that both views agree the connection is streaming and that a test write appears on the standby within the lag you observe.

Checks that prove replication is healthy

A standby that connects is not the same as a standby that keeps up. The checks below run on the primary and the standby and cover connection state, lag, WAL retention, read behavior and end-to-end data flow. Together they tell you whether a replica would be usable after a failover, which is the only reason it exists.

Replication state in pg_stat_replication

Run SELECT application_name, state, sync_state, sent_lsn, replay_lsn FROM pg_stat_replication; on the primary. Each standby should appear with state streaming. A missing row means the standby has disconnected, and a catchup or backup state that lasts means it is still behind. Alert when an expected standby is absent for more than a short window, and when sync_state differs from what your design requires, since a standby that quietly became asynchronous changes your data-loss exposure.

Failover docs

Replay and write lag

Lag shows how far a standby trails the primary. Compare write_lag, flush_lag and replay_lag in pg_stat_replication, and compare pg_current_wal_lsn() on the primary with pg_last_wal_replay_lsn() on the standby. Replay lag matters most for read queries and for the data you would lose in an asynchronous failover. Alert on lag above a threshold you set from your recovery point target, and on lag that keeps growing even when write volume is steady, which usually points to a slow disk or a long-running conflicting query on the standby.

Standby receiver status

On the standby, query pg_stat_wal_receiver to confirm the WAL receiver process is running, that status is streaming, and that sender_host and slot_name match what you configured. Check the standby log for repeated connection errors, authentication failures against your pg_hba.conf entry, or timeline messages. A receiver that restarts in a loop often shows up as intermittent lag rather than a clean disconnect, so alert on repeated reconnects as well as on a stopped receiver.

Replication slot retention and WAL growth

A replication slot stops the primary from removing WAL that a standby still needs. If a standby stays down, WAL accumulates in pg_wal until the disk fills, which can stop the primary entirely. Query pg_replication_slots for active and restart_lsn, and track the WAL directory size and free disk space on the primary. Alert when a slot is inactive, when retained WAL grows faster than expected, and when free space drops below your agreed floor. Confirm the retention limit you choose, since it decides whether a long outage costs a standby or the primary.

High availability docs

Read queries on the hot standby

A hot standby serves read-only queries, so test that path directly. Run a simple SELECT pg_is_in_recovery(); on the standby, which should return true, and run a representative read query through the same route your applications use. Watch for query cancellations caused by recovery conflicts in the standby log, since long reads can be cancelled when the standby must apply changes that remove rows they still need. Alert on cancellation counts and on read latency, because a standby that accepts connections but returns stale or cancelled results is not ready to serve reads.

Test write visible on the replica

Metrics show the standby is moving WAL, but only a data test shows it applies the changes. Create a small, dedicated table on the primary, insert a timestamped row, and query for that row on the standby after a short wait. Record how long the row takes to appear, then drop the table. Run this on a schedule, and alert when the row is missing or arrives later than your target. This check catches problems that lag counters can miss, such as replay blocked by a configuration difference or a standby that reads from the wrong cluster.

Questions teams ask before setting up replication

How much effort does a PostgreSQL streaming replica take to set up?

Effort depends mainly on how many standbys you need, how large the primary's data set is, and how much of the surrounding work is new to your team. A single standby is a bounded task: create a replication role, allow its connection in pg_hba.conf, take a base backup with pg_basebackup, start the standby with a standby.signal file, and check that it streams. The time that varies most is not the commands but the work around them: network paths between servers, TLS for replication connections, monitoring of lag and replication slots, and a tested procedure for promoting the standby. Ask any partner to break its estimate into those parts so you can see which ones your team already covers.

Can our internal team set up streaming replication without a partner?

Yes, if the team already runs PostgreSQL in production and is comfortable reading the server logs and configuration files. The core steps are documented in the PostgreSQL high availability documentation, and the mechanics are not hard. What internal teams most often under-plan is the verification: confirming that the standby replays WAL under load, that lag stays within an agreed bound, that slots do not grow without limit, and that someone has practiced promotion. A partner adds value mainly when you need that verification written down, when the replicas must meet an audit expectation, or when the team has no spare capacity to own the result after go-live.

What do we need to provide for a streaming replica project?

Plan to provide the following before work starts:

How does streaming replication differ from a full failover tool?

Streaming replication copies WAL from a primary to a standby so the standby holds the same data and can be promoted by hand or by script. The PostgreSQL failover documentation states that the database does not detect a primary failure or notify the standby on its own, so a replica alone does not give you automatic failover. Tools such as Patroni, repmgr and pg_auto_failover add the detection, leader election and fencing that decide when promotion happens. Choose the replication setup first, because every failover tool builds on it. Then decide whether automatic promotion is required, which depends on your recovery time target and on how often an operator is available to act.

Which PostgreSQL version should we run for replicas?

Run a version that is still in its support window for the whole period you expect to operate the cluster. Per the PostgreSQL versioning policy, supported versions are 18 (final release November 14, 2030), 17 (to November 8, 2029), 16 (to November 9, 2028), 15 (to November 11, 2027) and 14 (to November 12, 2026). Versions 13 and earlier are unsupported. Primary and standbys should run the same major version for streaming replication, and minor releases should be applied to both on a regular schedule, since minor releases arrive at least once every three months. If you are still on an unsupported version, plan the upgrade before or alongside the replica build.

What should we ask for in a quote for replication work?

Ask for a written scope that lists each server, the PostgreSQL version and the number of standbys, along with the network, TLS and authentication decisions. Request the deliverables by name: configuration files, a runbook for promotion, lag and slot monitoring thresholds, and a record of the test results. Ask which items are one-time work and which recur, such as minor version patching, monitoring upkeep or a retainer for changes. Confirm what the client must supply, what the partner will not do, and how acceptance is tested. DeployOpen plans and implements these engagements against a written scope, and quotes follow from that scope.

Does a standby replace our backups?

No. A streaming standby reflects the primary's data within the current replication lag, so an accidental DROP TABLE or a bad update is copied to the standby as well. The PostgreSQL continuous archiving documentation describes point-in-time recovery, which combines a base backup with archived WAL files, as the way to return to an earlier state. Plan both: replicas for availability, and tested backups with archived WAL for recovery. Ask your partner or team to confirm where backups are stored, how long they are kept, and when the last restore test was run.

Limits to confirm in your environment

Streaming replication is simple to switch on and easy to misjudge in production. The cards below cover the places where a standby, a WAL archive or a network link can fail in ways the first setup does not show, and what to confirm in your own environment before you rely on the cluster.

Replication slot WAL growth

A replication slot holds WAL on the primary until the standby that owns it has consumed that WAL. If a standby stops, the slot keeps retaining WAL and the primary's disk can fill, which takes down the primary itself. Confirm how much disk headroom the primary has, how quickly WAL is generated during peak writes, and whether a limit such as max_slot_wal_keep_size is in place and monitored. Decide who is alerted when a slot falls behind and who is allowed to drop it.

HA docs

Hot standby query conflicts

A hot standby serves read-only queries, but WAL replay can conflict with those queries, for example when vacuum removes rows a standby query still needs. Depending on configuration, either replay waits or the query is cancelled. Confirm which kinds of read traffic will reach the standby, how long replay may wait, and how your application handles a cancelled query. Replication setup alone does not settle this trade-off.

HA docs

Network bandwidth between sites

Streaming replication sends all changed data from the primary to each standby, so write volume sets a continuous bandwidth requirement on the link. A standby on a remote site may fall behind when the link is saturated during bulk loads or backups. Measure your primary's WAL generation rate over a representative period, confirm the link capacity and latency with your network team, and confirm that the link has headroom for base backups and rebuilds.

External failover tooling

PostgreSQL does not detect a failed primary or promote a standby on its own. A standby created by streaming replication is only a copy until someone or something promotes it. Decide whether promotion is manual, scripted or handled by a tool such as Patroni, repmgr or pg_auto_failover, and who owns that decision. Confirm how clients find the new primary, since replication does not move connections for you.

Failover docs

Version-specific behavior to confirm

Replication parameters, slot behavior and recovery settings can differ between major versions, and standby configuration files have changed over time. Your supported PostgreSQL version sets which release notes apply to your build. Confirm the exact version you will run, its end-of-life date, and the release notes for every version between your baseline and the target. Test the same configuration on the version you will run in production.

Oldest supported major
14
Versioning policy

WAL storage sizing

WAL volume depends on write rate, checkpoint settings, the number of replication slots and how long archived WAL is kept for point-in-time recovery. Each of these multiplies the storage needed on the primary and the archive. Estimate WAL generation from measured write activity rather than from table sizes, add headroom for a standby outage, and confirm the retention period your recovery objectives require. Keep the WAL archive on storage separate from the data directory.

Archiving docs

How the primary, standby and monitoring checks connect

The diagram starts on the primary, where the replication role is authorized by a pg_hba.conf entry before a standby can connect. The standby's WAL receiver streams changes over that replication connection, and a replication slot on the primary holds the WAL the standby still needs. A monitoring check reads pg_stat_replication on the primary to confirm the standby is attached and how far behind it is. Check the trust boundary first, then the slot, then the lag reported by the monitoring check.

Replication role, slot, WAL stream and the health check that reads them.

When streaming replication alone is enough and when it is not

Streaming replication gives you a warm copy of the primary and read capacity on hot standbys, but it does not give you automatic failover, split-brain protection, connection routing or backups. A standby that is configured with primary_conninfo, a standby.signal file and a replication role will follow the primary, and it can serve read-only queries. PostgreSQL does not detect that the primary has failed or promote a standby on its own. Someone, or a tool, has to decide that the primary is gone, promote one standby, and make sure the old primary cannot accept writes afterward. Each of those steps needs its own design, and streaming replication setup does not supply any of them.

Teams that need unattended recovery should plan the cluster layer before go-live. The sibling pages cover the main options: PostgreSQL high availability with Patroni, etcd and HAProxy is one design where a distributed configuration store holds the leader lock and a proxy routes clients to the leader, repmgr clones standbys and automates failover through repmgrd, and pg_auto_failover uses a separate monitor node. Split-brain prevention, replication slot retention, read routing and cross-region standbys are also separate topics. Backups are separate as well: a replica that faithfully copies a dropped table is not a recovery point, so point-in-time recovery needs a base backup and archived WAL, as described in the continuous archiving documentation. Confirm which backup and recovery pages your team will follow before you treat the replica as a backup.

The decision to make is whether your recovery objectives can tolerate a manual promotion, a short outage while an operator confirms the failure, and separately managed backups. If they cannot, plan an external failover tool and its fencing, routing and tests now, and budget for the people who will operate it. If they can, document the manual promotion steps, the pg_ctl promote procedure, and the expected client behavior during the outage, and test them. Confirm which option fits your environment before building the first standby.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.