How does PostgreSQL streaming replication work?
IntermediateConceptPostgreSQL
Answer
Short answer
The primary streams its WAL to one or more standbys over a replication connection; standbys replay it continuously and can serve read-only queries (hot standby). It's asynchronous by default; synchronous replication makes commits wait for a standby to confirm.
Flow
Primary ── WAL stream ──▶ Standby (hot standby, read-only)
▲ writes ▲ reads
Checking it
-- on the primary
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 a standby
SELECT pg_is_in_recovery(); -- true
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;
Failover
A standby is promoted (pg_ctl promote or SELECT pg_promote();) when the primary fails. Tools like Patroni (or Kubernetes operators like CloudNativePG) automate leader election and failover; managed services do it for you.
What to say in the interview
"The primary streams WAL to hot standbys that replay it and serve reads; I monitor pg_stat_replication for lag. Async is default, synchronous trades latency for zero data loss. Failover is promotion, automated with Patroni, an operator or a managed service."
More on PostgreSQL
How do you set up PostgreSQL and log in with psql?BeginnerHow do you create a database, tables, users and query data in PostgreSQL?BeginnerHow do you back up and restore a PostgreSQL database?BeginnerWhat is PostgreSQL and why is it so popular?BeginnerHow is PostgreSQL organised: cluster, database, schema and table?BeginnerHow do you connect to PostgreSQL from the command line?Beginner