Backups, replication and production
Running PostgreSQL in production means planning for the bad days: a disk dies, someone runs DELETE without WHERE, traffic grows 10×. This lesson covers the practices that keep data safe and fast, then sends you off with a capstone project.
Connecting from your app
Apps talk to Postgres through a driver, and often an ORM or query builder on top:
| Language | Driver | Popular tools on top |
|---|---|---|
| Node.js / TypeScript | pg (node-postgres), postgres |
Prisma, Drizzle, Kysely |
| Python | psycopg |
SQLAlchemy, Django ORM |
| Java / Kotlin | JDBC | Spring Data JPA, jOOQ |
| Go | pgx |
sqlc, GORM |
// Node.js with node-postgres
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
export async function getCustomer(id) {
const { rows } = await pool.query('SELECT id, name, email FROM customers WHERE id = $1', [id]);
return rows[0] ?? null;
}
export async function transfer(from, to, amount) {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from]);
await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to]);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release(); // always give the connection back to the pool
}
}Connection pooling
Each Postgres connection is a separate server process using memory (several MB). A few hundred connections are fine; thousands will hurt. Serverless functions that each open their own connection can exhaust the server quickly.
- Use a pool inside each app instance (as above,
max: 10). - For many app instances or serverless, put PgBouncer (or your provider's pooler) in front: thousands of client connections share a few dozen server connections.
Migrations
Schema changes should be code: versioned files in git, applied the same way in every environment. Tools: Prisma Migrate, Drizzle Kit, Flyway, Liquibase, Alembic, golang-migrate. Rules for zero-downtime changes on big tables:
- Add columns as nullable (or with a constant default); backfill in batches.
CREATE INDEX CONCURRENTLY; add constraints withNOT VALID, thenVALIDATElater.- Never rename or drop a column the running app version still uses: expand first, migrate the code, then contract.
- Set a
lock_timeoutso a migration waiting for a lock gives up instead of blocking every query behind it.
Backups
A backup you haven't restored is not a backup. Test restores regularly.
Logical backups: pg_dump
pg_dump exports a database as SQL or a compressed archive. It's great for small-to-medium databases, copying data between environments, and upgrades.
pg_dump -Fc -d shop -f shop.dump # custom format: compressed, flexible
pg_restore -d shop_restored --jobs 4 shop.dump # restore in parallel
pg_dump -d shop --schema-only > schema.sql # just the structure
pg_dumpall --roles-only > roles.sql # roles live outside databasesPhysical backups and point-in-time recovery
Every change is first written to the WAL (write-ahead log). If you keep a base backup plus every WAL file since, you can restore the database to any moment, for example to one second before that accidental DELETE. This is PITR (point-in-time recovery).
- Tools: pgBackRest, Barman, WAL-G (to S3 or similar).
- Managed services (RDS, Cloud SQL, Neon, Supabase…) do this for you; learn where the "restore to time" button is before you need it.
Replication and high availability
| Type | How it works | Use for |
|---|---|---|
| Streaming (physical) replication | Replicas replay the primary's WAL byte for byte | Read replicas, failover standby |
| Logical replication | Publishes row changes for chosen tables | Zero-downtime upgrades, syncing some tables, feeding other systems |
-- Logical replication, on the source:
CREATE PUBLICATION shop_pub FOR TABLE orders, customers;
-- On the destination:
CREATE SUBSCRIPTION shop_sub CONNECTION 'host=source dbname=shop user=repl' PUBLICATION shop_pub;- Read replicas take reporting and read-heavy traffic off the primary. Replication is usually asynchronous, so replicas may be a little behind ("replication lag").
- Automatic failover promotes a replica when the primary dies. Self-hosted, teams use Patroni; managed services have it built in (often called "Multi-AZ" or "high availability").
Monitoring and tuning
Watch these:
- Slow queries: enable the
pg_stat_statementsextension, then look at the queries with the highesttotal_exec_time.EXPLAIN ANALYZEthem. - Connections and long-running or idle-in-transaction sessions (
pg_stat_activity). - Cache hit ratio, disk usage, replication lag, and dead tuples / autovacuum activity.
Key settings to know (the defaults are conservative):
| Setting | Starting point |
|---|---|
shared_buffers |
~25% of RAM |
effective_cache_size |
~50–75% of RAM (a planner hint, not an allocation) |
work_mem |
Memory per sort/hash operation; raise carefully (it's per operation, per connection) |
maintenance_work_mem |
Higher speeds up VACUUM and index builds |
random_page_cost |
Lower (e.g. 1.1) on SSDs |
Upgrades
PostgreSQL ships a new major version every year, and each is supported for five years. Minor releases (18.1 → 18.2) are bug and security fixes: apply them promptly; they're a restart. Major upgrades use pg_upgrade (fast, in place), dump and restore, or logical replication to a new server for near-zero downtime.
Production checklist
- App connects as a least-privilege role, over TLS, with a connection pool
- Automated backups with PITR, and a tested restore procedure
- A replica / high-availability setup for anything important
- Migrations in version control, run by CI/CD
-
pg_stat_statementson; alerts for slow queries, disk space, connections, replication lag - Indexes on foreign keys and frequent filters; unused indexes removed
- Autovacuum healthy; no long idle-in-transaction sessions
- Minor versions patched; a plan for the next major upgrade
🎓 PostgreSQL track complete!
You can design schemas with strong types and constraints, write advanced SQL (upserts, CTEs, LATERAL, JSONB, full-text search), add logic with functions and triggers, tune queries with indexes and EXPLAIN, reason about transactions and locking, secure data with roles and RLS, and run Postgres in production.
Capstone project: a multi-tenant task tracker
Build it in a local Postgres (Docker is easiest):
- Tables:
tenants,users,projects,tasks(with a status enum,due_on date,tags text[],meta jsonb) andcomments. Use identity oruuidv7()keys, foreign keys with sensibleON DELETErules, andCHECKconstraints. - A trigger maintaining
updated_at, and an audit table recording status changes. - A view
overdue_tasksand a materialized view with per-project statistics. - Full-text search over task titles and descriptions.
- Row-level security so each tenant's app role sees only its own data.
- Seed 1 million tasks with
generate_series; useEXPLAIN ANALYZEto make your three most common queries fast. - Write a small API (any language) that uses parameterised queries and a transaction for "move task + add comment".
- Back it up with
pg_dump, drop the database, and restore it.
1.Why put PgBouncer in front of PostgreSQL?
2.Someone deleted important rows 10 minutes ago. Which backup approach can restore to just before that moment?
3.What's the safe way to add an index to a busy production table?