Relational databases
Transactions and isolation
A transaction groups database work into one outcome: its changes commit together or are abandoned together. Isolation determines how that work interacts with other transactions. The distinction matters whenever a decision can become wrong between reading the facts and changing them.
The shop has one blue mug left. Mina and Tariq can each read that one mug, each decide to buy it and each commit a complete purchase. Nothing was left half-written, yet the shop sold the same mug twice. Choosing the transaction's boundary solved one problem; choosing how it makes its decision must solve the other.
We will replay Mina's order 103, then follow a separate rule about payments against it. The examples use PostgreSQL 18. The examples use selected interleavings to expose particular results; they do not predict which request wins or how long it waits. Other engines can give the same isolation name different behaviour.
One purchase, one transaction
Before order 103, P7 has one blue mug and P3 has twelve packets of green tea. Mina wants the mug and two teas. Accepting her purchase must reduce both stock counts and record the order with both lines. Keeping only some of those changes would give the shop a different purchase from the one it accepted.
One transaction must own the two stock decrements, the pending order and both lines. If work stops after allocating the mug, rollback must abandon that allocation too; otherwise the database would retain only part of the purchase.
Figure as text
The mug allocation, tea allocation and order are provisional together. Commit makes all three available to a new reader. Rollback after the mug allocation leaves the original stock and no order.
BEGIN starts the transaction. Its own statements can read the changes it has made, so the order can be inserted before its lines refer to it. COMMIT accepts the changes as a unit. ROLLBACK abandons them. This all-or-nothing property is atomicity.
Without an explicit transaction block, PostgreSQL runs each successful statement in its own transaction, unless the client has already started one. Two updates followed by two inserts would then have several independent commit points. A failure between them could leave reduced stock without the order it was allocated to.
The successful purchase leaves P7 at 0, P3 at 10 and P9 at 4. Order 103 is pending. Line 1 is P7 × 1 at 20.00 and line 2 is P3 × 2 at 4.50, so the order totals 29.00. There is no payment. Calling a card provider from inside this block would not make its charge roll back with the database. The transaction boundary covers the database work; external work needs its own delivery and recovery design.
Guarding the last mug
Atomicity does not tell the database why a change is being made. Suppose Mina's purchase 103 and Tariq's competing purchase 104 each read stock 1. Each application calculates 1 - 1 and sends this later:
UPDATE products
SET stock = 0
WHERE product_id = 'P7';Both writes can succeed. The second replaces 0 with 0, so the constraint CHECK (stock >= 0) has no reason to refuse it. Both purchases can be complete and stock can be non-negative while two buyers have been promised one mug.
The condition that authorises the purchase belongs in the change itself:
UPDATE products
SET stock = stock - 1
WHERE product_id = 'P7' AND stock >= 1
RETURNING product_id, stock;This is a guarded update. It subtracts from the row being changed only if that row has enough stock. At PostgreSQL’s default isolation level, Read Committed, the stock condition is checked against the row the update can actually change, including after a conflicting transaction has finished.
Figure as text
Mina and Tariq both read one mug. Mina updates first. Tariq waits. Writing the earlier calculated zero can accept both purchases; a guarded subtraction rechecks stock zero and changes no row, so Tariq rolls back.
When Mina changes P7 first, her update holds a row lock until her transaction ends. Tariq's competing update waits. After Mina commits, Read Committed rechecks Tariq's condition against the updated P7. Stock is now 0, so stock >= 1 is false. His update changes no row and returns no row. If Mina rolled back instead, the available mug would remain for Tariq to try to allocate.
Zero changed rows is a successful SQL command with a failed business precondition. The application must roll back all of purchase 104, including any stock or order changes it made earlier. It must check each allocation, including the two packets of tea required by purchase 103. A guard on the mug alone cannot prove that a whole basket was available.
The non-negative constraint still belongs in the schema: it protects stock against other mistaken writes too. The guard expresses this operation's permission to allocate, and the transaction keeps that allocation with its order and lines. All three do different work.
What a transaction can see
A snapshot is the committed database view available to a read. It is a visibility rule, not a copy of all the tables. The transaction also sees its own earlier changes. PostgreSQL keeps row versions so an ordinary reader can use an earlier view while a writer changes a row; Storage and durability develops where those versions live.
An ordinary reader cannot read Mina's uncommitted order while she is still adding its lines. Once her purchase commits, all its changes become eligible to be seen together. That does not mean every later statement must use that committed view. The reader's isolation level determines which snapshot it uses.
Read Committed
At Read Committed, each ordinary SELECT gets a fresh statement snapshot. Go back before purchase 103. A report first reads mug stock. Mina then commits the purchase. The report next asks whether order 103 exists, using a snapshot from after that commit.
Figure as text
The first stock read sees one mug. Mina commits a purchase. Read Committed uses new statement snapshots: the order appears and the later stock read sees zero. Repeatable Read keeps the first query’s snapshot: no order and stock one.
The report has stock 1 from its first statement and an existing order 103 from its second. Those answers came from opposite sides of the commit. No reader saw half an uncommitted transaction, but the application combined facts from two moments. Reading P7 again would now give 0: a nonrepeatable read, where a repeated read returns a changed value.
One ordinary SELECT that reads both facts would use one snapshot. Several such statements in a Read Committed transaction do not share one. Also keep an ordinary snapshot read distinct from the guarded update: the update's wait and recheck are what made the last-mug decision safe.
Repeatable Read
At Repeatable Read, the report’s first query establishes its transaction snapshot. Its later queries keep that view, so it sees stock 1 and no order 103, even after Mina’s commit. This is useful for several queries that must describe the same database view, such as the batches of a consistent export.
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT stock FROM products WHERE product_id = 'P7';
-- This first query establishes the snapshot.
-- Another session can commit purchase 103 here.
SELECT order_id FROM orders WHERE order_id = 103;
COMMIT;BEGIN alone does not establish this snapshot. If Mina commits after BEGIN but before the report's first query, the report sees her purchase. In PostgreSQL, the first query or data-changing statement fixes the Repeatable Read view. Set the isolation level before that statement.
A stable view is not permission to overwrite newer work. If a Repeatable Read transaction tries to update P7 after another transaction changed it and committed since that view was established, PostgreSQL can abort it with a serialization failure. It cannot proceed by adopting the newer P7 as Read Committed did. The application must start the whole transaction again with fresh reads.
Repeated queries can also differ by gaining or losing matching rows. That is a phantom read: for example, a query for order 103's payments returns no rows, then returns a payment another transaction committed. PostgreSQL Repeatable Read prevents that too. Its stable set of rows still leaves a different problem.
When the rule spans rows
Start a separate scenario after order 103 exists. Its two lines are worth 29.00 and it has no payments. Suppose the shop's rule is that total recorded payments must not exceed that line value. Keep the lines fixed for this example. Two requests each want to record 20.00.
Each request reads the order's line value and the total already paid, then decides whether there is room for its payment. The totals must be calculated separately, so joining several payment rows to several order lines does not multiply either amount. This query returns one pair of totals:
SELECT
(SELECT SUM(quantity * unit_price)
FROM order_items WHERE order_id = 103) AS line_value,
(SELECT COALESCE(SUM(amount), 0)
FROM payments WHERE order_id = 103) AS paid;
-- line_value | paid
-- 29.00 | 0A request allows the insert only when paid + 20.00 <= line_value. Suppose both Repeatable Read requests read before either commits, then insert different payment rows.
Figure as text
Two transactions each read zero paid and propose twenty. Under Repeatable Read their distinct payment rows can both commit, producing forty. Serializable cannot retain both; in the illustrated outcome one aborts and its whole retry refuses another twenty.
Both snapshots say 0 paid. Each new payment fits, because 20.00 is at most 29.00. Payment 601 and payment 602 have different primary keys, so there is no duplicate key or shared payment row to stop them. Both transactions can commit, leaving 40.00 paid against 29.00 of lines.
Each transaction could repeat its total query before inserting and still get 0. It has no nonrepeatable read and no phantom. The problem is write skew: overlapping transactions read facts that jointly authorise their changes, then write different rows whose combined effect breaks the rule.
Try placing the requests in a serial order, with one complete before the other starts. If A goes first, B reads 20.00 paid and refuses another 20.00. If B goes first, A refuses. Neither order allows both payments. The concurrent outcome cannot match any serial order: it is a serialization anomaly.
A row check that each amount is positive accepts both payments. A PostgreSQL CHECK cannot enforce this total across other rows. Nor does locking only the existing payments solve the empty case: there are no payment rows to lock, and another request can insert a new one. The decision needs protection over the set it reads, including possible additions.
Serializable
Serializable requires the committed work to have an effect equivalent to running the transactions one at a time in some order. It does not require the engine to run them literally one at a time. PostgreSQL lets them overlap, tracks conflicts between their reads and writes and aborts work when needed to preserve serial outcomes.
At Serializable, the requests can still both read 0, but they cannot both keep their payment. Suppose A commits and B is aborted. That is one possible winner, and the failure may be reported during the work or at commit. Only a successful commit confirms that an attempt’s work survived.
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- Read line_value and paid with the query above.
-- Application: if paid + 20.00 > line_value, ROLLBACK.
-- Otherwise insert this request's payment:
INSERT INTO payments (payment_id, order_id, amount, method)
VALUES (601, 103, 20.00, 'card');
COMMIT;This shows request A's database work, not an executable conditional program: the application must make the stated decision before issuing the insert and handle any error through commit. Every participating writer must follow the protection. Serializable cannot infer a payment rule from an unconditional insert, or protect it against a writer that bypasses the protocol. If order lines can change, those changes must also preserve the rule.
PostgreSQL reports a serialization failure with SQLSTATE 40001. Abandon that attempt and retry the whole transaction, including the reads and the application decision. B’s new attempt then sees 20.00 paid. It refuses the second 20.00 rather than replaying an insert approved by the old view. A retry is another chance to make a valid decision, not a promise that the original purchase or payment will be accepted.
There is a cost: conflict tracking and aborted work, which can grow under contention. Keep the decision and its writes short, and put a bound on repeated attempts. Do not send a charge or confirmation based on provisional reads from an attempt that may still abort.
Giving a decision a common lock
A different approach gives every payment decision the same existing row to coordinate through: order 103's order row. Each participating request takes an exclusive row lock on that authority before reading the totals, and keeps it through its decision, insert and commit. The requests can no longer make the decision at the same time.
The order row exists before any payments. Locking it does not automatically lock all its payments; every writer must cooperate in the same protocol.
The read still needs the right snapshot. At Read Committed, a separate totals query after acquiring the authority lock can see the preceding holder's committed payment. Taking the lock does not refresh an already established Repeatable Read snapshot. A lock on an unchanged order row can therefore coexist with a stale view of its payments.
This is the point to design the complete protocol: which row represents the rule, when the snapshot is taken, which writers participate and in what order they acquire several locks. Locks, contention and deadlocks develops that design and the diagnosis of waiting. Adding FOR UPDATE to an arbitrary query is not enough to establish it.
An abort and a missing commit reply
A serialization failure tells the application that this attempt did not commit. Starting again with fresh reads is appropriate. A dropped connection while COMMIT is in flight tells it less: the server may have committed and lost the reply, or may not have committed at all.
| What arrives | What it establishes | Next decision |
|---|---|---|
Successful COMMIT reply | This attempt committed | Report its accepted result |
| Serialization failure | This attempt was aborted | Retry the whole decision from fresh reads, within the request's retry policy |
| Connection lost during commit | The outcome is unknown | Recover the result of the same logical request before applying it again |
A blind second purchase could allocate stock twice even under Serializable: two complete purchases in sequence are a perfectly serial outcome. Request identity and a recorded result connect retries to the same business action. Retries and uncertain commit outcomes develops that recovery procedure. Isolation protects overlapping decisions; it does not identify duplicate requests.
Choosing isolation for a rule
Start by stating the fact that must remain true: an invariant. For the mug, accepting a purchase must allocate available stock. For payments, their total must remain at most the order's line value. Then name the reads that authorise the change and every operation that can invalidate them.
| Need | Protection developed here | What still needs checking |
|---|---|---|
| Keep the purchase's changes together | One atomic transaction | Every failed guard rolls back the whole purchase |
| Allocate from one product row | Guard and subtract together at PostgreSQL Read Committed | Every allocation checks its affected rows |
| Read several results from one view | One Repeatable Read transaction | When its first query fixes the snapshot |
| Decide from a changing set of payments | Serializable work with whole-transaction retries, or a complete common-lock protocol | Every writer, including changes to the order's value, preserves the rule |
Choose from the rule, not from an isolation name alone. A stable snapshot answers what was visible together; a serial outcome says the committed decisions can fit together. Keep enforceable constraints alongside the protocol, test both competing attempts on the chosen engine and follow a failed or uncertain request all the way to its business result.