A bank transfer changes two balances, and a customer must never see one change without the other. A transaction is how a database makes a group of statements behave as one step.
The PostgreSQL tutorial describes a transaction as a bundle of steps into a single all-or-nothing operation. The intermediate states are not visible to other concurrent transactions, and if a failure stops the transaction from completing, none of its steps affect the database. A transaction ends in one of two ways. COMMIT makes all its changes permanent, and ROLLBACK discards them all.
Transaction guarantees are summarised by the acronym ACID.
Letter
Property
What it promises
A
Atomicity
All the steps happen or none of them do
C
Consistency
A transaction takes the database from one valid state to another, as defined by its rules (constraints)
I
Isolation
Concurrent transactions do not see each other's unfinished work
D
Durability
Once the database has acknowledged a commit, the change survives a crash
PostgreSQL treats every statement as running inside a transaction. If you do not write BEGIN, each statement gets an implicit BEGIN and, when it succeeds, a COMMIT: this is autocommit. Two separate UPDATE statements sent without BEGIN are therefore two transactions, and a crash between them leaves the first one applied and the second never run: for a transfer, money gone from one account only.
Two sessions on one server
Some lessons in this chapter need two connections talking to one server at the same time, with the script deciding when each statement is sent. The harness below starts a local PostgreSQL 18.6 server with the embedded-postgres package and opens real connections with the pg package. Each call of run sends one statement and prints the session name, the statement, and its result, or its SQLSTATE error code and message. A statement that must wait is started without await, so the other session can carry on.
A script that uses it starts a server on a port, opens sessions A and B, and always stops the server in a finally block. Later chapters call this file "the two-session harness". The payments ledger used here has accounts with a balance that a CHECK constraint keeps from going negative.
ts
import { startServer, session } from'./sessions.ts'const port = 56323const server = await startServer(port, './pgdata-tx1')
try {
const a = await session(port, 'A')
const b = await session(port, 'B')
await a.run(`CREATETABLE accounts (
account_id int PRIMARY KEY, holder text NOT NULL,
balance numeric(12,2) NOT NULL CHECK (balance >= 0))`)
await a.run(`INSERT INTO accounts (account_id, holder, balance)
VALUES (1, 'Asha', 1000), (2, 'Ravi', 500)`)
The printed statements have their whitespace collapsed to a single line, and parameter values are printed after the statement. Results are the rows as JSON. The script is one file, tx1.ts. This page shows its first lines, and each later page shows the next lines of the same file, with the output they produced. A blocked statement is started without await and awaited later; the waiting example further down shows it.
Autocommit and a transfer
The first run shows autocommit. txid_current() returns the number of the current transaction. Outside BEGIN every call gets a new transaction number, and inside BEGIN the number stays the same until COMMIT.
text
A: SELECT txid_current() AS xid -> SELECT [{"xid":"755"}]
A: SELECT txid_current() AS xid -> SELECT [{"xid":"756"}]
text
A: BEGIN -> BEGIN []
A: SELECT txid_current() AS xid -> SELECT [{"xid":"757"}]
A: SELECT txid_current() AS xid -> SELECT [{"xid":"757"}]
A: COMMIT -> COMMIT []
Transactions 755 and 756 are the two autocommitted statements, and 757 covers both statements inside BEGIN. Next comes the transfer: session A moves 100 from Asha to Ravi inside a transaction, reads the balances itself, and session B reads them before and after A commits. The script is below, and its output follows.
ts
console.log('-- a transfer, with another session reading')
const bal = 'SELECT holder, balance FROM accounts ORDER BY account_id'await a.run('BEGIN')
await a.run(`UPDATE accounts SET balance = balance - 100WHERE account_id = 1`)
await a.run(`UPDATE accounts SET balance = balance + 100WHERE account_id = 2`)
await a.run(bal)
await b.run(bal)
await a.run('COMMIT')
await b.run(bal)
console.log('-- the same transfer, rolled back')
await a.run('BEGIN')
await a.run(`UPDATE accounts SET balance = balance - 100WHERE account_id = 1`)
await a.run('ROLLBACK')
await b.run(bal)
text
A: BEGIN -> BEGIN []
A: UPDATE accounts SET balance = balance - 100 WHERE account_id = 1 ->
UPDATE []
A: UPDATE accounts SET balance = balance + 100 WHERE account_id = 2 ->
UPDATE []
A: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"900.00"},{"holder":"Ravi",
"balance":"600.00"}]
B: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"1000.00"},{"holder":"Ravi",
"balance":"500.00"}]
A: COMMIT -> COMMIT []
B: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"900.00"},{"holder":"Ravi",
"balance":"600.00"}]
A sees its own uncommitted changes, 900 and 600. B, reading in the middle, still sees 1000 and 500, as if nothing had happened. After COMMIT, B sees both changes at once. There was no moment when B could see the debit without the credit. That is atomicity and isolation working together.
Rolling back
The same transfer with ROLLBACK instead of COMMIT leaves no trace.
text
A: BEGIN -> BEGIN []
A: UPDATE accounts SET balance = balance - 100 WHERE account_id = 1 ->
UPDATE []
A: ROLLBACK -> ROLLBACK []
B: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"900.00"},{"holder":"Ravi",
"balance":"600.00"}]
A debited Asha, then rolled back. B reads 900 and 600, the balances that the earlier committed transfer left. Rolling back is cheap because the update never overwrote the old row. It wrote a new version, which no other session could see, and after the rollback no query sees it either. Vacuum removes it later.
Keep transactions short. Between BEGIN and COMMIT the transaction holds on to the rows it has changed, and other sessions that want them must wait. Do not leave a transaction open while waiting for a person, an HTTP call, or a slow computation. The final lesson of this chapter returns to this.
A statement that has to wait
Waiting is what holding a row means. In the script below, A updates the row for Asha and leaves the transaction open. B sends an update to the same row without await, and the script checks after 500 ms whether B has finished. Then A commits.
ts
console.log('-- a statement that has to wait')
await a.run('BEGIN')
await a.run(`UPDATE accounts SET balance = balance - 1WHERE account_id = 1`)
const waiting = b.run(`UPDATE accounts SET balance = balance + 1WHERE account_id = 1`)
const early = await Promise.race([
waiting.then(() => 'finished'),
new Promise((r) => setTimeout(() => r('still waiting'), 500))])
console.log('B after 500 ms:', early)
await a.run('COMMIT')
await waiting
text
A: BEGIN -> BEGIN []
A: UPDATE accounts SET balance = balance - 1 WHERE account_id = 1 ->
UPDATE []
B after 500 ms: still waiting
A: COMMIT -> COMMIT []
B: UPDATE accounts SET balance = balance + 1 WHERE account_id = 1 ->
UPDATE []
The statement from B was sent while A held the row, and it did not return until A had committed. B did not fail: it waited for the other transaction to end and then applied its change on top of the committed row. Later chapters print interleavings like this one: what each session did, in the order it happened, and which statement was still waiting.
What a rollback does and does not undo
A rollback covers more than rows. In this run a CREATE TABLE inside the transaction is undone too: after the rollback, the table is gone and a query on it fails with 42P01. A migration that fails halfway therefore does not have to leave half a schema. A few commands refuse to run inside a transaction block at all, such as VACUUM and CREATE INDEX CONCURRENTLY from the indexes chapter.
ts
console.log('-- DDL is transactional too')
await a.run('BEGIN')
await a.run('CREATE TABLE scratch (id int)')
await a.run('INSERT INTO scratch (id) VALUES (1)')
await a.run('ROLLBACK')
await a.run('SELECT count(*) FROM scratch')
text
A: BEGIN -> BEGIN []
A: CREATE TABLE scratch (id int) -> CREATE []
A: INSERT INTO scratch (id) VALUES (1) -> INSERT []
A: ROLLBACK -> ROLLBACK []
A: SELECT count(*) FROM scratch -> ERROR 42P01 relation "scratch" does
not exist
Sequence values are the exception. The documentation says that a value obtained from a sequence is not given back when the transaction that took it aborts, so that concurrent transactions do not block each other on the sequence. An identity column uses one. The script inserts a receipt, rolls back an insert, and inserts another.
ts
console.log('-- a rollback does not give back sequence numbers')
await a.run(`CREATETABLE receipts (
receipt_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
note text NOT NULL)`)
await a.run("INSERT INTO receipts (note) VALUES ('first')")
await a.run('BEGIN')
await a.run("INSERT INTO receipts (note) VALUES ('rolled back')")
await a.run('ROLLBACK')
await a.run("INSERT INTO receipts (note) VALUES ('second')")
await a.run(`SELECT receipt_id, note FROM receipts
ORDER BY receipt_id`)
text
A: CREATE TABLE receipts ( receipt_id int GENERATED ALWAYS AS IDENTITY
PRIMARY KEY, note text NOT NULL) -> CREATE []
A: INSERT INTO receipts (note) VALUES ('first') -> INSERT []
A: BEGIN -> BEGIN []
A: INSERT INTO receipts (note) VALUES ('rolled back') -> INSERT []
A: ROLLBACK -> ROLLBACK []
A: INSERT INTO receipts (note) VALUES ('second') -> INSERT []
A: SELECT receipt_id, note FROM receipts ORDER BY receipt_id -> SELECT
[{"receipt_id":1,"note":"first"},{"receipt_id":3,"note":"second"}]
The second receipt has number 3: number 2 went to the insert that was rolled back, and nothing reuses it. Gaps are normal, and the documentation says plainly that sequences cannot give gapless numbers. If a rule such as invoice numbers without gaps matters, the numbers have to be assigned some other way, inside the transaction that uses them.
Check yourself
Why did session B still read 1000 and 500 while A had updated both rows and not yet committed?
A's changes are visible only to A until it commits. Isolation keeps unfinished work out of other sessions' reads.
A rolled-back insert took receipt number 2 from an identity column. What number does the next successful insert get, and why?
3. A sequence value is not given back when its transaction aborts, so rolled-back inserts leave gaps. Numbers that must have no gaps cannot come from a sequence.
B updates a row that A has changed and not yet committed. What does B see, and how can a script show it?
B waits until A commits or rolls back. Start the statement of B without await, check after a delay that it has not finished, then let A commit and await it.
Part 2 · Atomicity in practice
When a statement fails
Atomicity means that a failed transaction leaves no partial effects. The SQL essentials chapter showed the PostgreSQL half of this: after any error inside a transaction block, the transaction is aborted, and the server answers every later statement with 25P02 (in_failed_sql_transaction) until the block ends. Only ROLLBACK (or COMMIT, which then does a rollback) ends it, and ROLLBACK TO a savepoint, shown below, gets it out of the failed state.
The rule protects you. A transaction with a failed step in the middle is no longer a transaction you meant to run, and carrying on would apply some of its steps and not others. It also surprises code that catches an error and tries the next statement on the same connection. The next statement fails too, with 25P02 instead of the original error, which is easy to miss in the logs.
The ledger from the previous lesson has CHECK (balance >= 0). The script runs a transfer of 100 that goes wrong: the first update is fine, the second takes 5,000 from Asha, who has 900 after the debit, and a third update, the credit to Ravi, follows the failure. Then the account balances are read.
ts
console.log('-- an error inside a transaction aborts it')
await a.run('BEGIN')
await a.run(`UPDATE accounts SET balance = balance - 100WHERE account_id = 1`)
await a.run(`UPDATE accounts SET balance = balance - 5000WHERE account_id = 1`)
await a.run(`UPDATE accounts SET balance = balance + 100WHERE account_id = 2`)
await a.run('COMMIT')
await a.run(bal)
text
A: BEGIN -> BEGIN []
A: UPDATE accounts SET balance = balance - 100 WHERE account_id = 1 ->
UPDATE []
A: UPDATE accounts SET balance = balance - 5000 WHERE account_id = 1 ->
ERROR 23514 new row for relation "accounts" violates check
constraint "accounts_balance_check"
A: UPDATE accounts SET balance = balance + 100 WHERE account_id = 2 ->
ERROR 25P02 current transaction is aborted, commands ignored until
end of transaction block
A: COMMIT -> ROLLBACK []
A: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"1000.00"},{"holder":"Ravi",
"balance":"500.00"}]
The error code is 23514, a check violation, for the 5,000 update. The credit gets 25P02. COMMIT returns the command tag ROLLBACK: the server did not commit anything. After it both balances are as they were, 1000 and 500, so the first, successful debit was also undone. Atomicity covers the statements that worked as well as the one that failed.
Savepoints
Sometimes a failed step should not cancel the whole transaction. A savepoint marks a point inside a transaction. ROLLBACK TO SAVEPOINT discards everything done since that point, but keeps the earlier changes and keeps the transaction open. The tutorial notes that the savepoint stays defined, so you can roll back to it again.
ts
console.log('-- a savepoint undoes only the failed step')
await a.run('BEGIN')
await a.run(`UPDATE accounts SET balance = balance - 100WHERE account_id = 1`)
await a.run('SAVEPOINT before_fee')
await a.run(`UPDATE accounts SET balance = balance - 5000WHERE account_id = 1`)
await a.run('ROLLBACK TO SAVEPOINT before_fee')
await a.run(`UPDATE accounts SET balance = balance + 100WHERE account_id = 2`)
await a.run('COMMIT')
await a.run(bal)
text
A: BEGIN -> BEGIN []
A: UPDATE accounts SET balance = balance - 100 WHERE account_id = 1 ->
UPDATE []
A: SAVEPOINT before_fee -> SAVEPOINT []
A: UPDATE accounts SET balance = balance - 5000 WHERE account_id = 1 ->
ERROR 23514 new row for relation "accounts" violates check
constraint "accounts_balance_check"
A: ROLLBACK TO SAVEPOINT before_fee -> ROLLBACK []
A: UPDATE accounts SET balance = balance + 100 WHERE account_id = 2 ->
UPDATE []
A: COMMIT -> COMMIT []
A: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"900.00"},{"holder":"Ravi",
"balance":"600.00"}]
The 5,000 update fails with 23514 as before. This time the session issues ROLLBACK TO SAVEPOINT before_fee, which clears the failed state, and the transaction carries on: the credit to Ravi runs and COMMIT really commits. The balances end at 900 and 600: the first debit and the credit survived, and only the step after the savepoint was undone.
Each savepoint starts a sub-transaction that the server has to keep track of, so do not open one for every row of a long loop. Use savepoints where a recoverable failure is expected, for example an insert that may violate a unique constraint, and not as a habit.
The session as a state machine
The scene follows the session through both scripts. It starts idle, BEGIN puts it in a transaction, and an error moves it to the failed state. In that state only COMMIT or ROLLBACK leads back to idle, and every other statement stays in the same state with 25P02. In the second run, the error again moves the session to the failed state, and ROLLBACK TO brings it back to the transaction state, with the earlier work intact.
Animated sceneA session moving through a failed transaction0:22
Watch for the session refusing every statement after one error, until it rolls back
Read it as steps
Watch for the session refusing every statement after one error, until it rolls back.
Two details of the scene match the runs. After the error, the session cannot execute even a correct statement, such as the credit to Ravi. And COMMIT in the failed state is answered with ROLLBACK, so code that checks only whether COMMIT raised an error would think a failed transaction had committed. Check the command tag, or let the driver's error from the first failing statement propagate.
Term
Meaning
Aborted transaction
A transaction block after an error; it refuses statements until it ends
25P02
SQLSTATE returned for statements sent in an aborted transaction
Savepoint
A named point inside a transaction that you can roll back to
ROLLBACK TO
Discards work since a savepoint and keeps the transaction open
Check yourself
After a failed UPDATE in a transaction block, the next SELECT returns 25P02. Why?
The transaction is aborted. The server ignores commands until the block ends with ROLLBACK or COMMIT.
The run issued COMMIT after the failure and got the command tag ROLLBACK. What state were the balances in?
Unchanged, 1000 and 500. The successful first debit was undone too, because the whole transaction was rolled back.
How does ROLLBACK TO SAVEPOINT differ from ROLLBACK?
It discards only the work since the savepoint, clears the failed state, and keeps the transaction open with the earlier changes.
Part 3 · Consistency
Whose job is consistency
Consistency says that a transaction takes the database from one valid state to another. Valid means whatever your rules say: a balance is never negative, every ledger entry belongs to a real account, the debits of a transfer equal its credits. The database cannot know what valid means unless you tell it, so consistency is shared between two parties.
The database's half is the rules you declare as constraints: NOT NULL, CHECK, UNIQUE, primary keys and foreign keys. It enforces them for every statement from every application, and it refuses a change that breaks one. The application's half is everything that cannot be declared, and the application has to get it right inside its transactions.
By default a constraint is checked immediately, no later than the end of the statement. That is too early for some valid operations. A transfer written as two inserts is unbalanced after the first one. A pair of rows that reference each other cannot both exist before the other does. For these cases PostgreSQL lets a foreign key, a unique or primary key constraint, an exclusion constraint or a constraint trigger be deferrable: marked DEFERRABLE INITIALLY DEFERRED, it is checked when the transaction commits, not after each statement. A constraint declared DEFERRABLE INITIALLY IMMEDIATE can be switched inside one transaction with SET CONSTRAINTS ALL DEFERRED. SET CONSTRAINTS is not run here. The transaction may pass through an invalid state, as long as the state at COMMIT is valid. NOT NULL and CHECK constraints cannot be deferred at all, which is why the balance rule below needs a trigger.
The ledger below follows double-entry bookkeeping. A transfer is a set of entries in an entries table, and the entries of one transfer must sum to zero. A plain CHECK cannot express that, because it sees one row at a time. A constraint trigger, a trigger that can be deferred, can: it runs a function after each inserted row, and the documentation says that it fires either at the end of the statement or, if deferred, at the end of the transaction. The function raises an exception, here with SQLSTATE 23514, when the entries do not balance.
A deferred balance check
The tables and the trigger. Account references are deferrable too, which the next page uses.
ts
await a.run(`CREATETABLE accounts (
account_id int PRIMARY KEY, holder text NOT NULL)`)
await a.run(`CREATETABLE entries (
entry_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
transfer_id int NOT NULL,
account_id int NOT NULL REFERENCES accounts (account_id)
DEFERRABLE INITIALLY DEFERRED,
amount numeric(12,2) NOT NULL)`)
await a.run(`CREATE FUNCTION check_balanced() RETURNS trigger
LANGUAGE plpgsql AS $$ BEGIN
IF (SELECT sum(amount) FROM entries
WHERE transfer_id = NEW.transfer_id) <> 0 THEN
RAISE EXCEPTION 'transfer % does not balance', NEW.transfer_id
USING ERRCODE = '23514';
END IF;
RETURN NULL; END $$`)
await a.run(`CREATE CONSTRAINT TRIGGER entries_balanced
AFTER INSERT ON entries DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION check_balanced()`)
await a.run(`INSERT INTO accounts (account_id, holder)
VALUES (1, 'Asha'), (2, 'Ravi')`)
const ins = `INSERT INTO entries (transfer_id, account_id, amount)
VALUES ($1, $2, $3)`
The trigger fires once for each inserted entry, at commit, and each firing looks at the sum of that transfer. The first run inserts a debit and then a credit. Between the two inserts the sum is not zero, and nothing complains.
text
A: BEGIN -> BEGIN []
A: INSERT INTO entries (transfer_id, account_id, amount) VALUES ($1, $2,
$3) [1,1,-100] -> INSERT []
A: SELECT sum(amount) AS so_far FROM entries -> SELECT
[{"so_far":"-100.00"}]
A: INSERT INTO entries (transfer_id, account_id, amount) VALUES ($1, $2,
$3) [1,2,100] -> INSERT []
A: COMMIT -> COMMIT []
so_far is -100.00 while the transfer is half written, which would have broken an immediate check. At COMMIT the sum is 0 and the commit succeeds. Now only one side of a transfer.
text
A: BEGIN -> BEGIN []
A: INSERT INTO entries (transfer_id, account_id, amount) VALUES ($1, $2,
$3) [2,1,-50] -> INSERT []
A: COMMIT -> ERROR 23514 transfer 2 does not balance
A: SELECT count(*) AS entries FROM entries -> SELECT [{"entries":"2"}]
COMMIT fails with 23514 and the message "transfer 2 does not balance". The transaction is rolled back, and the count shows two entries, the two from transfer 1. The check ran at the last moment, after the application had finished, so the database refused a transfer that the application forgot to complete.
Deferred references
A deferred foreign key lets the transaction create the rows in any order. The third run inserts the entries for account 3 first, and creates account 3 afterwards, in the same transaction.
ts
console.log('-- an entry before its account, in one transaction')
await a.run('BEGIN')
await a.run(ins, [3, 3, -10])
await a.run(ins, [3, 1, 10])
await a.run(`INSERT INTO accounts (account_id, holder)
VALUES (3, 'Meera')`)
await a.run('COMMIT')
All statements succeed, including COMMIT, because at that moment the account exists. The same thing with an immediate foreign key would fail at the first insert. Deferral does not remove the rule: it moves the check to the end. The next run references an account that never appears.
ts
console.log('-- an account that never appears')
await a.run('BEGIN')
await a.run(ins, [4, 9, -10])
await a.run(ins, [4, 1, 10])
await a.run('COMMIT')
await a.run('SELECT count(*) AS entries FROM entries')
text
A: BEGIN -> BEGIN []
A: INSERT INTO entries (transfer_id, account_id, amount) VALUES ($1, $2,
$3) [4,9,-10] -> INSERT []
A: INSERT INTO entries (transfer_id, account_id, amount) VALUES ($1, $2,
$3) [4,1,10] -> INSERT []
A: COMMIT -> ERROR 23503 insert or update on table "entries" violates
foreign key constraint "entries_account_id_fkey"
A: SELECT count(*) AS entries FROM entries -> SELECT [{"entries":"4"}]
The inserts succeed and the COMMIT fails with 23503, a foreign key violation, naming the constraint. The count is four: two from transfer 1, two from transfer 3, and nothing from the failed transfer 4. Note that the error is raised by COMMIT. Code that treats COMMIT as a formality and ignores its result would report success for work that was not saved.
A limit of this trigger is worth knowing. It fires on INSERT only, so an UPDATE or DELETE of entries after the fact could unbalance a transfer. A ledger usually forbids both, by permissions or by making the table append-only, or adds the trigger for those events as well.
What the database cannot check
Some rules cannot be written as constraints, or are too expensive to check in the database. "A customer may transfer at most 50,000 in a day." "Only the account holder may start a transfer." "A seat is sold only if the show has not started." The application checks these, and it must check them inside the same transaction that makes the change, so that the check and the change succeed or fail together.
A check in application code carries a risk of its own: the data can change between the check and the change, when two transactions run at once. A SELECT balance followed by an UPDATE based on it is a classic case. The way to deal with it is for the transaction to take the right lock or to use a constraint that the database enforces for every writer. Prefer a declared constraint wherever the rule can be expressed, because the database applies it to every application, including scripts and tools that were written later and never saw your code.
Term
Meaning
Constraint
A rule the database enforces, such as CHECK, UNIQUE or a foreign key
DEFERRABLE
The constraint may be checked at COMMIT instead of after each statement
Constraint trigger
A trigger that can be deferred, used for rules that span rows
Double entry
Every transfer is recorded as entries that sum to zero
Check yourself
Why did the SELECT sum(amount) in the middle of the first transfer show -100.00 without any error?
The balance check is deferred, so it runs at COMMIT. The transaction may pass through an unbalanced state.
The deferred foreign key failed with 23503 on COMMIT. What happened to the other rows of that transfer?
They were rolled back with it. The count of entries stayed at four, with nothing from the failed transfer.
Where should a rule like "at most 50,000 per day" be checked, and why not only in the user interface?
In the application, inside the same transaction as the change. A check only in the interface can be bypassed by other clients and scripts, and one made before the transaction can be outdated by the time it commits.
Part 4 · Durability and the write-ahead log
Write the log first
Durability means that after the database has said "committed", the change survives a crash. The obvious way to achieve it is to write every changed data page to disk at commit. That is slow, because the changed pages are scattered across many table and index files, and a transaction that touches ten pages would need ten random writes before it could return.
PostgreSQL uses a write-ahead log (WAL) instead. The rule, in the documentation's words, is that changes to data files must be written only after those changes have been logged, that is, after the WAL records describing them have been flushed to permanent storage. The WAL is one file, written sequentially, and only it needs to be flushed at commit, which the documentation says costs much less than flushing the data pages. One flush can also cover the commits of several transactions that finish at about the same time.
The sequence for a change is therefore this. The backend process, the server process that serves one connection, changes the data page in shared buffers, in memory, and writes a WAL record describing the change into the WAL buffer. At COMMIT it writes a commit record, and then waits until the WAL has been flushed to disk up to and including that record. Only then does it tell the client. The changed data pages are written to disk later, by background processes, at a time of the server's choosing.
Each WAL record has an address, a log sequence number (LSN), written as two hexadecimal numbers such as 0/18281E8. Two functions report where the log is: pg_current_wal_insert_lsn() is the end of the records written so far, and pg_current_wal_flush_lsn() is the position up to which the log is safely on disk. A transaction is durable once the flush position passes its commit record.
Watching the log position
The script reads the log positions before an update, after it, and after the commit. It starts with a CHECKPOINT, so that no background flushing disturbs the numbers.
ts
console.log('-- the WAL position moves with a transaction')
const pos = `SELECT pg_current_wal_insert_lsn() AS inserted,
pg_current_wal_flush_lsn() AS flushed`
await a.run(pos)
await a.run('BEGIN')
await a.run(`UPDATE accounts SET balance = balance - 100WHERE account_id = 1`)
await a.run(pos)
await a.run('COMMIT')
await a.run(pos)
await a.run(`SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),
pg_current_wal_flush_lsn()) AS unflushed_bytes`)
text
A: SELECT pg_current_wal_insert_lsn() AS inserted,
pg_current_wal_flush_lsn() AS flushed -> SELECT
[{"inserted":"0/18281E8","flushed":"0/18281E8"}]
A: BEGIN -> BEGIN []
A: UPDATE accounts SET balance = balance - 100 WHERE account_id = 1 ->
UPDATE []
A: SELECT pg_current_wal_insert_lsn() AS inserted,
pg_current_wal_flush_lsn() AS flushed -> SELECT
[{"inserted":"0/18282D8","flushed":"0/18281E8"}]
A: COMMIT -> COMMIT []
A: SELECT pg_current_wal_insert_lsn() AS inserted,
pg_current_wal_flush_lsn() AS flushed -> SELECT
[{"inserted":"0/1828300","flushed":"0/1828300"}]
A: SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),
pg_current_wal_flush_lsn()) AS unflushed_bytes -> SELECT
[{"unflushed_bytes":"0"}]
Before the update, the insert and flush positions are the same, 0/18281E8. The UPDATE wrote a record: the insert position moved to 0/18282D8, 240 bytes further on, while the flush position stayed behind. The data is in the WAL buffer, and a crash now would lose it. After COMMIT both are at 0/1828300, so the commit record is on disk, and the final query reports 0 unflushed bytes. The positions come from this run and change from run to run.
The scene shows the same steps as messages.
Animated sceneWhat happens at COMMIT0:17
Watch for the commit waiting until the log record is on disk
Read it as steps
Watch for the commit waiting until the log record is on disk.
The reply to the application is the last step. That ordering is the whole guarantee: if the application has received COMMIT, the commit record was already flushed.
Settings that govern durability
A few settings decide how much of this protection you pay for. The script asks the server for the defaults.
text
A: SHOW fsync -> SHOW [{"fsync":"on"}]
A: SHOW synchronous_commit -> SHOW [{"synchronous_commit":"on"}]
A: SHOW wal_level -> SHOW [{"wal_level":"replica"}]
A: SHOW checkpoint_timeout -> SHOW [{"checkpoint_timeout":"5min"}]
A: SHOW max_wal_size -> SHOW [{"max_wal_size":"1GB"}]
A: SHOW max_prepared_transactions -> SHOW
[{"max_prepared_transactions":"0"}]
fsync is on, which makes the server force WAL to physical storage. Turning it off can give faster commits, but the documentation says it can lead to unrecoverable data corruption after a power failure or system crash, and it should not be used where data matters. synchronous_commit is on, which waits for the local WAL flush at commit (and, when synchronous standbys are configured, for them as well). Setting it to off removes the wait. The other values, local, remote_write and remote_apply, only differ from on when synchronous standbys are configured: without them the documentation says they all give the same local flush. The documentation says that a crash may then lose transactions that were reported as committed, up to three times wal_writer_delay after the report, but without any corruption: the database is left as if they had been aborted cleanly. It is a legitimate choice for data that can be recomputed, such as a session heartbeat, and the wrong one for payments.
wal_level is replica, the level that supports archiving and replication. checkpoint_timeout is five minutes and max_wal_size is 1 GB. A checkpoint flushes all dirty data pages to disk and writes a checkpoint record to the WAL. After a crash the server starts replaying the log from the redo point named by the latest checkpoint record, so the checkpoint interval limits how much log must be replayed. A checkpoint begins every checkpoint_timeout, or earlier when the log is about to exceed max_wal_size. The cost is a burst of writes, so frequent checkpoints are not free.
There is also max_prepared_transactions, which is 0 here. It controls two-phase commit, which a later lesson of this chapter returns to.
Check yourself
The UPDATE moved the insert LSN but not the flush LSN. What does that mean for a crash at that moment?
The change is only in the WAL buffer in memory. A crash then loses it, which is correct, since the transaction had not committed.
Why is flushing the WAL at commit cheaper than flushing the changed data pages?
The WAL is written sequentially in one file, while the changed pages are scattered over many files. The data pages can be written later in the background.
What does synchronous_commit = off risk, and what does it not risk?
It may lose recently reported commits in a crash, for a short window. It does not corrupt the database, which is left as if those transactions had been aborted.
Part 5 · Crash recovery
What recovery has to do
The WAL makes one promise to a crashed server: every committed change is in the log, even if its data pages never reached the disk. Recovery keeps that promise. When the server starts after a crash, it finds the latest checkpoint record in the log, takes the redo point stored in it, and replays every log record from there to the end of the log, applying each change to the data pages. The documentation calls this roll-forward recovery, or REDO.
Replay brings the files back to the state they had at the moment of the crash, including the work of transactions that had not finished. Those transactions have no commit record in the log. After recovery they count as aborted, and the row versions they wrote are invisible to every query. Nothing needs to be undone one record at a time. The result is the one the first lesson promised: committed work survives, uncommitted work is gone.
This lesson makes the server crash on purpose and shows both halves. The setup is a separate local server, started with pg_ctl from the same package, so that the script can control its process. The script commits two kinds of work, leaves a transaction open, and then kills the server process and all its children with taskkill, using only the process id the server wrote in its own postmaster.pid file. The server gets no chance to write data pages or to shut down.
Killing the server mid-transaction
Session A commits a table with two accounts and then an update of Asha's balance to 900. Each statement was autocommitted. Session B opens a transaction, sets Ravi's balance to 0 and adds a third account, and does not commit. The script then kills the server, starts it again, and queries the table from a new session, C. The first lines of the script are helpers that start the server (start), wait for it (up), and run initdb. The part that matters follows.
The main part of the script follows. taskkill is the Windows command, and /T makes it end the child processes too. On Linux or macOS the documentation notes that SIGKILL on the postmaster is not relayed to its child processes, so they would have to be killed as well. Its immediate shutdown mode, pg_ctl stop -m immediate, also ends without shutdown processing and leads to recovery at the next start, and it is the way to rehearse this away from Windows.
ts
const a = await session(port, 'A')
await a.run(`CREATETABLE accounts (account_id int PRIMARY KEY,
holder text NOT NULL, balance numeric(12,2) NOT NULL)`)
await a.run(`INSERT INTO accounts (account_id, holder, balance)
VALUES (1, 'Asha', 1000), (2, 'Ravi', 500)`)
await a.run('UPDATE accounts SET balance = 900 WHERE account_id = 1')
const b = await session(port, 'B')
await b.run('BEGIN')
await b.run('UPDATE accounts SET balance = 0 WHERE account_id = 2')
await b.run(`INSERT INTO accounts (account_id, holder, balance)
VALUES (3, 'Meera', 50)`)
const pid = readFileSync(dir + '/postmaster.pid', 'utf8').split('\n')[0]
console.log('-- kill the server process tree, B has not committed')
execFileSync('taskkill', ['/F', '/T', '/PID', pid], { stdio: 'ignore' })
await sleep(1000)
const skip = readFileSync('log-crash.txt', 'utf8').split('\n').length
start(); await up()
const c = await session(port, 'C')
await c.run(`SELECT account_id, holder, balance
FROM accounts ORDER BY 1`)
await c.end()
const text = readFileSync('log-crash.txt', 'utf8')
for (const l of text.split('\n').slice(skip - 1))
if (/not properly|recovery|redo|ready to/.test(l))
console.log(l.replace(/^\S+ \S+ \S+ \[\d+\] /, ''))
execFileSync(bin + 'pg_ctl.exe', ['-D', dir, '-m', 'fast', 'stop'],
{ stdio: 'ignore' })
process.exit(0)
text
A: CREATE TABLE accounts (account_id int PRIMARY KEY, holder text NOT
NULL, balance numeric(12,2) NOT NULL) -> CREATE []
A: INSERT INTO accounts (account_id, holder, balance) VALUES (1, 'Asha',
1000), (2, 'Ravi', 500) -> INSERT []
A: UPDATE accounts SET balance = 900 WHERE account_id = 1 -> UPDATE []
B: BEGIN -> BEGIN []
B: UPDATE accounts SET balance = 0 WHERE account_id = 2 -> UPDATE []
B: INSERT INTO accounts (account_id, holder, balance) VALUES (3,
'Meera', 50) -> INSERT []
That is what ran before the kill. The next page shows what the clients saw and what came back.
What came back
text
a client saw: read ECONNRESET
a client saw: Connection terminated unexpectedly
a client saw: read ECONNRESET
a client saw: Connection terminated unexpectedly
C: SELECT account_id, holder, balance FROM accounts ORDER BY 1 -> SELECT
[{"account_id":1,"holder":"Asha","balance":"900.00"},
{"account_id":2,"holder":"Ravi","balance":"500.00"}]
LOG: database system was not properly shut down; automatic recovery in
progress
LOG: redo starts at 0/17F33F8
LOG: redo done at 0/1827E20 system usage: CPU: user: 0.01 s, system:
0.00 s, elapsed: 0.01 s
LOG: checkpoint starting: end-of-recovery immediate wait
LOG: checkpoint complete: wrote 41 buffers (0.3%), wrote 3 SLRU
buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.005 s,
sync=0.081 s, total=0.105 s; sync files=37, longest=0.004 s,
average=0.003 s; distance=210 kB, estimate=210 kB; lsn=0/1827E48,
redo lsn=0/1827E48
LOG: database system is ready to accept connections
Session C finds Asha with 900: the committed update is there. Ravi has 500, not 0, and there is no Meera, so B's two uncommitted changes are gone. The server log says why. "Database system was not properly shut down; automatic recovery in progress" is the sign of crash recovery. redo starts at 0/17F33F8 is the redo point, redo done at 0/1827E20 is the end of the replay, and the difference is about 2,15,000 bytes of log. At the end the server writes a checkpoint so that it does not need to replay the same log again, and accepts connections.
The log lines end with a checkpoint taken when recovery finishes (end-of-recovery), so a later start finds a newer checkpoint record and a newer redo point.
A caution about what this run proves. Killing the server process is not the same as cutting the power. After a kill, the operating system still holds the file data that the server had written, even if it was not yet on the physical disk. A power failure loses that data too, and that is the case that the fsync calls at commit protect against. Here recovery needed the log to repair the data pages, and the log record of every commit was in the operating system's hands, so the run shows the replay logic and the handling of unfinished transactions, not protection from the physical loss of cached writes.
How long recovery takes, and what it tells you
Recovery time depends on how much log lies between the last checkpoint and the crash. The checkpoint settings from the last lesson, checkpoint_timeout and max_wal_size, set the upper bound: a crash can only leave a few minutes of log, or about as much as max_wal_size allows, to replay. Spreading checkpoints further apart means fewer bursts of writes and a longer recovery; bringing them closer does the opposite.
The server log is the first place to look after a crash. It reports whether recovery ran, from where and to where, and when connections are accepted again. Clients see the crash as dropped connections, as the two ECONNRESET and "Connection terminated unexpectedly" lines show. An application must treat a dropped connection during a transaction as a failed transaction. It cannot know whether the server committed it just before the crash or not, which is why the last lesson of this chapter adds a key to a payment request, so that sending it again is safe.
Term
Meaning
Redo point
The log position, stored in a checkpoint record, from which replay starts
Replay (REDO)
Applying the log records after the redo point to the data pages
Crash recovery
Replay at start-up after the server stopped without a clean shutdown
postmaster.pid
A file in the data folder with the process id of the server
Check yourself
After the crash, Asha had 900 and Ravi had 500. Why was the first change kept and the second dropped?
The update to 900 had a commit record in the log, so replay applied it. Session B never committed, so its records had no commit record, and its changes count as aborted.
What does redo starts at tell you?
The position in the log of the checkpoint's redo point, where replay began. Everything between it and redo done at was replayed.
Why does a killed server process not prove that fsync works?
The operating system keeps the written data in its cache after the process dies. Only a power loss or operating-system crash discards that data, and that is what fsync at commit protects against.
Part 6 · Transactions in application code
Short transactions and retries
A transaction should hold its locks and its snapshot for as short a time as it can. That means: do the slow work, such as an HTTP call or a calculation, before BEGIN or after COMMIT; send the statements one after another without waiting for a user; and end the transaction on every path, including errors. A connection left in a transaction blocks other sessions that want the same rows.
Some failures are not bugs. PostgreSQL may abort a healthy transaction because of what another transaction did, and it signals this with two SQLSTATE codes. 40001 is a serialisation failure: the message is "could not serialize access due to concurrent update" or similar, and it occurs at the higher isolation levels when two transactions conflict. 40P01 is a deadlock, which the next page produces. The documentation says that applications using those isolation levels must be prepared to retry transactions, and that a failed transaction should be aborted and retried from the beginning, whole, not from the failing statement. At Repeatable Read, only updating transactions can fail this way.
The function below wraps a unit of work in a retry loop. It starts a REPEATABLE READ transaction, a level that reports conflicting updates as 40001, and runs the work. On COMMIT it returns. On an error it rolls back and retries only when the code is 40001 or 40P01, at most three times. Any other error is thrown at once.
ts
type Work = (attempt: number) => Promise<void>
asyncfunction withRetry(c: pg.Client, work: Work) {
for (let n = 1; ; n++) {
await c.query('BEGIN ISOLATION LEVEL REPEATABLE READ')
try {
await work(n)
await c.query('COMMIT')
console.log(`attempt ${n}: committed`)
return
} catch (e) {
await c.query('ROLLBACK')
const code = (e as { code?: string }).code ?? ''
console.log(`attempt ${n}: failed with ${code}`)
if (!['40001', '40P01'].includes(code) || n >= 3) throw e
}
}
}
A retry, run
The work reads Asha's balance, calculates a new one in the application, and writes it back, a read-modify-write that the database cannot protect by itself. On the first attempt, a second session changes the same row between the read and the write.
ts
await withRetry(c, async (n) => {
const r = await c.query(
'SELECT balance FROM accounts WHERE account_id = 1')
const balance = Number(r.rows[0].balance)
console.log(`attempt ${n}: read balance ${balance}`)
if (n === 1) await other.run(`UPDATE accounts
SET balance = balance + 50WHERE account_id = 1`)
await c.query(
'UPDATE accounts SET balance = $1 WHERE account_id = 1',
[balance - 100])
})
text
attempt 1: read balance 1000
B: UPDATE accounts SET balance = balance + 50 WHERE account_id = 1 ->
UPDATE []
attempt 1: failed with 40001
attempt 2: read balance 1050
attempt 2: committed
B: SELECT balance FROM accounts WHERE account_id = 1 -> SELECT
[{"balance":"950.00"}]
The lines that create and fill the table are left out.
The first attempt read 1000. Session B added 50 and committed. The write then failed with 40001, because the row had changed since the transaction took its snapshot. Attempt 2 started again from the beginning, read 1050, wrote 950, and committed. The final balance, 950, includes B's 50: nothing was lost. Without the retry the application would have shown an error to a user, and with the write done blindly it would have overwritten B's change.
Two rules make the loop safe. The retry covers everything the transaction did, including the reads, because the decision to write 950 depends on what was read. And side effects outside the database, such as sending an email, must not happen inside the retried work, or they would be repeated.
Idempotency keys
A network call can fail after the server has done the work: the commit succeeded and the reply was lost. The client cannot tell, and the only safe thing to do is to send the request again. For a payment, that must not move the money twice. An operation is idempotent if running it several times has the same effect as running it once.
The usual way to get this is an idempotency key: a unique identifier the client generates for each payment request and sends with every retry of it. The server records the key in a table with a unique constraint, in the same transaction as the payment. The second attempt conflicts with the stored key, and the server recognises it as a repeat. The function below uses INSERT ... ON CONFLICT DO NOTHING RETURNING: if the insert returns no row, the key already exists, and the transfer is skipped.
ts
asyncfunction transfer(key: string, from: number, to: number,
amt: number) {
await a.run('BEGIN')
const done = await a.run(`INSERT INTO transfers
(idempotency_key, from_id, to_id, amount) VALUES ($1, $2, $3, $4)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key`, [key, from, to, amt])
if (!done || done.length === 0) return a.run('ROLLBACK')
await a.run(`UPDATE accounts SET balance = balance - $1WHERE account_id = $2`, [amt, from])
await a.run(`UPDATE accounts SET balance = balance + $1WHERE account_id = $2`, [amt, to])
await a.run(`INSERT INTO outbox (payload) VALUES ($1)`,
[JSON.stringify({ event: 'transfer_done', key, amount: amt })])
return a.run('COMMIT')
}
The same request is sent twice. The function also writes an outbox row for the committed transfer, which the next page explains.
text
A: BEGIN -> BEGIN []
A: INSERT INTO transfers (idempotency_key, from_id, to_id, amount)
VALUES ($1, $2, $3, $4) ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key ["pay-2026-0001",1,2,100] -> INSERT
[{"idempotency_key":"pay-2026-0001"}]
A: UPDATE accounts SET balance = balance - $1 WHERE account_id = $2
[100,1] -> UPDATE []
A: UPDATE accounts SET balance = balance + $1 WHERE account_id = $2
[100,2] -> UPDATE []
A: INSERT INTO outbox (payload) VALUES ($1)
["{\"event\":\"transfer_done\",\"key\":\"pay-2026-0001\",
\"amount\":100}"] -> INSERT []
A: COMMIT -> COMMIT []
A: BEGIN -> BEGIN []
A: INSERT INTO transfers (idempotency_key, from_id, to_id, amount)
VALUES ($1, $2, $3, $4) ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key ["pay-2026-0001",1,2,100] -> INSERT []
A: ROLLBACK -> ROLLBACK []
A: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"900.00"},{"holder":"Ravi",
"balance":"600.00"}]
A: SELECT idempotency_key, amount FROM transfers -> SELECT
[{"idempotency_key":"pay-2026-0001","amount":"100.00"}]
A: SELECT outbox_id, payload, sent_at FROM outbox -> SELECT
[{"outbox_id":1,"payload":{"key":"pay-2026-0001",
"event":"transfer_done","amount":100},"sent_at":null}]
The first call runs BEGIN, the insert, the two updates, the outbox insert and COMMIT. In the second, the insert returns no row (INSERT []) and the function rolls back. The balances show one transfer, 900 and 600, and transfers has one row. The unique constraint on the key, not the application's logic, is what makes the repeat safe: two concurrent copies of the same request would collide on it as well, and only one would proceed.
Deadlocks, the outbox and two-phase commit
A deadlock happens when two transactions each hold a lock the other needs. The script crosses two updates: A changes account 1 and B changes account 2, then A asks for account 2 and B asks for account 1.
ts
await a.run('BEGIN')
await b.run('BEGIN')
await a.run(move(1))
await b.run(move(2))
const waiting = a.run(move(2))
awaitnew Promise((r) => setTimeout(r, 300))
console.log('A is waiting for B, now B asks for the row A holds')
await b.run(move(1))
await waiting
await a.run('COMMIT')
await b.run('COMMIT')
text
A: SHOW deadlock_timeout -> SHOW [{"deadlock_timeout":"1s"}]
A: BEGIN -> BEGIN []
B: BEGIN -> BEGIN []
A: UPDATE accounts SET balance = balance - 10 WHERE account_id = 1 ->
UPDATE []
B: UPDATE accounts SET balance = balance - 10 WHERE account_id = 2 ->
UPDATE []
A is waiting for B, now B asks for the row A holds
A: UPDATE accounts SET balance = balance - 10 WHERE account_id = 2 ->
ERROR 40P01 deadlock detected
B: UPDATE accounts SET balance = balance - 10 WHERE account_id = 1 ->
UPDATE []
A: COMMIT -> ROLLBACK []
B: COMMIT -> COMMIT []
A: SELECT holder, balance FROM accounts ORDER BY account_id -> SELECT
[{"holder":"Asha","balance":"990.00"},{"holder":"Ravi",
"balance":"490.00"}]
The lines that create and fill the table are left out.
PostgreSQL notices the cycle after deadlock_timeout, 1 second by default, and aborts one of the transactions with 40P01. In this run it was A. The documentation says that which transaction is aborted is difficult to predict and should not be relied upon. The survivor, B, continued and committed, and A's COMMIT answered ROLLBACK. The balances show only B's change to account 2 and its change to account 1, 990 and 490. The cure is to take locks in a consistent order, here always the lower account number first, and the fallback is the retry loop above, which treats 40P01 like 40001.
When a transaction must also tell another system about a change, such as a message queue or a search index, the obvious solution is a distributed transaction that commits in both at once. PostgreSQL supports a building block for it, PREPARE TRANSACTION, for two-phase commit. The documentation says it is not intended for application use but for an external transaction manager, and warns that a prepared transaction holds its locks and can interfere with VACUUM if left for long. max_prepared_transactions is 0 by default, as the earlier run showed, so the feature is off.
The simpler pattern is the outbox. The application writes its change and a row describing the event into an outbox table in the same local transaction, as the previous page did. A separate relay process reads unsent outbox rows, delivers them to the other system, and marks them sent. The change and the event commit or fail together. The relay may deliver an event twice if it crashes between delivering and marking, so the receiver must handle duplicates, with an idempotency key, for example.
Check yourself
Why must the whole transaction be retried after 40001, and not only the failing UPDATE?
The values written depend on what was read in the transaction, and the failure shows that those reads are out of date. A fresh transaction must read again.
The payment request is sent twice with the same key. What stops the money moving twice?
The unique constraint on the key. The second insert finds the key, returns no row, and the function rolls back.
Which transaction is the victim of a deadlock, and how should the application react?
The server picks one and its choice cannot be predicted. The application should retry the aborted transaction, and avoid deadlocks by locking rows in a consistent order.