🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Management / Database Administration › PostgreSQL Administration › Lesson 7
TEC-DATA86-03 · Lesson 7 · 13 clock hours · lab

Streaming Replication Setup and Failover

Objective. Students configure streaming replication between a primary and a hot-standby PostgreSQL server, verify replication lag, and perform a controlled promote-standby failover.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Streaming Replication in PostgreSQL

Streaming replication allows a standby PostgreSQL server to stay continuously synchronized with a primary server by receiving Write-Ahead Log (WAL) records over a network connection. This is the foundation of high-availability deployments and is a core skill tested on the PostgreSQL CE (EDB) exam.

How WAL-Based Replication Works

PostgreSQL writes every change to the WAL before applying it to data files. In streaming replication, the standby connects to the primary using a special replication protocol, and the primary streams WAL segments to the standby in near-real time. The standby continuously replays those WAL records, keeping its data close to the primary's state. A hot standby goes further: it allows read-only queries while replay is running, making it useful for reporting workloads as well as failover.

Configuring the Primary Server

On the primary, set `wal_level = replica` in `postgresql.conf`. This level records enough information for the standby to replay changes and to support logical decoding if needed. You must also set `max_wal_senders` to a value greater than zero (commonly 5 or 10) so the primary can serve WAL to standby connections.

Create a dedicated database role for replication:

```sql

CREATE ROLE replicator REPLICATION LOGIN PASSWORD 'strong_password';

```

In `pg_hba.conf`, add a line that permits the standby's IP address to connect with the `replication` database keyword:

```

host replication replicator <standby_ip>/32 scram-sha-256

```

Reload or restart the primary after these changes.

Building the Standby with pg_basebackup

`pg_basebackup` copies the primary's data directory to the standby host and places the server in a consistent state. Run it on the standby machine:

```bash

pg_basebackup -h <primary_ip> -U replicator -D /var/lib/postgresql/16/main \

-P -Xs -R

```

The `-R` flag writes a minimal `standby.signal` file and a `postgresql.auto.conf` entry for `primary_conninfo`, saving manual configuration. Verify the `primary_conninfo` string in `postgresql.auto.conf` contains the correct host, port, and user.

Starting the Standby and Verifying Replication

Start PostgreSQL on the standby. Because `standby.signal` is present, the server enters standby mode and begins WAL streaming. On the primary, query `pg_stat_replication` to confirm the connection:

```sql

SELECT client_addr, state, write_lag, flush_lag, replay_lag

FROM pg_stat_replication;

```

A row with `state = streaming` confirms the standby is receiving WAL. The three lag columns measure latency at different stages of the replication pipeline: write_lag is the delay until the primary acknowledges the WAL was written on the standby, flush_lag is the delay until it was flushed to disk, and replay_lag is the delay until it was replayed into the standby's data files.

Measuring Replication Lag

To observe lag deliberately, call `pg_wal_replay_pause()` on the standby, then insert rows on the primary. The standby receives WAL but does not apply it, so `replay_lag` grows. After calling `pg_wal_replay_resume()`, the standby catches up and the lag columns return toward zero. This exercise shows that committed transactions are not lost — WAL was received and buffered — and that catch-up happens automatically once replay resumes.

Performing a Controlled Failover

A controlled failover (sometimes called a switchover when planned) proceeds as follows:

1. Stop the primary cleanly with `pg_ctl stop -m fast`.

2. On the standby, run `pg_ctl promote` or create a `promote` trigger file if configured. PostgreSQL finishes replaying available WAL, removes `standby.signal`, and opens the server for read-write connections.

3. Verify promotion by connecting with `psql` and running `SELECT pg_is_in_recovery();` — it should return `false`.

4. Confirm that data committed on the primary before the stop is present on the new primary.

Document every step in a failover runbook. A runbook is a step-by-step procedure, kept current and tested, so any qualified team member can execute a failover under pressure without missing a step.

Safety and Operational Notes

Always use strong passwords and encrypted connections (`scram-sha-256` or TLS) for the replication role — replication accounts have elevated access. Restrict `pg_hba.conf` entries to the minimum required IP range. Before performing any failover in production, verify you have a recent backup independent of replication; replication is not a substitute for backup. Capture screenshots or log output at each verification step so you have an audit trail. When working on shared lab VMs, confirm with your instructor before stopping any PostgreSQL service that classmates may be using.

Key terms10

Streaming ReplicationA PostgreSQL feature in which a standby server connects to the primary and receives WAL records continuously over a network connection, keeping the standby's data closely synchronized.
WAL (Write-Ahead Log)A sequential log of all changes made to a PostgreSQL database, written before the changes are applied to data files; the basis for both crash recovery and replication.
Hot StandbyA standby PostgreSQL server that accepts read-only SQL queries while simultaneously replaying WAL records from the primary.
pg_basebackupA PostgreSQL utility that creates a consistent base backup of a running primary server, used to initialize the standby's data directory.
pg_stat_replicationA system view on the primary server that shows one row per connected standby, including the standby's IP address, replication state, and write, flush, and replay lag values.
replay_lagThe time elapsed between when the primary flushed a WAL record and when the standby applied (replayed) that record to its data files; one of three lag columns in pg_stat_replication.
pg_ctl promoteA command-line action that instructs a PostgreSQL standby to finish replaying available WAL and then transition to a fully read-write primary server.
Failover RunbookA documented, step-by-step procedure that an operations team follows to promote a standby to primary, ensuring no steps are skipped under pressure.
wal_levelA postgresql.conf parameter that controls how much information is written to the WAL; must be set to 'replica' or higher to support streaming replication.
standby.signalA file placed in the PostgreSQL data directory that causes the server to start in standby (recovery) mode rather than as a normal read-write primary.
In class: On a two-VM lab network, configure the primary server with wal_level = replica, create a replication role, add a pg_hba.conf entry for the standby, and use pg_basebackup to create the initial standby data directory; start the standby with a postgresql.conf primary_conninfo entry and confirm replication is active via pg_stat_replication on the primary. · Simulate replication lag by pausing the standby (pg_wal_replay_pause()), generating 10,000 rows of data on the primary with a provided INSERT script, then resuming replay (pg_wal_replay_resume()) and measuring catch-up time; record write_lag, flush_lag, and replay_lag from pg_stat_replication. · Perform a controlled failover: stop the primary, run pg_ctl promote on the standby, verify the standby becomes read-write, then reconnect a psql client to the new primary and confirm data written before the failure is present; write a one-page failover runbook documenting each step.
Materials: Two Linux VMs on the same virtual network, PostgreSQL 16 on both, pg_basebackup, pg_stat_replication view, failover runbook template, PostgreSQL Documentation Chapter 26 (High Availability)
Check: Instructor inspects pg_stat_replication output (captured screenshot) during replication and confirms the promoted standby is writable with no data loss for committed transactions; pass = replication confirmed AND failover runbook includes all steps in correct order.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

PostgreSQL High Availability and Replication
1. Which postgresql.conf parameter must be set on the primary server to enable streaming replication to a hot standby?
PostgreSQL High Availability and Replication
2. A DBA runs pg_basebackup with the -R flag. What does this flag do?
PostgreSQL High Availability and Replication
3. On the primary, a DBA queries pg_stat_replication and sees state = 'catchup' instead of 'streaming' for the standby. What does this indicate?
PostgreSQL High Availability and Replication
4. After calling pg_wal_replay_pause() on the standby and then inserting 10,000 rows on the primary, which pg_stat_replication column will grow the most?
PostgreSQL High Availability and Replication
5. A DBA executes SELECT pg_is_in_recovery(); on a PostgreSQL server and receives 'false'. What does this confirm?
PostgreSQL Security and Authentication
6. Which pg_hba.conf database keyword must be used in the entry that allows the replication role to connect from the standby?
PostgreSQL High Availability and Replication
7. During a controlled failover, a DBA stops the primary cleanly and then promotes the standby. Which statement about committed transactions is correct?
PostgreSQL Security and Authentication
8. Why is it important to use scram-sha-256 (or equivalent strong authentication) for the replication role in pg_hba.conf rather than the 'trust' method?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.