How do replication, high availability and connection pooling work for PostgreSQL in production?
Physical (streaming) replication
Standbys replay the primary's write-ahead log (WAL) byte for byte. They are read-only and can serve queries (hot standby). Asynchronous by default; synchronous_commit with synchronous_standby_names waits for a standby to confirm, trading latency for zero data loss.
Logical replication
Publishes row changes per table (CREATE PUBLICATION / CREATE SUBSCRIPTION). Works across major versions, which enables near-zero-downtime upgrades, and feeds change data capture (Debezium → Kafka) through replication slots.
Failover and HA
PostgreSQL itself does not elect a new primary. Tools do: Patroni (with etcd or Consul), repmgr, Kubernetes operators (CloudNativePG, Crunchy), or managed services (Cloud SQL HA, RDS Multi-AZ, Aurora). Applications connect through a virtual IP, DNS name or proxy that follows the primary.
Connection pooling
Each PostgreSQL connection is a separate process with its own memory, so thousands of connections hurt. Use a pool in the app (HikariCP: size it near cores * 2 per instance, not hundreds) and, with many app instances or serverless, PgBouncer in transaction mode in front of the database. In transaction mode, session state (session-level prepared statements, SET, advisory locks) does not carry across transactions.
Backups and recovery
Base backups plus archived WAL enable point-in-time recovery (pgBackRest, Barman, WAL-G, or managed PITR). Test restores regularly.
Example
# Spring Boot: primary for writes, replica for read-only transactions (via a routing DataSource)
spring:
datasource:
url: jdbc:postgresql://pg-primary:5432/shop
hikari:
maximum-pool-size: 10 # per app instance; total across instances must fit max_connections
connection-timeout: 3000
max-lifetime: 1500000
app:
replica-url: jdbc:postgresql://pg-replica:5432/shop-- Replication lag as seen from the primary
SELECT client_addr, state, sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind
FROM pg_stat_replication;Follow-up questions interviewers ask
Try answering each one before you open it.
Why can an abandoned replication slot take down the primary?
A slot makes the primary keep all WAL the consumer has not confirmed. If a CDC consumer stops, WAL accumulates until the disk fills and the database stops. Monitor pg_replication_slots (retained WAL) and set max_slot_wal_keep_size to cap it.