Skip to content
Engineering Bible
SQL and Databases

SQL and Databases on production

Connections are expensive, so pool them

  • PostgreSQL starts a whole server process for every connection.
  • The default limit, max_connections, is typically 100.
  • A pool keeps a few connections open and lends one to each request.
  • Count them all: 20 app servers with a pool of 10 each already need 200.

A pooler shares connections between many clients

  • PgBouncer sits between the app and the database. Many clients share a few connections.
  • In transaction pooling, a client holds a real connection only during a transaction.
  • That breaks session features such as SET, LISTEN and session-level advisory locks.

Replicas replay the primary's log

  • PostgreSQL records every change in the write-ahead log (WAL).
  • A replica receives the WAL as a stream and applies it. It can serve read-only queries.
  • Replication is asynchronous by default. A replica is typically under a second behind.
  • So a read from a replica straight after a write can miss it. Read that from the primary.

Replication

  1. Primarytakes every write
  2. WAL streamasynchronous by default
  3. Replicaread-only queries

Backup

  1. Base backupa copy of the data files
  2. WAL archiveevery change since
  3. Restoreto any moment you pick
The same log feeds both. Replicas keep you online. Backups let you go back in time.

Failover needs a plan

  • If the primary dies, an asynchronous replica can lack the last few commits.
  • Synchronous replication makes each commit wait for a replica: no loss, slower writes.
  • PostgreSQL does not detect a dead primary by itself. A tool or a person promotes a replica.

A replica is not a backup

  • A bad DELETE reaches every replica within about a second.
  • pg_dump writes a SQL copy of the database as of the moment it started.
  • A base backup plus archived WAL restores to any moment: point-in-time recovery.
  • Practice the restore. A backup you have never restored is only a hope.

Start relational and add other stores for a reason

  • A relational database answers questions you did not plan for: any filter, any join.
  • Key-value stores like DynamoDB are fast for the few lookups you designed them for.
  • Other queries there are slow and costly, so you must know your access patterns up front.
  • SQLite has no server: one file, one writer at a time. Good for apps and small sites.
SQL and Databases in seven pages7 / 7