Databases
Run PostgreSQL in production: SQL, configuration, security, backups, replication, HA and tuning.
The full database administrator path for PostgreSQL. Start with the relational model and SQL, then learn to configure and secure a server, back it up and restore it, replicate and fail over, run it on Kubernetes, monitor it, and diagnose slow queries down to the operating system. Each subject links the official documentation or the tool's own docs.
The subjects follow the roadmap.sh PostgreSQL DBA roadmap.
PostgreSQL is an open-source, standards-focused relational database with strong consistency, rich types and a deep extension system. A DBA keeps it installed, secure, backed up, replicated, monitored and fast — this roadmap walks that whole job.
Data stored as tables of rows with typed columns, related through keys and queried declaratively with SQL; the database guarantees integrity through constraints and transactions.
Strong consistency, joins, constraints and a mature query optimiser — at the cost of schema changes needing care and writes scaling vertically before they scale out.
The vocabulary used everywhere else: databases, schemas, tables, rows and columns on the object side; relations, tuples, attributes and domains in relational theory.
Compared with MySQL, SQL Server and Oracle: transactional DDL, extensibility (custom types, index methods, extensions), JSONB, rich indexing and a permissive licence.
Document stores trade joins and constraints for flexible schemas and easy horizontal scaling. JSONB lets Postgres hold documents too, so many teams never need a second database.
How PostgreSQL organises things: a cluster runs many databases, each database holds schemas, schemas hold tables, views, functions and types. Knowing this hierarchy explains search_path, permissions and why you cannot query across databases directly.
SQL statements that read (SELECT) or change data, parsed, planned and executed by the server. Everything a client does goes through them.
Numeric, text, boolean, date/time with time zones, UUID, arrays, JSONB, ranges, enums and more. Pick the narrowest type that fits — timestamptz over timestamp, text over varchar(n) without a real limit.
One record in a table. Each row version also carries hidden system columns (xmin, xmax, ctid) that MVCC uses.
A named, typed field with optional default, generated expression and constraints. Adding a column with a default is cheap in modern versions.
The main storage object: columns, constraints and storage options, optionally partitioned, unlogged or temporary.
Namespaces inside a database for organising objects and permissions. search_path decides which schemas unqualified names resolve against — lock it down in security-sensitive functions.
Isolated collections of schemas within one cluster, created from a template and connected to one at a time.
The theory under SQL: relations (tables) are sets of tuples (rows) over attributes (columns) whose values come from domains. Constraints and NULL semantics are where theory meets day-to-day bugs.
The set of allowed values for an attribute. PostgreSQL lets you define reusable domains — a base type plus checks, like an email or positive amount.
Named properties of a relation — columns in SQL terms — each drawn from a domain.
An ordered set of attribute values — a row. Internally, every update writes a new tuple version, which is why vacuuming exists.
A set of tuples sharing the same attributes. In PostgreSQL "relation" covers tables, views, indexes and sequences — anything listed in pg_class.
Rules the database enforces: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY and EXCLUDE. They are the last line of defence for data integrity — never rely on the application alone.
Unknown, not empty: NULL = NULL is NULL, not true. Use IS NULL, IS DISTINCT FROM and COALESCE, and remember aggregates and UNIQUE treat NULL specially.
The ideas that make PostgreSQL trustworthy and fast: ACID transactions, MVCC so readers never block writers, the write-ahead log for durability, and the parse → rewrite → plan → execute pipeline behind every query.
Atomicity, consistency, isolation, durability — a transaction applies entirely or not at all, respects constraints, is isolated from others and survives a crash once committed.
Multi-version concurrency control: each transaction sees a snapshot, updates create new row versions, and old versions linger until vacuum removes them. Readers and writers do not block each other.
BEGIN … COMMIT, savepoints, and isolation levels — Read Committed by default, Repeatable Read and Serializable when you need stronger guarantees and can retry on serialisation failures.
Every change is written to the WAL before the data files. It makes commits durable, enables crash recovery, and is the stream replication and point-in-time recovery are built on.
A query is parsed, rewritten (views, rules), planned by the cost-based optimiser using table statistics, then executed as a tree of nodes you can inspect with EXPLAIN.
Get a server running the way it will run in production: from your OS packages or containers, managed by the service manager, with a client to connect. Know where the data directory and configuration files live.
The official image is the fastest way to a local server: set POSTGRES_PASSWORD, mount a volume for /var/lib/postgresql/data, and pin a major version tag.
Install from the PGDG repositories (apt.postgresql.org, yum.postgresql.org) rather than the distro's default, to get current major versions and timely updates.
The interactive terminal: \l, \dt, \d table, \x, \timing, \e and running scripts with -f. A DBA lives in it.
Managed services (RDS, Cloud SQL, Azure, Neon) handle backups, patching and failover, but limit superuser access and extensions. Understand what you give up before choosing.
On most Linux servers PostgreSQL runs as a systemd unit: systemctl start|stop|restart|reload postgresql, with logs in the journal.
The core tool to init, start, stop (smart, fast, immediate), reload and promote a server for a given data directory.
Debian and Ubuntu's wrapper for running several clusters and versions side by side, with pg_lsclusters to list them.
A DBA must read and write SQL fluently: DDL to define structures, DML to query and change data, and bulk import and export. Write it by hand before relying on an ORM, and learn to read what an ORM generates.
Data definition: CREATE, ALTER, DROP and COMMENT for schemas, tables, indexes and views. In PostgreSQL DDL is transactional, so a failed migration rolls back cleanly.
CREATE SCHEMA … AUTHORIZATION, moving objects with ALTER … SET SCHEMA, and setting search_path per role or database.
CREATE TABLE with constraints and defaults, ALTER TABLE to evolve it — knowing which changes rewrite the table or take strong locks.
Data manipulation: SELECT, INSERT, UPDATE, DELETE and MERGE, with RETURNING to get changed rows back in the same round trip.
SELECT lists, expressions, ORDER BY, LIMIT and DISTINCT ON — the bread and butter of reading data.
WHERE with comparisons, IN, BETWEEN, LIKE/ILIKE, ANY, and HAVING for filtering groups.
INSERT … ON CONFLICT for upserts, UPDATE … FROM joins, DELETE … USING, and batching large changes to keep locks and WAL volume manageable.
Inner, left, right, full and cross joins, plus semi- and anti-joins with EXISTS/NOT EXISTS. Index your foreign keys — Postgres does not do it for you.
COPY streams data in and out in CSV or binary — far faster than row-by-row inserts. \copy in psql does the same through the client.
The SQL that separates a DBA from a casual user: subqueries and CTEs (recursive too), lateral joins, set operations, window functions, and server-side code with PL/pgSQL, procedures and triggers.
Queries inside queries: scalar subqueries, IN/EXISTS, and derived tables in FROM. The planner often turns them into joins.
GROUP BY with aggregates, FILTER (WHERE …) for conditional aggregates, and GROUPING SETS, ROLLUP and CUBE for subtotals.
WITH names intermediate results for readability, and data-modifying CTEs chain inserts and updates in one statement. Modern versions inline simple CTEs unless you mark them MATERIALIZED.
WITH RECURSIVE walks hierarchies and graphs — org charts, category trees, bill of materials — with SEARCH and CYCLE clauses to control order and loops.
LATERAL lets a subquery in FROM reference earlier tables — perfect for "top N per group" and calling set-returning functions per row.
UNION, INTERSECT and EXCEPT combine result sets; prefer UNION ALL when duplicates are impossible, to skip the deduplication step.
Aggregates collapse rows; window functions (row_number, rank, lag, running sums with OVER) compute across rows while keeping each one.
Functions return values and run inside the caller's transaction; procedures (CALL) can commit mid-way. Mark volatility (IMMUTABLE, STABLE) correctly so the planner can optimise.
Postgres's procedural language: variables, loops, conditionals and exception blocks around SQL — for logic that belongs next to the data.
Functions fired before or after row or statement changes — for audit logs, derived columns and integrity checks. Use them sparingly: hidden logic surprises people.
postgresql.conf controls memory, WAL, checkpoints, vacuum, replication, the planner and logging. The defaults suit a tiny machine — tune the handful of settings that matter for your hardware and workload, and know which need a restart and which a reload.
shared_buffers (often ~25% of RAM), work_mem per sort or hash node, maintenance_work_mem, and connection limits. work_mem multiplies across concurrent queries — size it carefully.
wal_level, synchronous_commit, max_wal_size and WAL compression trade durability, replication features and I/O against each other.
Checkpoints flush dirty pages so recovery has a starting point; spread them out (checkpoint_timeout, checkpoint_completion_target) to avoid I/O spikes. The background writer trickles pages out in between.
Autovacuum removes dead row versions, updates statistics and prevents transaction-id wraparound. Tune its thresholds per busy table rather than turning it off — ever.
Settings for senders and standbys: max_wal_senders, replication slots, hot_standby, synchronous standby names and WAL retention.
Cost constants (random_page_cost lower on SSDs), effective_cache_size, statistics targets and parallel query settings shape the plans you get.
Log slow statements (log_min_duration_statement), lock waits, checkpoints, autovacuum runs and temp files, with a log_line_prefix your log analyser understands.
CREATE EXTENSION adds features packaged with Postgres (pg_stat_statements, pg_trgm, postgres_fdw) or from third parties (PostGIS, pgvector). Some need shared_preload_libraries.
Least privilege end to end: who may connect and how (pg_hba.conf, SCRAM, TLS), what each role may do (privileges, default privileges, row-level security), and how to share data safely (anonymisation).
Users and groups are both roles. Give applications a non-superuser login role, grant through group roles, and never connect apps as postgres.
SELECT, INSERT, UPDATE, DELETE, USAGE, EXECUTE and more, on tables, schemas, sequences and functions — including column-level grants.
GRANT and REVOKE manage privileges and role membership. Revoke CREATE on the public schema in older clusters.
ALTER DEFAULT PRIVILEGES makes objects created later get the right grants automatically — otherwise every new table needs a manual grant.
SCRAM-SHA-256 passwords, certificates, peer for local OS users, LDAP, GSSAPI. Avoid trust and the legacy md5.
Rules matched top to bottom by connection type, database, user and address, each naming an auth method. Reload after editing and check pg_hba_file_rules for errors.
Encrypt connections with TLS: server certificates, ssl_min_protocol_version, hostssl rules, and clients using sslmode=verify-full.
Policies that filter which rows each role sees or changes — the base of many multi-tenant designs. Table owners bypass them unless you force RLS.
sepgsql applies SELinux mandatory access control labels to database objects, on top of normal privileges — for high-security deployments.
An extension that masks or replaces personal data with declared rules, so you can hand realistic data to developers and analysts safely.
Beyond the database itself: provisioning hardware, replication, connection pooling, backups, upgrades, high availability, Kubernetes and monitoring. The next subjects cover each area; start by sizing the machine the database runs on.
Size CPU, RAM and especially storage I/O for the workload, track growth, and plan headroom before you need it — disk filling up is the classic outage.
Copies of the database on other servers, for read scaling, failover and upgrades. Physical replication copies the whole cluster byte for byte; logical replication sends row changes for chosen tables.
Standbys stream WAL from the primary and replay it continuously — asynchronous by default, synchronous when you cannot lose a commit. Use replication slots and watch lag.
Publications and subscriptions replicate row changes per table — across major versions and to different schemas. DDL and sequences are not replicated.
Each Postgres connection is a whole process with its own memory, so hundreds of idle app connections hurt. A pooler multiplexes many client connections onto a few server ones.
The lightweight standard pooler. Transaction pooling gives the biggest win but breaks session state — prepared statements need care and SET and advisory locks do not carry over.
Multi-threaded or feature-rich options: PgCat (sharding, load balancing), Odyssey, Supavisor, and Pgpool-II.
A backup only counts once you have restored it. Combine logical dumps for portability with physical base backups plus WAL archiving for point-in-time recovery, and test restores on a schedule.
A consistent logical dump of one database. Use the custom or directory format (-Fc, -Fd) for parallel, selective restores.
Dumps the whole cluster as SQL, including roles and tablespaces — run it with --globals-only alongside per-database dumps.
Restores custom or directory-format dumps, in parallel with -j, optionally only chosen objects.
Takes a physical copy of a running cluster over the replication protocol — the starting point for standbys and point-in-time recovery.
Backup and recovery manager for fleets of servers: base backups, WAL streaming, retention policies and remote recovery.
Archives base backups and WAL to object storage (S3, GCS, Azure) with compression and encryption.
Parallel, incremental and differential backups with verification, encryption and repository retention — the most common serious choice.
Incremental backups with page-level change tracking, validation and merge, from Postgres Professional.
Automate regular test restores, verify checksums (pg_verifybackup, pgbackrest verify) and measure how long recovery really takes against your RTO.
Minor versions are drop-in binary updates — apply them promptly. Major versions change the on-disk format and need a dump and restore, pg_upgrade, or logical replication to a new cluster for near-zero downtime.
Upgrades a cluster in place in minutes, with --link or --clone to avoid copying data files. Run --check first, and re-analyse afterwards.
Replicate into a new-version cluster, let it catch up, then switch the application over — downtime measured in seconds.
High availability means automatic, safe failover: detect a dead primary, promote the best standby, and stop the old primary from coming back as a second writer (split brain).
The standard HA template: a distributed configuration store (etcd, Consul) holds the leader lock, and Patroni manages replication, failover and configuration.
repmgr for simpler replica management and failover, and pg_auto_failover with its monitor node.
Clients must always find the current primary and spread reads over replicas. Service discovery and load balancers route connections so failover does not mean reconfiguring every application.
A TCP load balancer that health-checks nodes (often Patroni's REST API) and routes writes to the primary and reads to replicas.
Service discovery and a key/value store: DNS names that always point at the current primary, and a DCS for Patroni.
Moves a virtual IP between nodes with VRRP so clients keep one address across failover.
A consistent distributed key/value store — the most common place Patroni keeps its leader lock.
Databases on Kubernetes need stable identities and persistent volumes, and an operator that understands Postgres for failover, backups and upgrades. Do not run production Postgres as a plain Deployment.
A StatefulSet with a persistent volume claim gives one Postgres pod stable storage — fine for development, not for HA.
Package manager for Kubernetes; charts install Postgres or an operator with configurable values.
Controllers that run Postgres clusters declaratively — CloudNativePG, Crunchy PGO, Zalando — with failover, backups to object storage and rolling upgrades.
Watch connections, transaction rates, cache hit ratio, replication lag, bloat, long-running transactions, wraparound age and disk space — and alert before users notice. The statistics views are the raw data every tool reads.
Scrapes metrics from postgres_exporter into a time-series store; graph them in Grafana and alert with Alertmanager.
An all-in-one monitoring platform with ready-made PostgreSQL templates.
A Postgres-specific web console for monitoring and administering many instances.
A Nagios-compatible plugin with dozens of Postgres checks — bloat, replication, locks, wraparound.
Monitors pgBackRest backups and WAL archives so you know a backup actually exists before you need it.
Anything done by hand twice should be scripted: provisioning, configuration, backups, checks. Use shell for glue, a real language for logic, and configuration management so servers are reproducible.
Bash with set -euo pipefail, psql with -v ON_ERROR_STOP=1 and -At for parseable output, and a .pgpass file instead of passwords on the command line.
Python (psycopg), Go (pgx) or similar for automation that outgrows shell — proper error handling, retries and tests.
Agentless configuration management over SSH, with a postgresql collection for users, databases and settings.
Event-driven configuration management and remote execution at scale.
Configuration as Ruby code in cookbooks, applied by an agent.
Declarative configuration management with a model-driven language.
Schema changes on a live database must not lock out traffic. Version every change, make each one backwards compatible with the running code, and know which operations take heavy locks.
Set lock_timeout, build indexes CONCURRENTLY, add constraints NOT VALID then validate, expand-then-contract column changes, and backfill in batches.
Flyway, Liquibase and Sqitch version SQL migrations; ORMs ship their own. Linters like squawk flag dangerous statements in review.
Postgres can be a dependable job queue, which spares you another system. The key is SELECT … FOR UPDATE SKIP LOCKED, short transactions and keeping the queue table small and vacuumed.
Use SKIP LOCKED workers and LISTEN/NOTIFY for wake-ups; avoid polling hot tables in long transactions and letting finished jobs pile up unarchived.
A mature queue extension (from Skype) with batching and multiple consumers; pgmq is a newer, simpler alternative.
Good schemas make correct queries easy: normalise first, denormalise deliberately, choose keys and types carefully, and split very large tables by partitioning or sharding only when the numbers demand it.
1NF to BCNF remove redundancy so each fact lives in one place. Denormalise later, with a measured reason, using materialized views or generated columns.
Declarative range, list or hash partitioning splits a huge table so queries prune partitions and old data drops in a single DETACH.
Spreading data across servers by a shard key — with Citus, foreign data wrappers or application routing. It costs cross-shard joins and transactions, so exhaust a single node first.
Most performance problems are query problems: N+1 queries, SELECT *, OFFSET pagination on big tables, functions on indexed columns, and row-by-row loading. Learn the patterns that keep queries index-friendly and set-based.
Load with COPY, batch inserts in transactions, drop or defer indexes and constraints during huge loads, then ANALYZE. Process large updates in chunks.
How the server works inside: one process per connection plus background workers, shared buffers in front of the OS cache, 8 kB pages on disk, MVCC row versions cleaned by vacuum, and a lock manager coordinating it all.
The postmaster forks a backend per connection; the checkpointer, background writer, WAL writer and autovacuum run alongside. Shared memory holds buffers and locks; each backend has local work memory.
Vacuum removes dead tuples, updates the visibility and free-space maps, and freezes old transaction ids to prevent wraparound.
Pages are read into shared buffers, pinned while in use and evicted by a clock-sweep. Dirty pages are written by the background writer and checkpointer.
Table-level lock modes, row locks, advisory locks and deadlock detection. pg_locks with pg_blocking_pids() shows who is waiting on whom.
Each table is files of 8 kB pages under the data directory, with TOAST for large values and separate visibility and free-space map forks.
Postgres describes itself in tables — pg_class, pg_attribute, pg_index, pg_namespace — and every \d command in psql is a query over them.
There is no universally right configuration: short transactional workloads, long analytical scans and mixed ones want different memory, parallelism, indexing and storage settings. Measure your workload, then tune for it.
Many small, concurrent transactions: favour connection pooling, selective indexes, small work_mem, aggressive autovacuum and low-latency storage.
Large scans and aggregations: more work_mem, parallel query, BRIN indexes, partitioning and materialized views — or a columnar extension.
Both at once on one database: isolate analytics on replicas, cap resources per role, and watch long queries holding back vacuum.
Per-table settings: fillfactor for HOT updates on update-heavy tables, and per-table autovacuum thresholds for big, busy ones.
ALTER ROLE … SET and ALTER DATABASE … SET give reporting users more work_mem and app users a statement_timeout, without changing the whole server.
EXPLAIN shows the plan the optimiser chose; EXPLAIN (ANALYZE, BUFFERS) runs it and shows what really happened. Compare estimated and actual rows, find the expensive node, then fix statistics, indexes or the query.
Read plans bottom-up: scan types, join methods, sorts, loops and costs. With ANALYZE and BUFFERS you see real timings and pages touched.
explain.depesz.com colours a pasted text plan by where time is spent, with exclusive time per node.
A visual plan explorer — a tree and flame graph of the plan — that runs in the browser or embeds in your tools.
explain.tensor.ru visualises plans and suggests fixes for common problems.
The hosted PEV2: paste a plan, get a shareable visual analysis.
The cumulative statistics views are a DBA's first stop when something is slow: what is running, what is waiting, which queries cost the most, which tables need vacuum.
One row per connection: current query, state, wait event and how long the transaction has been open. Find blockers and idle-in-transaction sessions here.
Aggregated statistics per normalised query — calls, total and mean time, rows, buffer hits. Sort by total time to find what to optimise first.
Terminal tools built on the statistics views give a live, top-like picture of a server without setting up a monitoring stack.
A top-like admin tool for Postgres: activity, tables, indexes, replication and I/O stats in one terminal UI.
Many database problems are really CPU, memory or disk problems. Classic Linux tools show whether the machine itself is saturated.
Live CPU and memory per process — spot a runaway backend, then match its PID in pg_stat_activity.
sar, iostat and mpstat: historical and live CPU, disk and network statistics — iostat -x shows disk saturation.
Per-process disk I/O, to see which backend or vacuum worker is hammering the disk.
When statistics are not enough, look inside the process: where CPU goes, which system calls block, and what a crashed backend was doing.
Attach to a stuck backend to print a stack trace, or open a core dump after a crash.
Traces system calls of a process — useful to see a backend waiting on I/O, locks or the network.
CPU profiling and flame graphs with Linux perf, plus Brendan Gregg's perf-tools scripts for tracing I/O and latency.
Enable core files for the postgres user so a crashing backend leaves evidence you can analyse with gdb or send in a bug report.
Safe kernel-level tracing (bcc, bpftrace) to measure latency and I/O in production with little overhead.
Postgres logs record slow queries, errors, lock waits, checkpoints and autovacuum. Turn them into reports, or slice them quickly with classic text tools.
Parses Postgres logs into an HTML report: slowest and most frequent queries, errors, locks, connections and checkpoints.
Collects and reports cluster and system statistics over time for audits and capacity planning.
Field-based text processing for quick aggregations — counting errors per hour, summing durations.
Find lines that match a pattern — every ERROR, every lock wait, everything from one PID.
Stream editing: extract or rewrite parts of log lines before further processing.
Methods beat guessing. Work through resources and services systematically so you find the bottleneck rather than the first thing that looks odd.
For every resource — CPU, memory, disk, network — check Utilisation, Saturation and Errors.
For every service, track Rate, Errors and Duration of requests — the user-facing view.
Google SRE's four: latency, traffic, errors and saturation — a good default set of database alerts.
Indexes trade write speed and space for faster reads. Know the index types and when each fits, use partial, expression and covering (INCLUDE) indexes, and remove the unused ones that only slow writes.
The default: equality, ranges, sorting and prefix LIKE. Column order in multi-column indexes matters.
Equality only, sometimes smaller than a B-Tree for long keys; crash-safe and replicated since version 10.
A framework for geometric, range and full-text indexes — and for exclusion constraints like "no overlapping bookings".
Space-partitioned trees (quad-trees, k-d trees, radix trees) for non-balanced data like points and IP ranges.
Inverted indexes for values containing many items: JSONB, arrays, full-text search and trigram similarity.
Tiny block-range summaries for huge tables whose values follow physical order, like append-only timestamps.
PostgreSQL is built in the open by its community. Following the lists, testing and reviewing patches is how DBAs influence the features they will run in a few years.
pgsql-hackers for development, pgsql-general and pgsql-performance for users — where design decisions and bug reports happen.
Pick a patch from the CommitFest, build it, test it against real workloads and report back — reviewers are always the scarcest resource.
Discuss on pgsql-hackers first, follow the coding conventions, include tests and docs, and register the patch in the next CommitFest.