PostgreSQL¶
Scope: designing and running PostgreSQL databases for applications, on the major versions the PostgreSQL project currently supports. Architecture-level data rules, such as data ownership, consistency between services, the transactional outbox and versioned migrations, are in general/data.md; this file covers how to apply them in PostgreSQL. For secrets, see general/security.md, and for connecting from serverless functions, see Serverless and edge hosting.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 9 PostgreSQL Documentation (PostgreSQL Global Development Group): the baseline. Read the manual for the version you run; the chapters on data definition, indexes, concurrency control, performance tips, routine maintenance, backup and restore, client authentication and database roles matter most for application work.
- 8 Backup and Restore (PostgreSQL docs): SQL dumps, file system backups and continuous archiving with point-in-time recovery, and the trade-offs between them.
- 7 Don't Do This (PostgreSQL wiki): a short list of common mistakes in data types, SQL constructs, tools and authentication, with the rare cases where each is still the right choice.
- 7 Versioning Policy (PostgreSQL): how long each major version is supported, what minor releases contain, and the end-of-life date of every release.
- 7 Performance Tips (PostgreSQL docs): reading query plans with
EXPLAIN, planner statistics, and populating a database efficiently. - 7 PgBouncer features (PgBouncer): the session, transaction and statement pooling modes and which PostgreSQL features each one supports.
Key rules¶
Schema and data types¶
- 8
PG-1Declare integrity rules as constraints in the database: a primary key on every table,NOT NULLon most columns, and foreign key, unique and check constraints where the data needs them. PostgreSQL then rejects every write that would break them, whichever code path makes it. (PostgreSQL, Constraints) - 7
PG-2Store points in time astimestamptz, nottimestamp.timestamptzrecords an instant and converts input with a time zone to UTC;timestampsilently ignores the time zone, so arithmetic across zones or daylight saving changes can be wrong. (PostgreSQL wiki, Don't use timestamp (without time zone), PostgreSQL, Date/Time Types: Time Stamps) - 6
PG-3Generate keys with identity columns, such asid bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, instead ofserial.serialmakes schema, dependency and permission management cumbersome. An identity column doesn't guarantee uniqueness by itself, so also make it the primary key. (PostgreSQL wiki, Don't use serial, PostgreSQL, Identity Columns) - 6
PG-4Usetextfor strings, rather thanchar(n)or avarchar(n)with an arbitrary limit. The types perform the same,char(n)pads values with spaces, and an arbitrary limit rejects real data later. (PostgreSQL, Character Types, PostgreSQL wiki, Don't use char(n), Don't use varchar(n) by default)
Indexes and queries¶
- 7
PG-5Add indexes for the queries the application actually runs: find the costly ones withpg_stat_statements, check their plans withEXPLAIN ANALYZEon realistic data, and drop indexes that are never used. Every index slows down writes. PostgreSQL doesn't index the referencing columns of a foreign key, so index them yourself when you join on them or delete referenced rows. (PostgreSQL, Examining Index Usage, Indexes: Introduction, pg_stat_statements, Foreign Keys)
Schema migrations¶
- 8
PG-6Create and drop indexes on tables in use withCREATE INDEX CONCURRENTLYandDROP INDEX CONCURRENTLY. A plainCREATE INDEXblocks writes to the table until it finishes. The concurrent forms can't run inside a transaction block. A failed concurrent build leaves anINVALIDindex behind: drop it and try again. (PostgreSQL, CREATE INDEX: Building Indexes Concurrently, DROP INDEX) - 7
PG-7Set a shortlock_timeoutat the start of each migration, and retry the migration when it times out. ManyALTER TABLEforms need anACCESS EXCLUSIVElock; while the statement waits behind a long-running transaction, all later reads and writes on the table wait behind it. (PostgreSQL, lock_timeout, Table-Level Locks, Squawk, Applying migrations safely) - 7
PG-8Add foreign key and check constraints to existing tables asNOT VALID, then runVALIDATE CONSTRAINTin a separate transaction. Adding the constraint then skips the table scan, and validation takes a lock that lets writes continue. PostgreSQL 18 also allows this for not-null constraints. (PostgreSQL, ALTER TABLE: Notes)
Connections and transactions¶
- 7
PG-9Put a connection pooler such as PgBouncer between the database and large numbers of clients, such as many app instances or serverless functions, instead of raisingmax_connections. In transaction pooling mode, don't use session state such asSET,LISTEN, SQLPREPAREor session-level advisory locks. (PostgreSQL wiki, Number Of Database Connections, PgBouncer, SQL feature map for pooling modes, PostgreSQL, max_connections) - 7
PG-10Keep transactions short, setidle_in_transaction_session_timeoutto end abandoned ones, and leave autovacuum on. An open transaction keeps its locks and stops vacuum from removing dead rows, which bloats tables. (PostgreSQL, idle_in_transaction_session_timeout, Deadlocks, Recovering Disk Space)
Backup and recovery¶
- 9
PG-11Test restores regularly, and check that the restored database works and contains the correct data.pg_verifybackupchecks a base backup against its manifest, but the PostgreSQL docs say it doesn't replace a test restore. (PostgreSQL, pg_verifybackup, Backup and Restore) - 8
PG-12Back up production databases with continuous archiving, base backups plus archived WAL, so that you can restore to any point in time, not only to the last dump. Set up and test WAL archiving before you take the first base backup. (PostgreSQL, Continuous Archiving and Point-in-Time Recovery)
Security¶
- 8
PG-13Connect the application as a role that isn't a superuser and doesn't own the tables, and grant it only the privileges it needs; run migrations as a separate owner role. Owners can alter or drop their objects, a right that can't be revoked, and normally bypass row security. (PostgreSQL, Role Attributes, Privileges, Row Security Policies) - 7
PG-14Usescram-sha-256password authentication over TLS, and have clients verify the server withsslmode=verify-full. MD5 passwords are deprecated, andtrustauthentication over TCP/IP lets clients connect as any user without a password. (PostgreSQL, Password Authentication, libpq SSL Support, PostgreSQL wiki, Don't use trust authentication over TCP/IP) - 5
PG-15When tenants share tables, isolate their rows with row security policies, and make sure the application role isn't the table owner or useFORCE ROW LEVEL SECURITY. Superusers, roles withBYPASSRLSand, by default, table owners bypass the policies. (PostgreSQL, Row Security Policies)
Versions¶
- 9
PG-16Run a supported major version, apply each minor release soon after it ships, and upgrade to a newer major version before the current one reaches end of life. Each major version is supported for five years, and the project recommends always running the current minor release. Major upgrades needpg_upgradeor a dump and restore. (PostgreSQL, Versioning Policy, pg_upgrade)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 pg_verifybackup: built into PostgreSQL; checks a base backup taken with
pg_basebackupagainst its manifest, and can be run after every backup. Partly checksPG-11. - 6 Squawk: a linter for PostgreSQL migration files that runs in CI and in editors, and can comment on GitHub pull requests.
require-concurrent-index-creation,require-concurrent-index-deletionandban-concurrent-index-creation-in-transactioncover index changes,constraint-missing-not-validflags constraints added withoutNOT VALIDor validated in the same transaction,require-lock-timeoutflags migrations without alock_timeout, andprefer-timestamptz,prefer-identity,prefer-text-fieldandban-char-fieldflag the column types. ChecksPG-2,PG-4,PG-6andPG-8, and partlyPG-3andPG-7. - 5 pgBackRest
check: validates that WAL archiving and backups are configured correctly, and detects archiving problems that would leave backups incomplete;verifychecks that the backups and archived WAL in a repository are valid. Partly checksPG-11andPG-12.
Tutorials and further reading¶
- 7 Tutorial (PostgreSQL docs): the official introduction to PostgreSQL, relational concepts and SQL.
- 7 Use The Index, Luke (Markus Winand): a free online book on SQL indexing and query tuning for developers, with notes for PostgreSQL.
- 5 PostgreSQL 14 Internals (Egor Rogov, Postgres Professional): a free book on MVCC, vacuum, the buffer cache, WAL, locks, query execution and index types.