AlgoViz

PostgreSQL

medium 32 min

PostgreSQL is an open-source relational database that never overwrites a row: every change adds a new version, readers pick the version their snapshot may see, and vacuum clears away versions nobody needs.

Video lesson · Chapter 1 of 6

Two answers to one inventory question

0:00 / 4:48

PostgreSQL in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

PostgreSQL, or Postgres, is an object-relational database. You define tables, types and rules, ask questions in SQL, and group changes into transactions that happen completely or not at all. It is free software under the PostgreSQL License, which resembles the BSD and MIT licences, and no single company owns it.

One server has one supervisor process, one process per client connection, shared memory, and two kinds of files: data files and the write-ahead log. Almost everything people praise or curse about it follows from two choices: new row versions instead of overwriting, and one process per connection.

Why it exists

Most systems need a place where facts stay correct: orders, accounts, bookings. PostgreSQL gives transactions, foreign keys, checks and a real serializable level, and it lets the same database answer questions nobody planned for.

It is also broad. JSON documents, text search, ranges, geography through PostGIS and job queues can live in one database and one transaction, so a young system can run fewer products.

A short history

  1. 1986

    Implementation of POSTGRES begins at the University of California, Berkeley.

  2. 1994

    Andrew Yu and Jolly Chen add an SQL interpreter. The result is released as Postgres95.

  3. 1996

    The project is renamed PostgreSQL, and the version number continues from the Berkeley releases.

  4. June 1999

    Version 6.5 replaces table locking for readers with multi-version concurrency control.

  5. September 2010

    Version 9.0 adds streaming replication and hot standby: a standby that answers read-only queries.

  6. November 2026

    Version 19 is released, with a REPACK command and a WAIT command for read-your-writes on standbys. Each major version is supported for five years.

Words to know

Tuple
One version of one row, stored in a page.
MVCC
Multi-version concurrency control: readers use old versions instead of waiting for writers.
xmin, xmax
Hidden fields of a tuple: the transaction that created it and the one that deleted or replaced it.
WAL
Write-ahead log: changes are logged, and the log is flushed, before data pages reach the disk.
Vacuum
Cleaning that marks the space of dead tuples as reusable and freezes old ones.
Heap
The table's own pages. Rows sit in no particular order, and indexes point into it.
Backend
The server process that serves one connection.
Standby
A server that replays the primary's WAL.

How it works

Step through the idea, or press Play.

Step 1 of 4

Write a version. An update adds a tuple and closes the old one

Understand it

Start here

The museum that never paints over

Think of a conservator who looks after one drawing. Painting over it is forbidden. Every change is a new dated tracing, hung beside the old one.

One drawing, several tracings
10The first tracing

Adding is fast and lets everyone look. Someone must do the cleaning.

The product

What you get

  • Transactions and rules

    ACID, foreign keys, checks, exclusion constraints, and serializable transactions. Even schema changes can be rolled back.

  • MVCC

    Reading never blocks writing and writing never blocks reading.

  • Many index types

    B-tree, hash, GiST, SP-GiST, GIN and BRIN, plus partial, covering and expression indexes.

  • JSON and text

    Binary JSON with indexes, and language-aware text search, next to ordinary columns.

  • Extensions

    Types, functions, operators and index methods as add-ons: PostGIS, pg_trgm, TimescaleDB, Citus.

  • Free and open

    The PostgreSQL License, a community project since 1996, and many managed services.

Hard limits

WhatLimit
One table, 8 kB pages32 TB per table or partition
Columns in a table1,600, and a row's fixed part must fit a page
One field1 GB
Database sizeUnlimited
Indexes per tableUnlimited
From the product's limits page. You meet practical limits, such as vacuum time and memory, long before these.

Inside

One server, many processes

The path of a write

An application connects to one server process of its own. It reads and changes pages in shared buffers and adds records to the WAL buffers. The WAL goes to WAL files at commit, and dirty pages go to the data files later.
Two paths to disk: the log now, the pages later.
  1. 1

    Connect

    Port 5432 by default. pg_hba.conf says who may connect from where and how. Prefer SCRAM-SHA-256 with TLS: MD5 passwords are deprecated, and version 19 warns when one is used.

  2. 2

    Fork

    The supervisor, historically called the postmaster, starts a backend for the connection. A crashed backend makes the supervisor reset the others, because shared memory could be damaged.

  3. 3

    Parse and plan

    Text becomes a tree. The planner compares costs using statistics collected by ANALYZE: scan types, join order, nested loop, hash or merge join.

  4. 4

    Execute

    The executor reads 8 kB pages through shared buffers. A page in use is pinned, a changed one is dirty, and a clock sweep picks pages to evict.

  5. 5

    Log

    Each change adds a WAL record. The commit status of every transaction takes two bits in pg_xact.

  6. 6

    Write behind

    The background writer trickles dirty pages out, and the checkpointer writes the rest and marks where recovery starts. Autovacuum cleans.

The helpers and their defaults

ProcessJobDefault
WAL writerFlushes WAL between commitsEvery 200 ms
Background writerWrites some dirty pages earlyEvery 200 ms, at most 100 pages
CheckpointerWrites all dirty pages, spread out5 min or about 1 GB of WAL, target 0.9
AutovacuumVacuum and analyze where neededUp to 3 workers, wakes every minute
WAL senderStreams WAL to a standbyOne per standby
More frequent checkpoints mean faster recovery and more writing. max_wal_size is a soft limit. Watch pg_stat_bgwriter and pg_stat_checkpointer.

Inside

Durability: log first

The rule of the write-ahead log is that a data page may reach the disk only after the log record that describes its change. The backend edits the page in memory and adds the record. At commit it waits until the log is flushed. After a crash the server replays the log from the last checkpoint.

One commit

Commits that arrive together can share one flush. This is called group commit.

synchronous_commit

ValueThe client waits forA crash can lose
offNothing on diskUp to about 600 ms of commits, never consistency
localThe local flushNothing here, recent commits after a failover
on (default)Local flush, and the synchronous standby's flush if one is namedNothing while one of them survives
remote_applyThe standby has replayed itAs above, and the standby already shows it
The 600 ms is three times wal_writer_delay. You can set this per transaction: off for a click log, on for a payment.

WAL segments are 16 MB files by default. Keep them in an archive together with a base backup and you can restore to any moment in between: point-in-time recovery. pg_dump is a logical export and cannot be the base for it.

Inside

MVCC: which version do I see?

Every tuple carries xmin and xmax. A snapshot sees a tuple when the creator had committed before the snapshot and the deleter, if any, had not. Isolation levels explains the anomalies. This is how the product maps them.

The levels in PostgreSQL

You ask forYou getRemember
Read uncommittedRead committedDirty reads never happen
Read committed (default)A new snapshot per statementTwo reads may differ
Repeatable readOne snapshot, without phantomsRetry on error 40001
SerializableSnapshot plus conflict tracking (SSI)Retry on error 40001
Three levels are really implemented. The retry is the application's job and repeats the whole transaction.

Is this tuple visible?

Simplified: a transaction also sees its own changes.

Operations

Vacuum, bloat and transaction ids

  1. 1

    Reuse space

    Dead tuples no snapshot can need are removed. The file rarely shrinks, because the free space is kept for new tuples.

  2. 2

    Update the visibility map

    Pages whose tuples everyone can see let an index-only scan skip the heap.

  3. 3

    Freeze

    Transaction ids are 32 bits and circular. Old tuples are marked frozen so that they stay in the past for ever.

  4. 4

    Analyze

    A separate job, run by the same daemon, refreshes the planner's statistics.

When does autovacuum start?

min⁡(108,;50+0.2×rows)10,000,000 rows⇒2,000,050 dead tuples\min(10^8,; 50 + 0.2 \times \text{rows}) \qquad 10{,}000{,}000 \text{ rows} \Rightarrow 2{,}000{,}050 \text{ dead tuples}
Defaults, including the cap added in version 18. On a large, busy table set a smaller scale factor for that table, for example 0.02.

How long until ids run out?

2311,000 writing transactions/s≈2.15×106 s≈25 days\frac{2^{31}}{1{,}000 \text{ writing transactions/s}} \approx 2.15 \times 10^{6}\,\text{s} \approx 25 \text{ days}
Without freezing. Forced vacuums start at an age of 200 million by default. With fewer than three million ids left, the server refuses to give out new ones.

Healthy

  • Autovacuum on, and tuned for hot tables
  • Short transactions, with idle_in_transaction_session_timeout
  • Alerts on id age and on dead tuples
  • max_slot_wal_keep_size set when slots are used

What holds cleaning back

  • A transaction left open for hours
  • An abandoned replication slot
  • A forgotten prepared transaction
  • A standby with hot_standby_feedback and long queries

Speed

Choosing an index

Index types

TypeGood forExample
B-treeEquality, ranges, sorting, prefixes in C collationON users (email)
HashEquality onlyUSING hash (token)
GINMany keys per row: JSONB, arrays, textUSING gin (tags)
GiSTOverlap, nearest neighbour, ranges, geometryUSING gist (area)
SP-GiSTUnbalanced structures: points, prefixesUSING spgist (p)
BRINHuge tables in natural order, tiny sizeUSING brin (at)
SQL
-- Only some rows: the query must repeat the condition.CREATE INDEX CONCURRENTLY orders_open ON orders (user_id) WHERE status = 'open';-- Extra columns allow an index-only scan.CREATE INDEX ON users (email) INCLUDE (name, status);-- Order matters: equality columns first, then the range.CREATE INDEX ON orders (user_id, created_at DESC);-- The query must use the same expression.CREATE INDEX ON users (lower(email));
CONCURRENTLY does not block writes. It takes longer, cannot run inside a transaction, and can leave an invalid index if it fails. A unique constraint already has an index: do not add another.

Speed

Reading a plan

SQL
EXPLAIN (ANALYZE, BUFFERS)          -- ANALYZE really runs the querySELECT u.id, count(o.id) AS nFROM users u LEFT JOIN orders o ON o.user_id = u.idWHERE u.status = 'active'GROUP BY u.id ORDER BY n DESC LIMIT 10;-- Seq Scan on users (cost=0.00..1234.00 rows=5000 width=50)--                   (actual time=0.010..5.230 rows=4823.00 loops=1)--   Buffers: shared hit=500 read=50
Cost is in planner units, time in milliseconds per loop. hit pages were in shared buffers, read pages came from the system's cache or the disk.

What to look for

You seeThink of
Seq Scan keeping few of many rowsA missing index
Estimate and actual far apartANALYZE, or extended statistics
Nested Loop with many loopsA bad estimate, or no index inside
Sort spilled to diskMore work_mem for that query
lower(email) ignores the indexAn expression index
On SSDs, teams often lower random_page_cost from its default of 4. Measure before and after. JIT compilation is off by default since version 19.
SQL
-- Needs shared_preload_libraries = 'pg_stat_statements' and a restart.CREATE EXTENSION IF NOT EXISTS pg_stat_statements;SELECT left(query, 80) AS q, calls, round(total_exec_time) AS total_ms, round(mean_exec_time) AS mean_msFROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;-- Candidates for a missing index.SELECT relname, seq_scan, seq_tup_read, idx_scan, n_live_tupFROM pg_stat_user_tables WHERE seq_scan > 100 AND n_live_tup > 10000ORDER BY seq_tup_read DESC LIMIT 20;-- Never-used indexes. Check replicas and constraints before dropping.SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS sizeFROM pg_stat_user_indexes WHERE idx_scan = 0;-- Dead tuples and the last vacuum.SELECT relname, n_live_tup, n_dead_tup, last_autovacuumFROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;

Features

JSONB, text search and window functions

jsonb stores parsed JSON. It costs a little more to write than json, which keeps the exact text, and is much faster to query. See document database and full-text search for the ideas.

JSONB operators

OperatorMeaningGIN?
-> and ->>Field as JSON, field as textExpression B-tree
#> and #>>Nested path as JSON, as textExpression B-tree
@>Left contains rightYes
?, ?|, ?&Key exists: one, any, allYes, not with jsonb_path_ops
||, -, #-Merge, remove key, remove pathNot searches
jsonb_path_ops is usually smaller and faster for @>, and does not support the key-exists operators. Changing one key rewrites the whole value.
SQL
CREATE TABLE products (  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,  name       text NOT NULL,  attributes jsonb NOT NULL DEFAULT '{}',  search     tsvector GENERATED ALWAYS AS (               setweight(to_tsvector('english', name), 'A')) STORED);CREATE INDEX ON products USING gin (attributes jsonb_path_ops);CREATE INDEX ON products USING gin (search);SELECT name, attributes->'specs'->>'ram' AS ramFROM products WHERE attributes @> '{"brand": "Acme"}';UPDATE products SET attributes = jsonb_set(attributes, '{specs,storage}', '1024')WHERE id = 1;SELECT name, ts_rank(search, q) AS rankFROM products, websearch_to_tsquery('english', 'fast laptop') AS qWHERE search @@ q ORDER BY rank DESC LIMIT 20;-- Ranking, running total, moving average and growth, without losing rows.SELECT day, amount,       rank() OVER (ORDER BY amount DESC)             AS place,       sum(amount) OVER (ORDER BY day)                AS running,       avg(amount) OVER (ORDER BY day ROWS 6 PRECEDING) AS avg7,       amount - lag(amount) OVER (ORDER BY day)       AS changeFROM daily_sales;
On ties, row_number gives 1, 2, 3, 4, rank gives 1, 2, 2, 4 and dense_rank gives 1, 2, 2, 3. pg_trgm adds typo-tolerant search.

From text to a match

A dedicated engine such as Elasticsearch is worth its sync pipeline when relevance, facets and volume become the product.

Patterns

Locks, queues and partitions

SQL
-- A job queue: claim one row, skipping rows other workers hold.BEGIN;SELECT id, payload FROM jobsWHERE status = 'pending' ORDER BY idLIMIT 1 FOR UPDATE SKIP LOCKED;-- ... do the work ...UPDATE jobs SET status = 'done' WHERE id = $1;COMMIT;-- Undo a part, keep the rest.BEGIN;INSERT INTO orders (user_id, total) VALUES (1, 99.99);SAVEPOINT s;INSERT INTO shipments (order_id, address) VALUES (currval('orders_id_seq'), '1 Main St');ROLLBACK TO SAVEPOINT s;       -- only if the shipment failedCOMMIT;-- Application locks: one waits, one returns true or false.SELECT pg_advisory_lock(12345);SELECT pg_advisory_unlock(12345);SELECT pg_try_advisory_lock(12345);
No two workers hold one job at a time. Effects outside the database, such as an email, can still repeat after a crash: make them idempotent. Long jobs should not keep a transaction open; store a lease time instead.
SQL
CREATE TABLE events (  id         bigint GENERATED ALWAYS AS IDENTITY,  user_id    bigint NOT NULL,  payload    jsonb,  created_at timestamptz NOT NULL DEFAULT now(),  PRIMARY KEY (id, created_at)          -- must contain the partition key) PARTITION BY RANGE (created_at);CREATE TABLE events_2026_11 PARTITION OF events  FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');SELECT count(*) FROM events WHERE created_at >= '2026-11-15';  -- prunesALTER TABLE events DETACH PARTITION events_2026_11 CONCURRENTLY;DROP TABLE events_2026_11;              -- no row-by-row delete, no dead tuples
Split by range, list or hash. Each partition has smaller indexes and its own vacuum. pg_partman automates creation. The benefit starts when a table outgrows memory and queries name the key.

Operations

Connections need a pool

max_connections is 100 by default, and each connection is a process with its own memory, plus work_mem (4 MB by default) per sort or hash. Serverless functions and many app servers soon ask for thousands. A pooler such as PgBouncer lets them share a few.

PgBouncer modes

ModeServer connection returnsCost
session (default)When the client disconnectsLittle sharing
transactionAt the end of a transactionNo session SET, LISTEN, SQL PREPARE or session advisory locks
statementAfter each statementNo multi-statement transactions
Protocol-level prepared statements work in transaction mode when max_prepared_statements is not zero. NOTIFY works, LISTEN does not.

A starting pool size

active≈2×cores+spindles2×16+0=32\text{active} \approx 2 \times \text{cores} + \text{spindles} \qquad 2 \times 16 + 0 = 32
From the PostgreSQL wiki: spindles are zero when the active data is fully cached. 1,000 clients can share 32 busy connections. Measure from there.
Python
# psycopg 3 with an async poolimport osfrom psycopg.types.json import Jsonbfrom psycopg_pool import AsyncConnectionPoolpool = AsyncConnectionPool(os.environ["DATABASE_URL"], min_size=5, max_size=20, open=False)async def transfer(src: int, dst: int, amount) -> None:    async with pool.connection() as conn, conn.transaction():        cur = await conn.execute(            "UPDATE accounts SET balance = balance - %s WHERE id = %s AND balance >= %s",            (amount, src, amount))        if cur.rowcount == 0:            raise ValueError("insufficient funds")      # rolls back        await conn.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, dst))        # a nested conn.transaction() here would be a savepointasync def save_prefs(user_id: int, prefs: dict) -> None:    async with pool.connection() as conn:        await conn.execute(            """INSERT INTO user_settings (user_id, preferences) VALUES (%s, %s)               ON CONFLICT (user_id) DO UPDATE               SET preferences = user_settings.preferences || EXCLUDED.preferences""",            (user_id, Jsonb(prefs)))# at startup: await pool.open(); await pool.wait()    at the end: await pool.close()
Parameters are always sent apart from the SQL. Never build SQL from user text.

Growth

Replication, failover and scaling

One synchronous standby, one read replica

Application servers send writes through PgBouncer to a primary. The primary streams its WAL to a synchronous standby, which acknowledges before the commit, and to an asynchronous replica that returns rows to readers.
All writes meet on the primary. Reads that accept lag go elsewhere.

Standbys replay WAL byte for byte. Asynchronous is the default: fast, and a failover may lose the last commits. With synchronous_standby_names a commit waits for a standby, which protects those commits as long as that standby is the one promoted, and stalls writes when no such standby answers. Logical replication sends row changes instead: use it for selected tables or between versions. It does not copy schema changes.

Failover with Patroni

PostgreSQL has no built-in failure detection. Patroni keeps one leader through etcd, Consul or ZooKeeper. 30 s and a loop of 10 s are its defaults. Managed services do this for you.

What to do when it is slow

Sharding is last because every query must then know its key. See sharding.

Operations

Settings and commands

Memory settings

SettingDefaultStart with
shared_buffers128 MB25% of memory, rarely above 40%
work_mem4 MB, per operationSmall globally, more per query
maintenance_work_mem64 MBMore, for index builds and vacuum
effective_cache_size4 GB, only a hint50% to 75% of memory
wal_buffers1/32 of shared buffers, at most a segmentLeave it
Shell
psql -c "SELECT pg_size_pretty(pg_database_size('myapp'));"psql -c "VACUUM (VERBOSE, ANALYZE) users;"psql -c "SELECT pid, state, now() - xact_start AS age, left(query, 60)         FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY age DESC;"psql -c "SELECT pg_cancel_backend(12345);"      # cancel the querypsql -c "SELECT pg_terminate_backend(12345);"   # close the connectionpg_dump -Fc -f backup.dump myapp                # logical copypg_restore -d myapp backup.dumppg_basebackup -D /backup/base -X stream -P      # base for point-in-time recovery# on a standby: delay of replay (also grows when the primary is idle)psql -c "SELECT now() - pg_last_xact_replay_timestamp() AS lag;"
In psql, \d+ users shows columns, indexes and size. Practise restoring: a backup that was never restored is a hope.
SQL
CREATE TABLE users (  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,  public_id  uuid NOT NULL DEFAULT uuidv7() UNIQUE,   -- version 18 and later  email      text NOT NULL UNIQUE,  status     text NOT NULL DEFAULT 'active' CHECK (status IN ('active','inactive','suspended')),  updated_at timestamptz NOT NULL DEFAULT now());CREATE TABLE profiles (  user_id  bigint PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,  bio      text,  metadata jsonb NOT NULL DEFAULT '{}');CREATE FUNCTION touch() RETURNS trigger LANGUAGE plpgsql AS $$BEGIN  NEW.updated_at = now();  RETURN NEW;END $$;CREATE TRIGGER users_touch BEFORE UPDATE ON users  FOR EACH ROW EXECUTE FUNCTION touch();
A schema that checks itself. Use numeric for money and timestamptz for moments.

Decide

When to choose it, and what it costs

Choose it when

  • Money, bookings or stock must be right
  • Questions join many tables and keep changing
  • Mostly transactions with some reporting
  • Maps (PostGIS), JSON or text search beside relations
  • You want rich features without licence fees

Look elsewhere when

  • Writes outgrow one primary: distributed SQL, Cassandra
  • Only key lookups at huge scale: DynamoDB, Redis
  • Heavy analytics: see OLAP
  • Deep graph walks, or search as the main product
  • Automatic sharding is required from day one

Neighbours

ProductChoose it over PostgreSQL forPostgreSQL wins on
MySQLPrimary-key heavy loads, Vitess, team habitIndex types, JSONB, extensions, SQL breadth
MongoDBDocument-shaped data, built-in shardingJoins, constraints, changing questions
CockroachDBAutomatic sharding over regionsSingle-node speed and the ecosystem
TimescaleDB, CitusThey are extensions: add them insteadYou keep one database

Summary

The whole topic in one minute.

PostgreSQL adds a version for every change, so readers and writers do not block each other. The bill is paid by vacuum: if old snapshots, stuck replication slots or a lazy setting stop it, tables bloat and transaction ids run short.

Durability is the WAL, flushed at commit. The same log feeds recovery, backups to a point in time, standbys and change streams. Each connection is a process, so put a pool in front. Grow in order: queries and indexes, memory, pool, replicas, partitions, and sharding last.

  • An update adds a version. Vacuum removes versions no snapshot needs.
  • The WAL is flushed at commit, and data pages follow later.
  • Read committed is the default; retry on 40001 at higher levels.
  • Pool connections: each one is a process.
  • Pick the index by the operator, and prove it with EXPLAIN.
  • Failover needs a tool such as Patroni or a managed service.
  • Queries, memory, pool, replicas, partitions, then shards.

Sources