Your shop app runs on 50 servers, and they all talk to one Postgres. It has a users table and an orders table. Each chapter takes one thing the app does, like a query or a COMMIT, and follows it down into Postgres. You also see the common ways Postgres can take your app down.
After this post you can:
- size connections and
work_memwithout crashing the server - explain what an UPDATE, a VACUUM and a COMMIT do on disk
- pick an index, check it with EXPLAIN, and ship a schema change without locking out your app
All examples ran on PostgreSQL 18, the current major version.
One process per connection#
Each of the 50 app servers keeps a pool of 20 database connections. That is 1,000 connections, and Postgres starts to struggle before any real query runs.
Words you need:
- Process: a running program with its own memory, managed by the operating system.
- Postmaster: the parent Postgres process. It listens on the port and starts a new process for each new connection.
- Backend: the process that serves one client connection. Your queries run here.
- Session: one connection's life, from connect to disconnect.
- Pooler: a small program between your app and Postgres that shares a few database connections among many clients.
- The app opens a connection. The postmaster is listening on the port.
- The postmaster starts a new backend process for this client.
- Every query on this connection runs in backend 1, until the client disconnects.
- A second connection gets a second backend process, with its own memory.
Each time a client connects, the postmaster starts a new backend process for it. The backend lives until the client disconnects.
See it yourself. Open one psql session (the Postgres command-line client) on a fresh Postgres 18, and ask pg_stat_activity, a built-in view with one row per Postgres process:
SELECT backend_type FROM pg_stat_activity ORDER BY 1;
backend_type
------------------------------
autovacuum launcher
background writer
checkpointer
client backend
io worker
io worker
io worker
logical replication launcher
walwriter
Every line is a separate operating system process. The client backend line is you. Open a second psql window and run it again: a second client backend shows up. The others do background work:
| Process | What it does |
|---|---|
| checkpointer | writes all changed pages (8 KB blocks of a table) to disk at a checkpoint (WAL chapter) |
| background writer | writes some changed pages early, so checkpoints have less to do |
| walwriter | flushes the write-ahead log to disk (WAL chapter) |
| autovacuum launcher | starts workers that clean up dead rows (VACUUM chapter) |
| io worker | new in Postgres 18: does disk reads for backends (io_method = worker is the default) |
Old guides also list a "stats collector" process. It is gone since Postgres 15. Activity statistics (counters like rows read) now live in shared memory.
Why 1,000 connections hurt#
1,000 connections are 1,000 backend processes. Each one has its own private memory (next chapter), and the operating system has to switch between all of them. Most sit idle most of the time, but they still cost memory and a process slot.
There is also a hard limit. max_connections is 100 by default. Once it is reached, new connections get an error (a few slots stay reserved for superusers, the admin users). Check yours with SHOW max_connections; before you pick pool sizes.
The fix: a pooler#
A pooler like PgBouncer sits between the app and Postgres. The app opens 1,000 connections to PgBouncer. PgBouncer keeps a small pool of real Postgres connections (say 20) and lends them out.
PgBouncer has three pool modes:
| Mode | A Postgres connection is given back when | Notes |
|---|---|---|
| session | the client disconnects | the default, barely better than no pooler |
| transaction | the transaction ends | the common choice for web apps |
| statement | each query ends | multi-statement transactions are not allowed |
Transaction mode is where the savings come from. A client only holds a real connection while a transaction runs. Most clients are idle at any moment, so "one process per client" becomes "one process per busy transaction". The cost: a SET command can be lost, because your next transaction may get a different connection.
- The client runs SET search_path = app (which schema, a named group of tables, to search) once, outside any transaction.
- PgBouncer runs it on Postgres connection 1, then gives that connection back.
- The next transaction arrives.
- It runs on connection 2, which never got the SET.
PgBouncer's docs list what never works in transaction mode:
SETandRESET(useSET LOCALinside a transaction instead)LISTEN(waits for messages that another session sends withNOTIFY)- session-level advisory locks (locks your app takes on a number, not on a table)
- SQL
PREPAREandDEALLOCATE(save a parsed query under a name, and remove it)
Prepared queries from your driver are different:
- Your database driver can prepare queries itself, as part of the network protocol, without SQL
PREPARE. - These work in transaction mode as long as PgBouncer's
max_prepared_statementsis not zero. - Since PgBouncer 1.24 the default is 200. Before that it was 0 (off).
Your app has 30 servers with a pool of 10 connections each, and no pooler. How many backend processes serve them?
You move to PgBouncer in transaction mode. Which code breaks?
Memory and the work_mem trap#
Words you need:
- Shared memory: memory that every Postgres process can see.
- Shared buffers: the page cache inside shared memory. Pages read from disk land here first.
- Private memory: memory that belongs to one backend only.
- work_mem: how much memory one sort or one hash step may use before it spills to temporary files on disk.
- hash_mem_multiplier: hash steps may use
work_memtimes this number. The default is 2.0.
The database server has 64 GB of RAM and 200 connections. Someone sets work_mem = 256MB because "we have lots of RAM". At peak, each connection runs a query with one sort and one hash join.
A hash join builds a hash table in memory from one table. Then it looks up each row of the other table in that hash table.
The math, step by step:
- The sort may use up to
work_mem: 256 MB. - The hash join may use up to
work_mem × hash_mem_multiplier: 256 MB × 2 = 512 MB. - One query: 256 + 512 = 768 MB.
- 200 queries at the same time: 200 × 768 MB = 153,600 MB, about 150 GB.
That is more than twice the RAM. Not every query hits the limit at the same moment, but a traffic spike can get close. Then the operating system runs out of memory and may kill a Postgres process. Postgres then ends every connection and runs crash recovery (WAL chapter).
work_mem is a limit for each sort or hash step, in each query, in each connection. One query can run several sorts and hashes at once, and many sessions do this together. Each backend has its own private memory, and all of them share one big cache:
So the safe pattern is:
- Keep
work_memsmall for everyone. The default is 4 MB. - Raise it only for the one big query that needs it, inside a transaction:
BEGIN;
SET LOCAL work_mem = '256MB'; -- only for this transaction
SELECT user_id, sum(total_cents) FROM orders GROUP BY user_id;
COMMIT; -- work_mem goes back to normal
SET LOCAL also works with PgBouncer in transaction mode.
| Setting | Kind | Default | Note |
|---|---|---|---|
shared_buffers | shared | 128 MB | the docs suggest 25% of RAM as a start on a dedicated server |
work_mem | private, per operation | 4 MB | multiply by operations and connections |
hash_mem_multiplier | private | 2.0 | hash steps get twice work_mem |
maintenance_work_mem | private | 64 MB | used by VACUUM and CREATE INDEX |
How to see a spill#
When a sort needs more than work_mem, it writes to temporary files. To see it, run the query with EXPLAIN ANALYZE, which runs the query and shows real numbers (the EXPLAIN chapter has more). Here is a real line from sorting 2 million orders rows with work_mem = 1MB:
Sort Method: external merge Disk: 41120kB
"external merge" plus "Disk" means the sort spilled. It is slower, but nothing crashes. A sort that fits shows Sort Method: quicksort Memory: 25kB instead.
work_mem = 64MB. One query has 2 sorts and 1 hash join, and 50 connections run it at once. What is the worst case?
One report query needs a big sort. What is the safest fix?
Pages, tuples and the CTID#
Where does a row really live? You need this to understand why updates make tables grow, and what an index really points to.
Words you need:
- Page: a fixed block of 8 KB. Postgres reads and caches whole pages, never single rows.
- Tuple: one stored version of a row. Postgres uses this word for a row on disk.
- Line pointer: a 4-byte slot at the top of the page that says where a tuple sits in that page.
- CTID: a tuple's address: (page number, line pointer number).
- Heap: Postgres's name for a table's own data file, where the tuples live (an index is a separate file).
- xmin / xmax: the ID of the transaction that created this tuple, and the one that deleted it (0 if none yet).
Make a tiny table and ask Postgres:
CREATE TABLE users (
id bigint PRIMARY KEY,
name text NOT NULL,
email text,
balance_cents bigint NOT NULL DEFAULT 0
);
INSERT INTO users (id, name, email, balance_cents) VALUES
(1, 'Alice', 'alice@example.com', 10000),
(2, 'Bob', 'bob@example.com', 5000),
(3, 'Cara', 'cara@example.com', 0);
SELECT ctid, xmin, xmax, id, name FROM users;
SELECT pg_relation_filepath('users');
Real output from Postgres 18 (your numbers will differ):
ctid | xmin | xmax | id | name
-------+------+------+----+-------
(0,1) | 754 | 0 | 1 | Alice
(0,2) | 754 | 0 | 2 | Bob
(0,3) | 754 | 0 | 3 | Cara
pg_relation_filepath
----------------------
base/5/16384
ctid,xminandxmaxare hidden columns that every table has.(0,1)means page 0, slot 1.base/5/16384is the file on disk, inside the data folder.
From table to file to page#
A table is one or more files:
base/5/16384 the users table, first 1 GB
base/5/16384.1 the next 1 GB
base/5/16384_fsm free space map
base/5/16384_vm visibility map
- Each file grows up to 1 GB. After that, Postgres starts a new file with
.1at the end, then.2, and so on. - A
_fsmfile (free space map) tracks which pages have room. - A
_vmfile (visibility map) tracks which pages have no dead tuples. Dead tuples are old row versions nobody can see any more (MVCC chapter).
Each file is a list of 8 KB pages. When Postgres needs one row, it reads the whole 8 KB page that holds it. Pages are also what shared buffers caches.
A page fills from both ends:
+-----------------------------------+ byte 0
| Page header (24 bytes) |
+-----------------------------------+
| Line pointer 1 | 2 | 3 | ... | grows down
| |
| free space |
| |
| ... tuple 3 | tuple 2 | tuple 1 | grows up
+-----------------------------------+ byte 8191
Line pointers are added from the top. Tuples are added from the bottom. When the two meet, the page is full and the next row goes to another page.
Each tuple has a small header (23 bytes on most machines) before your column data. The header holds xmin, xmax and a few flags. The MVCC chapter shows why xmin and xmax matter so much.
How a lookup finds a row#
An index does not store the row. It stores the CTID. Follow SELECT name FROM users WHERE id = 2:
- The primary key index finds id = 2 and returns CTID (0,2).
- Postgres checks shared buffers for page 0 of the users file.
- Not cached: it reads the whole 8 KB page from disk into shared buffers.
- It reads line pointer 2 at the top of the page. It gives the spot of the tuple inside the page.
- It checks xmin and xmax to see if this version is visible to you.
- It returns the name: Bob.
Thanks to the line pointer, a tuple can move inside its page (when Postgres compacts free space) and keep the same CTID. The line pointer keeps its number. Only the spot it points to inside the page changes.
Never use a CTID as an ID. It changes when the row is updated, or moved by VACUUM FULL (a command that rewrites the table, VACUUM chapter). The docs say not to use it as a row identifier. Use the primary key.
A row has ctid (12,5). What does that mean?
Your query needs one 100-byte row. How much does Postgres read?
MVCC: an UPDATE is a new row#
Guess first: Session A is renaming Alice but has not committed yet. Session B reads Alice's row at that moment. Does Session B wait, or does it see something?
Words you need:
- Transaction ID (XID): a number Postgres gives each transaction that writes. It goes up by one each time.
- Row version: one tuple of a row. One logical row can have several versions on disk.
- Snapshot: the list of transactions your query treats as finished, taken when the query (or transaction) starts.
- Dead tuple: an old row version that no running transaction can see any more.
Rename Alice, then look at the hidden columns. These are real outputs from Postgres 18:
-- before
SELECT ctid, xmin, xmax, id, name FROM users WHERE id = 1;
-- ctid | xmin | xmax | id | name
-- (0,1) | 754 | 0 | 1 | Alice
BEGIN;
UPDATE users SET name = 'Alicia' WHERE id = 1; -- this is transaction 755
COMMIT;
-- after
SELECT ctid, xmin, xmax, id, name FROM users WHERE id = 1;
-- ctid | xmin | xmax | id | name
-- (0,4) | 755 | 0 | 1 | Alicia
The row got a new address: slot 1 became slot 4.
pageinspect is an extension (add-on) that comes with Postgres. With it you can see every tuple on page 0, even the ones you can no longer select. lp is the line pointer number:
CREATE EXTENSION pageinspect;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('users', 0));
lp | t_xmin | t_xmax | t_ctid
----+--------+--------+--------
1 | 754 | 755 | (0,4)
2 | 754 | 0 | (0,2)
3 | 754 | 0 | (0,3)
4 | 755 | 0 | (0,4)
Slot 1 is still there. Its xmax is 755, the transaction that replaced it, and its t_ctid points to the new version in slot 4. Every UPDATE or DELETE leaves an old version like this. Tables that change a lot collect many: order status, counters, job queues.
MVCC means multi-version concurrency control. Postgres never changes a row in place. An UPDATE writes a new version and marks the old one with its own XID in xmax. A DELETE only sets xmax.
A simple version of the visibility rule: a tuple is visible to you if
- the transaction in its
xminhad committed when your snapshot was taken, and - it was not deleted for you: no delete, a delete that rolled back, or a delete not yet committed when your snapshot was taken.
Two sessions at work:
- Slot 1 holds Alice with xmin 754 and xmax 0. Everyone sees it.
- Session A starts transaction 755 and runs the UPDATE.
- Postgres writes Alicia in slot 4 with xmin 755, and sets xmax 755 on slot 1. Both versions are on the page now.
- Session B reads before 755 commits. It still sees Alice, and nobody waits.
- Transaction 755 commits. New queries see Alicia.
- Slot 1 becomes a dead tuple once no snapshot can still need it.
This is the big win of MVCC. Readers do not block writers, and writers do not block readers. A plain SELECT never waits for an UPDATE on the same row.
You DELETE 1 million rows. What happens on disk right away?
VACUUM, bloat and the long transaction#
Words you need:
- VACUUM: the command that removes dead tuples and marks their space as free for reuse.
- Autovacuum: a background process that runs VACUUM for you when a table has enough dead tuples.
- Bloat: space in a table or index taken by dead tuples or empty gaps. Every scan still has to read it.
The orders table gets its status updated all day: pending, then paid, then shipped. Each update leaves a dead tuple. Here is a real VACUUM run after 50,000 status updates:
VACUUM (VERBOSE) orders;
tuples: 50000 removed, ... 0 are dead but not yet removable
All 50,000 dead tuples were removed, and their space can be reused for new rows. Watch for bloat when a table keeps growing although the row count stays flat, or queries on it slowly get slower.
Plain VACUUM removes dead tuples and keeps the space for new rows in the same table. It does not give the space back to the operating system, except when whole pages at the end of the table are empty. So the file stays the same size, and new rows fill the holes.
VACUUM FULL does shrink the file, but it blocks all reads and writes on the table while it runs.
The long transaction that blocks cleanup#
What do you think happens if one session opens a transaction and forgets to commit? Here is a test on Postgres 18. Session 1 opened a transaction and stayed open. Session 2 updated 20,000 orders and ran VACUUM:
- Session 1 opens a transaction and stays open.
- Session 2 updates 20,000 orders, then runs VACUUM.
- VACUUM removes 0. Session 1 might still need to see those old versions.
- Session 1 finally commits.
- The same VACUUM now removes all 20,000.
The real VACUUM output, while Session 1 was open:
tuples: 0 removed, ... 20000 are dead but not yet removable
And after Session 1 committed:
tuples: 20000 removed, ... 0 are dead but not yet removable
VACUUM cannot remove a dead tuple that an open transaction might still need to see. The Postgres docs say an open transaction stops VACUUM from removing dead rows made after it started, even when it holds no important locks.
Find the oldest open transactions:
SELECT pid, now() - xact_start AS xact_age, state, left(query, 40) AS query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start;
xact_start is when the transaction started. Real output from a test with one session left open:
pid | xact_age | state | query
-----+-----------------+---------------------+------------------------------
104 | 00:00:05.898994 | idle in transaction | SELECT count(*) FROM orders;
111 | 00:00:00 | active | SELECT pid, now() - xact_start
pid 111 is your own query, which is normal. pid 104 is the suspect: idle in transaction means it ran a query, then stopped without COMMIT. Here it is 6 seconds old. In a real problem it is minutes or hours.
To stop it from happening again, set a timeout (the default, 0, means off):
ALTER DATABASE app SET idle_in_transaction_session_timeout = '5min';
Postgres then ends any session that sits idle inside a transaction for longer than 5 minutes.
VACUUM VERBOSE says 30000 are dead but not yet removable. What do you check first?
Transaction ID wraparound#
Words you need:
- Freeze: marking an old tuple as "visible to everyone forever", so its XID is never compared again.
XIDs are 32-bit numbers, so there are about 4 billion of them. When they run out, they start again from the beginning. So Postgres compares them on a circle:
- From your XID, about 2.1 billion XIDs are behind you (older) and 2.1 billion in front (newer).
- Alice's tuple has xmin 754. It is behind you, so it is older and visible.
- Billions of transactions later, 754 is more than 2.1 billion behind the current XID.
- Now 754 lands in the front half. It looks like it comes from the future, and Alice vanishes from every query.
- The fix: VACUUM freezes the tuple first. A frozen tuple counts as older than every XID, so it never crosses.
| Seen from your XID | How many XIDs | Rows from them |
|---|---|---|
| the half behind you | about 2.1 billion (2^31) | older: visible once committed |
| the half in front of you | about 2.1 billion (2^31) | newer: in the future, not visible |
If a tuple's xmin falls more than 2.1 billion behind, it crosses into the "in front" half and vanishes from every query. VACUUM prevents this by freezing old tuples: a frozen tuple counts as older than every XID, so wraparound cannot touch it.
When a table's oldest unfrozen tuple is more than 200 million transactions old (autovacuum_freeze_max_age), Postgres forces an autovacuum on it. This runs even if autovacuum is turned off.
Watch it per database. datfrozenxid is the oldest XID in that database that is not frozen yet. age() says how many transactions ago that XID was:
SELECT datname, age(datfrozenxid),
2^31 - age(datfrozenxid) AS xids_left
FROM pg_database
ORDER BY 2 DESC;
Real output from a fresh test database:
datname | age | xids_left
-----------+-----+------------
postgres | 12 | 2147483636
template1 | 12 | 2147483636
template0 | 12 | 2147483636
On a healthy system age stays around 200 million or lower, because autovacuum freezes a table once it passes that age. If xids_left keeps dropping, look for the same causes as bloat:
- an old open transaction
- autovacuum that is too slow, or turned off (then only the forced runs happen)
Why does freezing stop wraparound?
WAL: how a COMMIT survives a crash#
A customer places an order:
INSERT INTO orders (user_id, status, total_cents, currency, created_at)
VALUES (7, 'pending', 4500, 'USD', now());
COMMIT;
Postgres says COMMIT. One second later the server loses power. The changed data page was still only in memory. Is the order gone?
Words you need:
- WAL (write-ahead log): an append-only log of every change, kept in the
pg_walfolder. - WAL buffers: a small area in shared memory where WAL records wait before they are flushed to disk.
- Dirty page: a page in shared buffers that changed but is not written to the data file yet.
- LSN (log sequence number): a position in the WAL, like
0/17F64B8. You get the current one withSELECT pg_current_wal_lsn();. - Checkpoint: a moment when all dirty pages are written to the data files.
The rule of the WAL: a change may reach the data file only after the WAL record that describes it is safely on disk. At COMMIT, only the WAL has to be flushed. The data pages can wait.
- The backend changes the page in shared buffers. The page is now dirty.
- It writes a WAL record of the change into the WAL buffers.
- On COMMIT it flushes the WAL up to that record to disk.
- Only then does the client get COMMIT back. The data page is still dirty, only in memory.
- Later the background writer or the checkpointer writes the page to its data file.
- After a crash, Postgres replays the WAL from the last checkpoint and rebuilds the page.
So the order is not gone. Crash recovery replays its WAL record. This also explains why a crashed database takes a while to come back, and what you risk with synchronous_commit = off (next section).
Why not write the data page at COMMIT? One transaction can touch pages all over many files. The WAL is written in order, in one stream, so flushing it is much cheaper.
The same WAL also feeds replicas (copies of the database on other servers) and backups.
synchronous_commit#
The default is synchronous_commit = on: COMMIT waits for the WAL flush, as above.
With off, COMMIT returns before the flush. A crash can lose the last few commits. The database still stays consistent: no half-written or broken data, as if those commits had rolled back. Use it only for data you can afford to lose, and set it for that transaction only with SET LOCAL synchronous_commit = off.
Checkpoints and pg_wal#
A checkpoint writes all dirty pages to the data files. After it, crash recovery only has to start from that checkpoint. A checkpoint runs every 5 minutes by default (checkpoint_timeout), or sooner when a lot of WAL piles up.
Even when pg_wal fills the disk, never delete files in it. Postgres needs them for crash recovery.
COMMIT returned, then the server crashed before the checkpoint. With synchronous_commit = on, is the commit safe?
Indexes and column order#
The shop's orders table now has 2 million rows (test data):
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL,
status text NOT NULL, -- pending, paid, shipped, cancelled
total_cents bigint NOT NULL,
currency text,
created_at timestamptz NOT NULL
);
The app runs this query all day:
SELECT id, total_cents FROM orders
WHERE user_id = 7 AND created_at > '2026-03-01'
ORDER BY created_at;
Which index is better: (user_id, created_at) or (created_at, user_id)? Column order matters any time one index covers two or more columns, like one user's orders by date.
Words you need:
- B-tree: the default index type. It keeps keys sorted, so it handles
=,<,>, ranges and ORDER BY. - Composite index: one index on several columns, sorted by the first column, then the second, and so on.
- Equality condition: a filter like
user_id = 7. - Range condition: a filter like
created_at > '2026-03-01'.
Think of (user_id, created_at) as a phone book sorted by user, then by date. Postgres jumps to user 7, then to March, and reads forward. The rows come out already sorted by created_at, so no sort step is needed.
With (created_at, user_id) the book is sorted by date first. Postgres jumps to March 1 and must walk every entry after it, for every user, checking user_id on each one.
Here are the same six index entries, sorted both ways. The query wants user 7 after March 1:
| Entry | Index (user_id, created_at) | Index (created_at, user_id) |
|---|---|---|
| 1 | 5, Mar 02 | Feb 10, 7 |
| 2 | 7, Feb 10 | Mar 02, 5 (read, skip) |
| 3 | 7, Mar 05 (match) | Mar 03, 9 (read, skip) |
| 4 | 7, Apr 01 (match) | Mar 04, 12 (read, skip) |
| 5 | 9, Mar 03 | Mar 05, 7 (match) |
| 6 | 12, Mar 04 | Apr 01, 7 (match) |
On the left, the two matches sit next to each other. Postgres jumps to them, reads them and stops. On the right, it reads every entry from March on and throws most away. With millions of users, that is millions of wasted reads.
So put equality columns first, then the range column. You may see the advice "put the most selective column first" (the column that matches the fewest rows). For a mix of equality and range filters, the type of condition matters more.
Postgres 18 skip scan#
Postgres 18 can sometimes use (status, created_at) for a filter on created_at alone. When status has only a few values, it does one small search per value. It is only fast when the first column has few values, so keep the rule above.
Other index types#
| Type | Good for | Example | Watch out |
|---|---|---|---|
| B-tree | =, ranges, sorting | WHERE user_id = 7 | the default, use it unless you have a reason |
| GIN | values inside a value: JSONB, arrays, full-text | WHERE tags @> ARRAY['vip'] (@> means contains) | slower writes: one row adds many index entries |
| BRIN | huge tables where rows are stored in order, like time | WHERE created_at > now() - interval '1 day' | tiny (min and max per group of pages), but useless if rows on disk are not in that order |
The query is WHERE status = 'paid' AND created_at > '2026-10-01'. Which index fits best?
Reading EXPLAIN#
How do you know the index is used? Read the plan before you add an index and again after, and every time a query is slow.
Words you need:
- Planner: the part of Postgres that decides how to run a query, for example which index to use.
- EXPLAIN: shows the plan the planner picked, with cost estimates. It does not run the query.
- EXPLAIN ANALYZE: runs the query for real and adds the real times and row counts.
- ANALYZE (on its own): collects statistics, a summary of the values in a table. The planner uses them to guess row counts.
- Buffers: pages read.
hitcame from shared buffers,readcame from disk. Postgres 18 shows this by default with EXPLAIN ANALYZE.
Run the query from the last chapter with no index on it. Real output, shortened:
EXPLAIN ANALYZE SELECT id, total_cents FROM orders
WHERE user_id = 7 AND created_at > '2026-03-01' ORDER BY created_at;
Parallel Seq Scan on orders (... rows=1 ...) (actual ... rows=0.33 loops=3)
Filter: ((created_at > '2026-03-01 ...') AND (user_id = 7))
Rows Removed by Filter: 666666
Execution Time: 36.641 ms
Then create (user_id, created_at) and run it again:
Index Scan using orders_user_created_idx on orders (... rows=3 ...) (actual ... rows=1.00 loops=1)
Index Cond: ((user_id = 7) AND (created_at > '2026-03-01 ...'))
Buffers: shared hit=4 read=3
Execution Time: 0.301 ms
loops=3: the scan ran 3 times, once in each process (the main process and 2 parallel workers).rows=0.33: the average per run, so 0.33 × 3 = 1 row.Rows Removed by Filter: 666666: each process threw away 666,666 rows to find that one.Buffers: shared hit=4 read=3: with the index, Postgres touched 7 pages (4 + 3).
| You see | It means |
|---|---|
Seq Scan with a big Rows Removed by Filter | no useful index for this filter |
Index Scan / Index Only Scan | the index is used (index only: reads only the index; Heap Fetches shows rows it still checked in the table's heap) |
Bitmap Heap Scan | many matches: the index finds pages, then reads them in order |
estimated rows far from actual rows | old statistics: run ANALYZE orders |
Sort Method: external merge Disk: | the sort spilled past work_mem (memory chapter) |
A Seq Scan is not always bad. On a tiny table, or when the query needs most rows, it is the fastest plan.
Common reasons the index is ignored:
- A function on the column.
WHERE lower(email) = '...'cannot use an index onemail. Create an index onlower(email)instead:CREATE INDEX users_lower_email_idx ON users (lower(email));. On the test database, the plan changed from Seq Scan toIndex Scan using users_lower_email_idx. - Old statistics. Run
ANALYZE.
EXPLAIN ANALYZE runs your write#
EXPLAIN ANALYZE really executes the statement. On an UPDATE or DELETE, it changes your data. The docs say to wrap it like this:
BEGIN;
EXPLAIN ANALYZE UPDATE orders SET status = 'cancelled' WHERE id = 42;
ROLLBACK; -- the update is undone, you keep the plan
You want the real plan of a DELETE on production data. What do you run?
Locks and the lock queue#
Guess first: an ALTER TABLE ... ADD COLUMN without a default only changes metadata (the table's description), not the rows. It takes milliseconds. Can it still take your app down?
Here is a test on Postgres 18 with three sessions:
- Session 1 runs a slow report:
BEGIN; SELECT count(*) FROM orders; ...and keeps the transaction open. - Session 2 runs
ALTER TABLE orders ADD COLUMN note text;. - Session 3 runs a tiny
SELECT id FROM orders WHERE id = 1;.
pg_stat_activity then showed the following. The report was faked with pg_sleep, a function that just waits, so its wait shows as PgSleep:
wait_event_type | wait_event | query
-----------------+------------+------------------------------------------
Timeout | PgSleep | BEGIN; SELECT count(*) FROM orders; ...
Lock | relation | ALTER TABLE orders ADD COLUMN note text;
Lock | relation | SELECT id FROM orders WHERE id = 1;
The tiny SELECT is stuck in line behind the ALTER, which is itself waiting for the report. Locks matter for every migration (a script that changes the schema) on a busy table.
Words you need:
- Table lock: a lock on the whole table. Each command takes a lock mode, and some modes conflict.
- Lock queue: the line of sessions waiting for a lock. A new request waits if it conflicts with anyone already in the line.
- Constraint: a rule the database checks on every row, like NOT NULL.
In the output above, relation means a table.
Postgres has eight table lock modes. These five cover most cases, from weakest to strongest:
| Lock mode | Taken by | Blocks |
|---|---|---|
| ACCESS SHARE | SELECT | only ACCESS EXCLUSIVE |
| ROW EXCLUSIVE | INSERT, UPDATE, DELETE | SHARE and stronger, like CREATE INDEX (without CONCURRENTLY) |
| SHARE UPDATE EXCLUSIVE | VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY, VALIDATE CONSTRAINT | itself and stronger modes, not reads or writes |
| SHARE | CREATE INDEX (without CONCURRENTLY) | writes (INSERT, UPDATE, DELETE), not reads |
| ACCESS EXCLUSIVE | most ALTER TABLE, DROP, TRUNCATE, VACUUM FULL | everything, even SELECT |
A lock is held until the end of the transaction, not the end of the statement.
The MVCC chapter said a plain SELECT never waits for an UPDATE. That is about row versions, and it still holds. Table locks are a separate layer: a SELECT does wait when an ACCESS EXCLUSIVE lock is held or queued on the table.
Why the SELECT waited#
The ALTER needs ACCESS EXCLUSIVE, which conflicts with the report's ACCESS SHARE, so it waits. Postgres grants conflicting requests in the order they arrive. The new SELECT conflicts with the waiting ALTER, so it lines up behind it. Every query on orders now waits until the report finishes.
- A long report holds ACCESS SHARE on orders.
- A migration asks for ACCESS EXCLUSIVE and waits for the report.
- A normal SELECT arrives and lines up behind the migration.
- More app queries line up. The connection pool fills up.
- The report ends. The migration runs in milliseconds.
- The waiting queries run, but the app was frozen the whole time.
The fix is lock_timeout, in the next chapter.
A report holds orders, and your ALTER TABLE waits for its lock. What happens to a new, tiny SELECT on orders?
Safe migrations#
Every migration on a busy table follows two rules: never wait long for a lock, and never hold a strong lock while scanning the table. Use them for every schema change on a table your app reads or writes all the time. For the app side of a change (expand and contract, deploy order), see Ship Without Fear.
Step zero: set lock_timeout#
Set it at the top of every migration session:
SET lock_timeout = '5s';
From the same test as the lock queue, with a report holding the table:
ERROR: canceling statement due to lock timeout
The migration gave up after 5 seconds, so app queries only waited 5 seconds behind it. Retry later.
- The same long report holds orders.
- The migration runs with lock_timeout = 5s and waits for its lock.
- App queries line up behind it, as before.
- After 5 seconds the migration gives up with the lock timeout error.
- The app queries run. They waited 5 seconds, not the whole report.
Set it in the migration session. In postgresql.conf it would apply to every session.
Run migrations on a direct connection to Postgres, not through PgBouncer in transaction mode. In transaction mode, a session SET like lock_timeout can be lost (first chapter).
Adding a column#
ADD COLUMN with no default only changes metadata (the table's description), not the rows. Since Postgres 11, the same is true with a fixed default like 'web'. Postgres does not rewrite the table:
ALTER TABLE orders ADD COLUMN source text DEFAULT 'web';
It still takes ACCESS EXCLUSIVE for a moment, so lock_timeout still matters.
A volatile default is different. Volatile means the function can return a new value on every call, like clock_timestamp(). Postgres then has to rewrite the whole table. Avoid it on big tables:
ALTER TABLE orders ADD COLUMN checked_at timestamptz DEFAULT clock_timestamp(); -- rewrites every row
Adding an index#
A normal CREATE INDEX takes a SHARE lock: reads work, but every INSERT, UPDATE and DELETE waits until the build is done. Use the concurrent version:
CREATE INDEX CONCURRENTLY orders_user_created_idx ON orders (user_id, created_at);
It takes longer: two scans of the table, plus a wait for running transactions to finish. Watch out for two traps:
- It cannot run inside a transaction block. Real error:
CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Many migration tools wrap each migration in a transaction, so check how yours turns that off. - If it fails, it leaves an INVALID index. The planner ignores it, but every write still updates it. Find them with
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;. Then drop it withDROP INDEX CONCURRENTLYand try again, or useREINDEX INDEX CONCURRENTLY.
Making a column NOT NULL#
ALTER COLUMN currency SET NOT NULL scans the whole table while holding ACCESS EXCLUSIVE. On a big table that blocks everything. Postgres 18 lets you split it into 4 steps. One step is a backfill: filling old rows with a value.
- Step 1: set a default. Metadata only, so the lock is short.
- Step 2: backfill old rows in small batches. Each batch is its own short transaction.
- App writes keep going between the batches.
- Step 3: add the constraint without checking old rows. A short lock, no scan. New writes are checked from now on.
- Step 4: check the old rows. It holds SHARE UPDATE EXCLUSIVE, so app reads and writes keep going.
-- 1. Inserts that leave out currency get 'USD' (metadata only)
ALTER TABLE orders ALTER COLUMN currency SET DEFAULT 'USD';
-- 2. Backfill old rows, one id range per batch.
UPDATE orders SET currency = 'USD'
WHERE id BETWEEN 1 AND 10000 AND currency IS NULL;
-- next: 10001 to 20000, and so on, up to max(id)
-- 3. Add the constraint without checking old rows (short lock, no scan)
ALTER TABLE orders ADD CONSTRAINT orders_currency_not_null
NOT NULL currency NOT VALID;
-- 4. Check old rows
ALTER TABLE orders VALIDATE CONSTRAINT orders_currency_not_null;
A few notes on these steps:
- The default only helps when an INSERT leaves
currencyout. If your app sends NULL on purpose, it still writes NULL. Fix the app first. - The id ranges use the primary key, so each batch is quick.
- Commit each batch on its own: one huge transaction would block VACUUM (VACUUM chapter).
- Do the backfill before step 3. A NOT VALID constraint still checks every new insert and update. In a test, an UPDATE that only changed
statuson an old row with a NULLcurrencyfailed withviolates not-null constraint. - Step 4 took SHARE UPDATE EXCLUSIVE in a test on Postgres 18 (Postgres shows it as
ShareUpdateExclusiveLock), so app reads and writes keep going.
Your migration runs CREATE INDEX CONCURRENTLY and fails halfway. What is left behind?
Recap#
| Your app does | What Postgres does inside | What you can now do |
|---|---|---|
| opens a connection | starts one backend process | use PgBouncer transaction mode, and know what breaks in it |
| runs a big sort | gives each sort or hash its own work_mem | do the math, and raise it with SET LOCAL for one query |
| reads one row | reads the whole 8 KB page, finds the tuple by CTID | read a CTID |
| updates a row | writes a new version, leaves a dead tuple | explain MVCC |
| leaves a transaction open | VACUUM can't remove dead tuples | spot "dead but not yet removable" in VACUUM VERBOSE, find the open transaction in pg_stat_activity, set idle_in_transaction_session_timeout |
| runs for years | XIDs wrap around | watch age(datfrozenxid) against the 2^31 limit |
| commits | flushes the WAL first | explain why a commit survives a crash |
| filters by user and date | walks a B-tree | order an index: equality columns first, then the range |
| searches inside JSONB or arrays, or a huge time-ordered table | uses a GIN or BRIN index | pick GIN for values inside values, BRIN for huge tables stored in time order |
| gets slow | the planner picks a plan | read EXPLAIN, and wrap EXPLAIN ANALYZE of a write in BEGIN and ROLLBACK |
| migrates a busy table | queues locks in arrival order | use lock_timeout, CONCURRENTLY, and NOT VALID plus VALIDATE |
Next time a query is slow, run it with EXPLAIN ANALYZE first, then decide on the index.
Read next: System Design Basics puts this database inside a whole app, with caches, replicas and queues.