Skip to content

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.

16 min read0/4 questions

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 busy

For 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:

db.py
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.

Predict the outputPython

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?
Need a nudge? Hints walk you through it.

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.

Two transactions from one client in transaction mode
AppPgBouncerServer conn AServer conn BSET search_path = tenant_42SET search_path = tenant_42SELECT * FROM invoicesSELECT * FROM invoicesrows from public.invoices

The app sets session state, expecting it to stick for the rest of its connection.

1/5

What breaks or needs care in transaction mode:

  • Session-level SET (use SET LOCAL inside the transaction instead, which resets at commit).
  • Session advisory locks (pg_advisory_lock); use pg_advisory_xact_lock, which is released at commit.
  • LISTEN, cursors declared WITH 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.

Python
import os, sqlite3from shopdb import connect PATH = "/tmp/pool-demo.db"if os.path.exists(PATH): os.remove(PATH)connect(PATH).close() class TransactionPooler: def __init__(self, size): self.conns = [sqlite3.connect(PATH) for _ in range(size)] self.turn = 0 def transaction(self, *statements): conn = self.conns[self.turn] # next free server connection self.turn = (self.turn + 1) % len(self.conns) try: rows = [conn.execute(s).fetchall() for s in statements][-1] conn.commit() return rows except sqlite3.Error as e: conn.rollback() return f"ERROR: {e}" pool = TransactionPooler(size=2)print("1:", pool.transaction("CREATE TEMP TABLE cart (product_id INTEGER)"))print("2:", pool.transaction("INSERT INTO cart VALUES (3)"))print("3:", pool.transaction("SELECT COUNT(*) FROM cart"))print("4:", pool.transaction( "CREATE TEMP TABLE IF NOT EXISTS cart2 (product_id INTEGER)", "INSERT INTO cart2 VALUES (3)", "SELECT COUNT(*) FROM cart2"))
Output
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 -P

SQLite has both kinds too, which lets you practice the most important habit: the restore drill.

Python
import sqlite3from shopdb import connect db = connect() dump = "\n".join(db.iterdump()) # logical: SQL textprint(dump.count("INSERT INTO"), "INSERT statements")print(dump.splitlines()[1][:60]) physical = sqlite3.connect(":memory:") # physical: copy the pagesdb.backup(physical) restored = sqlite3.connect(":memory:") # the drill: restore, then checkrestored.executescript(dump)checks = { "customers": "SELECT COUNT(*) FROM customers", "order_items": "SELECT COUNT(*) FROM order_items", "revenue": "SELECT SUM(quantity * unit_price_cents) FROM order_items",}for name, sql in checks.items(): live = db.execute(sql).fetchone()[0] back = restored.execute(sql).fetchone()[0] copy = physical.execute(sql).fetchone()[0] print(f"{name:12} live={live} logical={back} physical={copy}", "OK" if live == back == copy else "MISMATCH")
Output
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.

Recovering from a bad UPDATE
  1. 02:00

    Base backup

    Nightly pg_basebackup finishes. WAL archiving has been running all along and keeps shipping segments.

  2. 09:12

    Normal writes

    Orders and stock changes. Each commit is in the WAL, and the archive gets every segment.

  3. 10:05

    The mistake

    UPDATE products SET price_cents = 0 runs without a WHERE. It commits. The WAL faithfully records it.

  4. 10:06

    Good writes keep coming

    Customers place orders at the wrong price. These writes are real and you will need them.

  5. 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.

  6. 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.

Python
import sqlite3from shopdb import connect, show primary = connect()base_backup = sqlite3.connect(":memory:")primary.backup(base_backup) # 02:00 wal_archive = []def write(at, sql): primary.execute(sql) primary.commit() wal_archive.append((at, sql)) write("09:12", "UPDATE products SET stock = stock - 1 WHERE id = 3")write("09:40", "INSERT INTO orders VALUES (11, 8, 'paid', '2025-07-20')")write("10:05", "UPDATE products SET price_cents = 0") # no WHEREwrite("10:06", "INSERT INTO orders VALUES (12, 4, 'paid', '2025-07-20')") def restore_to(target): db = sqlite3.connect(":memory:") base_backup.backup(db) for at, sql in wal_archive: if at >= target: break db.execute(sql) db.commit() return db recovered = restore_to("10:05")show(recovered, "SELECT id, name, price_cents, stock FROM products WHERE id IN (1, 3)")show(recovered, "SELECT MAX(id) AS last_order FROM orders")
Output
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.

Python
from shopdb import connect primary, replica = connect(), connect() # replica starts as an exact copywal, replica_lsn = [], 0 def write(sql): primary.execute(sql) primary.commit() wal.append(sql) return len(wal) # the commit LSN def replay(upto): global replica_lsn for lsn in range(replica_lsn + 1, upto + 1): replica.execute(wal[lsn - 1]) replica.commit() replica_lsn = upto def read(sql, min_lsn=0): if replica_lsn >= min_lsn: return "replica", replica.execute(sql).fetchone()[0] return "primary", primary.execute(sql).fetchone()[0] q = "SELECT status FROM orders WHERE id = 10"my_lsn = write("UPDATE orders SET status = 'paid' WHERE id = 10")print("naive replica read:", replica.execute(q).fetchone()[0])print("read your writes :", read(q, min_lsn=my_lsn))replay(upto=my_lsn)print("after replay :", read(q, min_lsn=my_lsn))
Output
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 the pairs0/5 matched

Match each production problem to the tool or setting that addresses it.

Choose an item, then its match on the other side.
Quick check
Your team moves from session to transaction pooling. Which piece of code is now a bug?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the steps of a point-in-time recovery in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.