Lesson 25 of 29Postgres in production
Connections, Backups and Replicas
Size connection pools, pick a PgBouncer mode, take backups you can restore to any second, and handle replica lag and failover in app code.
It is launch day. Traffic triples, the autoscaler adds twenty API pods, and within a minute every request fails with FATAL: sorry, too many clients already. The database is not slow. It is out of connection slots. Two hours later someone runs an UPDATE without a WHERE, and the team discovers that the nightly backup has never once been restored. By evening the read replica is ten seconds behind and users report that orders they just placed "disappeared". None of this is about writing SQL, and all of it is part of running Postgres in production. This lesson covers the three things that keep a database alive under real traffic: connections, backups and replicas.
Why connections are scarce
Postgres uses a process per connection. When a client connects, the postmaster forks a new backend process. That process has its own memory for sorting, hashing and caching the catalog, typically a few megabytes when idle and much more while it runs a big query (each sort or hash can use up to work_mem). Connecting is also slow: TCP, TLS, authentication and process start add up to several milliseconds before the first query runs.
The server enforces a hard ceiling, max_connections, which defaults to 100. Raising it to 2,000 does not help, for two reasons. First, memory: 2,000 backends that each sort at once can exhaust RAM. Second, a CPU with 8 cores can only run 8 queries at a time. The other 1,992 wait, and while they wait they compete for locks, buffers and the CPU scheduler. Throughput goes down past a point, and latency goes up for everyone.
The modern app stack makes this worse. Every API process keeps its own pool. Autoscaling multiplies processes. Serverless functions can open a connection per invocation. The PostgreSQL for Developers lesson showed the multiplication (servers times workers times pool size). The fix is the same at every scale: keep a small number of real connections busy, and queue the rest outside the database.
Sizing the pool
The surprising rule: a smaller pool is usually faster. A queue in your app is cheap and fair. A queue inside Postgres, as hundreds of backends fighting over 8 cores, is expensive and unfair.
A useful starting point, from the HikariCP team and Postgres folklore, is:
connections ≈ (CPU cores × 2) + number of disks the database can keep busyFor an 8-core managed instance that is about 20 active connections for the whole database, not per app server. Then measure: if the database CPU is idle while requests wait for a connection, the pool is too small; if CPU is pinned and query latency climbs with concurrency, it is too big. Long-running queries change the maths, which is one more reason to keep transactions short.
In app code, SQLAlchemy's engine pool has the knobs you will touch most:
from sqlalchemy import create_engine
engine = create_engine(
"postgresql+psycopg://app@db-proxy:6432/shop",
pool_size=5, # connections kept open per process
max_overflow=5, # extra connections allowed under bursts, then closed
pool_timeout=10, # seconds to wait for a free connection before raising
pool_pre_ping=True, # test a connection before use, replace it if dead
pool_recycle=1800, # close connections older than 30 minutes
)pool_timeout matters more than it looks. A request that waits 30 seconds (the default) for a connection is worse than one that fails fast with a clear error your load balancer can retry elsewhere. pool_pre_ping costs one tiny round trip and saves you from "server closed the connection unexpectedly" after a failover or an idle timeout.
What does this print?
# 6 API pods, 3 worker processes each # SQLAlchemy: pool_size=5, max_overflow=10 # Postgres: max_connections = 100, 3 reserved for superusers # How many connections can the app open at peak?
PgBouncer and transaction pooling
An app-side pool cannot share connections between processes. A connection pooler can. PgBouncer is the classic: a small, single-threaded proxy that speaks the Postgres protocol. Your apps open thousands of cheap connections to PgBouncer, and it maps them onto a small pool of real server connections. Its pool_mode decides when a server connection is handed back:
- Session: the client keeps one server connection until it disconnects. Safe for everything, but it only helps if clients connect and disconnect often.
- Transaction: the client gets a server connection for one transaction, then gives it back. This is the mode that gives you real sharing, and it is the usual choice.
- Statement: returned after every statement. Multi-statement transactions are not allowed. Rarely used.
Transaction mode has a cost you must know: the next transaction from the same client may run on a different server connection. Anything that lives in the session, rather than the transaction, can vanish or leak to another client.
The app sets session state, expecting it to stick for the rest of its connection.
What breaks or needs care in transaction mode:
- Session-level
SET(useSET LOCALinside the transaction instead, which resets at commit). - Session advisory locks (
pg_advisory_lock); usepg_advisory_xact_lock, which is released at commit. LISTEN, cursors declaredWITH HOLD, and temporary tables that outlive a transaction.- Prepared statements used to break. PgBouncer 1.21 added support for protocol-level prepared statements in transaction mode through
max_prepared_statements. If your driver caches prepared statements (asyncpg does), check that setting and your driver's docs.
You can watch the session-state bug happen. This block builds a tiny transaction pooler over two real connections to the same database file and hands them out round robin.
Press Run (⌘ Enter) to see what happens.Transaction 2 lands on the other connection and the temp table does not exist there. Transaction 3 is back on the first connection, where the table exists but is empty. Transaction 4 keeps all the session-dependent work inside one transaction, which is the rule for transaction pooling.
Managed platforms ship their own poolers: Amazon RDS Proxy, Supabase's Supavisor, and Neon's built-in pooler (PgBouncer underneath). They follow the same model with their own limits on session state, so read the "pinning" or "limitations" page for yours.
Backups: logical and physical
There are two kinds of Postgres backup, and they answer different questions.
A logical backup is SQL, or a compact archive of it. pg_dump takes a consistent snapshot of one database while it stays online, and pg_restore replays it. Use the custom format (-Fc) or directory format (-Fd) so you can restore in parallel with -j and pick single tables out of the archive. pg_dumpall --globals-only captures roles and tablespaces, which pg_dump skips. Logical dumps are portable across major versions and CPU architectures, which makes them great for copying a database, seeding staging, or keeping a long-term archive. They are slow to restore at size, because every index is rebuilt from scratch, and they only capture the moment the dump started.
A physical backup copies the data files themselves. pg_basebackup (or a tool like pgBackRest, Barman or WAL-G) takes a base backup, and WAL archiving ships every write-ahead log segment to storage as it fills. Base backup plus the WAL that followed lets you replay history to any moment: point-in-time recovery (PITR). Postgres 17 added incremental base backups (pg_basebackup --incremental, with summarize_wal on, merged by pg_combinebackup), which shrink the cost of frequent backups on big databases.
# Logical: one database, parallel restore, pick tables laterpg_dump -Fd -j 4 -d shop -f /backups/shop-2026-10-22pg_restore -j 4 -d shop_restore /backups/shop-2026-10-22# Physical base backup with the WAL it needs, streamed while runningpg_basebackup -D /backups/base-2026-10-22 -X stream -c fast -PSQLite has both kinds too, which lets you practice the most important habit: the restore drill.
Press Run (⌘ Enter) to see what happens.A real drill does the same thing on a schedule: restore last night's backup to a throwaway instance, run checks like these (row counts, a revenue total, the newest created_at), record how long it took, and alert if anything fails. A backup you have never restored is not a backup. It is a hope. Common silent failures are a WAL archive with a gap, a backup that excluded a tablespace, an encryption key nobody can find, and a restore that works but takes nine hours.
Point-in-time recovery
PITR is what saves you from the UPDATE without a WHERE. You restore the last base backup to a new server, set restore_command to fetch archived WAL, set recovery_target_time to just before the mistake, and start it. Postgres replays every committed change up to that moment and stops.
02:00
Base backup
Nightly pg_basebackup finishes. WAL archiving has been running all along and keeps shipping segments.
09:12
Normal writes
Orders and stock changes. Each commit is in the WAL, and the archive gets every segment.
10:05
The mistake
UPDATE products SET price_cents = 0 runs without a WHERE. It commits. The WAL faithfully records it.
10:06
Good writes keep coming
Customers place orders at the wrong price. These writes are real and you will need them.
10:30
Restore to 10:04:59
A new instance restores the base backup and replays WAL up to the target. Prices are correct there.
11:00
Repair, not replace
Copy the correct prices back to production, then deal with the 10:06 orders by hand. Do not throw away an hour of good data.
The simulation below does the same thing with a base backup and a log of statements standing in for WAL.
Press Run (⌘ Enter) to see what happens.The recovered copy has the right prices and the 09:12 stock change, and it does not have order 12. That is the trade-off of any restore: recovery to a point also loses the good writes after it. Seniors restore to a side instance and repair production from it, rather than replacing production wholesale.
Two numbers frame every backup decision. RPO (recovery point objective) is how much data you can afford to lose; continuous WAL archiving gets it to seconds, nightly dumps alone make it up to 24 hours. RTO (recovery time objective) is how long you can be down; it is set by restore speed, which only a drill can tell you. Multi-Region and Disaster Recovery covers how RPO and RTO drive the whole DR strategy, so here it is enough to know which Postgres tool moves which number.
Replicas and replication lag
Streaming replication sends the primary's WAL to one or more standbys, which replay it and can serve read-only queries (hot standby). Replication and Sharding in the system design course explains leaders, followers and failover in general. The Postgres details that matter in code are these.
By default replication is asynchronous: the primary commits without waiting for any standby. You can make it synchronous with synchronous_standby_names (for example ANY 1 (replica_a, replica_b)), and synchronous_commit picks how far the standby must get: remote_write, on (flushed to the standby's disk) or remote_apply (replayed, so visible to reads there). Synchronous replication protects committed data on failover, at the cost of a network round trip on every commit, and if no synchronous standby answers, commits wait.
Replication lag is the gap between the primary and a replica. It is usually milliseconds and spikes during big batch updates, index builds and vacuum. Watch it with replay_lag in pg_stat_replication on the primary, or now() - pg_last_xact_replay_timestamp() on the replica. Lag creates the bug from the intro: a user writes on the primary, the next page reads from a replica, and their change is not there yet.
Press Run (⌘ Enter) to see what happens.The fixes, from simplest to most precise: route a user's reads to the primary for a few seconds after they write (a "sticky primary" flag in the session); send any read that must be fresh, like "show my order" right after checkout, to the primary always; or remember the commit's WAL position (pg_current_wal_lsn()) and only use a replica that has replayed past it (pg_last_wal_replay_lsn()). Postgres 19 adds a WAIT FOR LSN command that makes the last option a single statement on the replica; it is new, so check the release notes for the final syntax before you rely on it.
Two replica traps catch people in their first on-call rotation. A long query on a replica can be cancelled with "canceling statement due to conflict with recovery", because replay needs to remove rows the query still reads; hot_standby_feedback and max_standby_streaming_delay trade that for bloat or lag. And a replication slot whose consumer has died keeps WAL forever, until the primary's disk fills. Set max_slot_wal_keep_size and alert on slot lag.
Logical replication sends row changes, not disk pages, through publications and subscriptions. It can replicate a subset of tables and works across major versions, which makes it the tool for near-zero-downtime upgrades and for change data capture: Debezium reads the same logical decoding stream to publish every change to Kafka.
Failover and upgrades
When the primary dies, something must promote a standby and move clients to it. Self-hosted teams use Patroni, which uses etcd or Consul to elect one leader and fence the old one so you never have two primaries (split brain). Managed services do it for you: RDS Multi-AZ, Aurora and Cloud SQL flip a DNS name or endpoint to the new primary, usually within a minute or two.
Your app code is part of failover. During that window, existing connections break, in-flight transactions are rolled back, and new connections fail until DNS points at the new primary. The app must reconnect (pool_pre_ping, short pool_recycle), must not cache DNS forever, and must retry failed transactions only when they are safe to repeat. A retry of a non-idempotent payment after a "connection lost during COMMIT" error can charge twice, because you cannot tell whether the commit landed. Idempotency keys, covered in Consistency and CAP, are the answer.
Major version upgrades have two standard paths. pg_upgrade --link rewrites the system catalogs and reuses the data files, so it takes minutes, but the database is down while it runs. Before Postgres 18 the upgraded cluster also started with no planner statistics, and queries were slow until ANALYZE finished; Postgres 18 keeps the statistics across pg_upgrade. For near-zero downtime, build a new cluster on the new version, copy data with logical replication, let it catch up, then switch the app over in seconds. Managed "blue/green" upgrade features are this pattern packaged.
Match each production problem to the tool or setting that addresses it.
Put the steps of a point-in-time recovery in order.
- Tap the steps below in the right order.
- connection pooler
- A proxy such as PgBouncer that lets many client connections share a small number of real database connections.
- transaction pooling
- A pooler mode that assigns a server connection for one transaction only, so session state like SET does not carry over.
- logical backup
- A dump of a database as SQL or an archive of it (pg_dump). Portable across versions, slow to restore at size.
- physical backup
- A copy of the database files (pg_basebackup), which with archived WAL allows point-in-time recovery.
- point-in-time recovery
- Restoring a base backup and replaying archived WAL up to a chosen moment, such as just before a mistake.
- replication lag
- How far a replica is behind the primary, which makes recent writes invisible to reads served there.
- replication slot
- A record on the primary of how much WAL a consumer still needs. An abandoned slot keeps WAL until the disk fills.