Under the Hood of PostgreSQL: Transactions, Plans, and Indexes

ACID: four guarantees without rote memorization

38 min

Chapter 10 — “The Engine Room”

QUERY stops beside a hatch you never noticed before: a round cover set into the floor of the archive deck, beneath a layer of amber light. A narrow ladder descends into a steady hum. Server racks, streams of log records, warm air from running hardware.

The engine room of Vault-9.

The blueprints from the last chapter are behind you. Ahead is the machinery that has kept this memory intact for one hundred sixty years.

QUERY: One hundred sixty years, and not a single row has fallen apart. That's not luck, cadet. It has a four-letter name.

The cadet climbs down into the orbital archive's engine room; four amber holographic supports representing the ACID guarantees hover above the server racks
Below the archive deck: four ACID supports — atomicity, consistency, isolation, and durability — hold the station's memory together.

ACID: four transaction guarantees

When a Kotomarket customer places an order, the database doesn't make just one change.

It needs to:

  1. create a row in orders;
  2. add items to order_items;
  3. reduce product stock in products;
  4. possibly record a payment;
  5. update the order status.

To a person, that's one action: “place an order.” To the database, it's several SQL commands.

That split creates several ways things can go wrong.

What if the server crashes after creating the order but before adding its items? What if stock is reduced, but the order is never created? What if two try to sell the last item at the same time? What if the database says COMMIT, but the row disappears after a restart?

To keep failures like these from turning the archive into ruins, transactions have properties.

ACID gives us four guarantees:

  • A — Atomicity
  • C — Consistency
  • I — Isolation
  • D — Durability

Don't memorize the acronym as a list of English words. Remember the idea instead: ACID turns several commands into one reliable unit of work.

BEGIN;

INSERT INTO orders (id, user_id, status, total_amount)
VALUES (1001, 7, 'paid', 25.00);

INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES
  (1001, 10, 2, 10.00),
  (1001, 15, 1, 5.00);

UPDATE products
SET stock = stock - 2
WHERE id = 10;

UPDATE products
SET stock = stock - 1
WHERE id = 15;

COMMIT;

To SQL, these are several commands. To the transaction, they're one job.

Either everything is applied, or everything is rolled back.

A — Atomicity: all or nothing

Atomicity means that a transaction either completes in full or doesn't happen at all.

If the database starts placing an order but something fails halfway through, it must not leave half the changes behind.

Bad:

order created
items not created
product stock reduced
payment status unknown

An order like this is a ghost: one part of the archive says it exists, while another says it doesn't.

Atomicity prevents that. If the transaction never reaches a successful COMMIT, its changes are rolled back.

The classic example is a money transfer:

debit 1000 from account A
credit 1000 to account B

These actions can't be separated. A failure between them must not leave the money “in midair.”

C — Consistency: the data obeys the rules again

Consistency means that a transaction moves the database from one valid state to another valid state.

A valid state isn't magic. It's defined by the rules in the schema and the system's logic:

  • PRIMARY KEY prevents duplicates;
  • FOREIGN KEY prevents references to rows that don't exist;
  • NOT NULL prevents required fields from being left empty;
  • CHECK rejects impossible values;
  • business must remain true.

For example, suppose the products table has this rule:

CHECK (stock >= 0)

Then a transaction must not commit a negative stock value.

If order_items.order_id has a to orders.id, an order item must not refer to an order that doesn't exist.

One caveat matters especially in interviews: the database can enforce only the rules you actually describe to it.

If you define a CHECK, FK, NOT NULL, or UNIQUE , PostgreSQL will enforce it. If a business invariant exists only in the team's heads or in a task comment, the database won't infer it on its own.

For example, this invariant:

orders.total_amount = sum of all order items

can be checked with a query, but unless it's enforced by a constraint, trigger, or correct transactional logic, the database isn't required to maintain it by itself.

I — Isolation: other transactions' drafts shouldn't interfere

Isolation controls how concurrent transactions see one another.

Imagine there's one item left in stock:

products.stock = 1

Two customers click “Buy” at the same time.

Without proper isolation, both transactions may read stock = 1, both decide “the item is available,” and both try to place an order. The same last item can end up being sold twice.

Isolation keeps concurrent work from interfering in unsafe ways.

Think of it this way: one transaction shouldn't see another transaction's kitchen while the meal is still being prepared. Another transaction's uncommitted changes are only a draft. They're here now, but they may be rolled back a second later.

SQL has different isolation levels. They control which effects are allowed during concurrent work: dirty reads, non-repeatable reads, phantom reads, and other anomalies. We'll cover them later. For now, remember the role of I: it protects transactions from one another.

D — Durability: don't lose data after COMMIT

Durability means that once the database says COMMIT, the result must survive a failure.

Not “probably.” Not “if you're lucky.” A committed transaction must not disappear after a restart.

For example:

BEGIN;

UPDATE orders
SET status = 'paid'
WHERE id = 1;

COMMIT;

If the client receives confirmation of COMMIT, it can treat the payment as safely recorded.

Even if the power flickers a second later, the server restarts, or the PostgreSQL process crashes, the database must restore the committed state.

This is where comes in.

reliabilityAAtomicityCConsistencyIIsolationDDurability
The four ACID supports: atomicity and durability protect against failures, consistency protects the rules, and isolation protects transactions from one another.

A is a set of operations that the database treats as one unit of work.

A transaction begins, runs several commands, and then either commits its changes:

COMMIT;

or rolls them back:

ROLLBACK;

is the set of guarantees that keeps this “one unit of work” from breaking into unsafe pieces.

ACID letter by letter: where each guarantee helps

Instead of treating as an acronym to memorize, think of it as a set of emergency systems in the engine room.

A — Atomicity: failure in the middle of operations

Atomicity handles this situation: “we started making several changes but never reached the end.”

Take a money transfer:

BEGIN;

UPDATE accounts
SET balance = balance - 1000
WHERE id = 1;

UPDATE accounts
SET balance = balance + 1000
WHERE id = 2;

COMMIT;

If the server crashes after the first UPDATE but before the second, prevents the database from committing a state where money was debited from one account but never credited to the other.

The same applies to an order:

create order
create items
reduce stock
record payment

This must be one indivisible operation. If something goes wrong, roll everything back.

A useful question to ask yourself:

Can the system remain valid if only half of these commands run?

If the answer is “no,” the commands belong in one .

C — Consistency: broken rules and invariants

Consistency deals with correctness rules.

Some rules live directly in the schema:

CREATE TABLE products (
  id INT PRIMARY KEY,
  name TEXT NOT NULL,
  stock INT NOT NULL CHECK (stock >= 0)
);

Now the database won't accept a product without a name or allow a negative stock value to be stored.

Another example is a :

CREATE TABLE order_items (
  id INT PRIMARY KEY,
  order_id INT NOT NULL REFERENCES orders(id),
  product_id INT NOT NULL REFERENCES products(id),
  quantity INT NOT NULL CHECK (quantity > 0)
);

An order item can't refer to an order or product that doesn't exist.

Some business , however, are harder to express with a single . For example:

order total must equal the sum of its items

You can check that with a query:

SELECT
  o.id AS order_id,
  o.total_amount,
  SUM(oi.quantity * oi.unit_price) AS items_sum
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id, o.total_amount
HAVING o.total_amount <> SUM(oi.quantity * oi.unit_price);

If the query returns rows, those orders have totals that don't match their items.

Consistency doesn't mean the database automatically understands every business rule. It guarantees that a transaction won't violate rules expressed through constraints and correct transactional logic. The more precisely you define those rules in the schema and code, the stronger your consistency guarantees become.

I — Isolation: neighboring transactions

Isolation deals with concurrency.

One transaction may be changing data while another reads it. At that moment, the second transaction must not see an unsafe intermediate state.

Here's a simple example:

-- Transaction 1
BEGIN;

UPDATE orders
SET status = 'paid'
WHERE id = 1;

-- COMMIT has not happened yet

Until COMMIT happens, the change can still be rolled back. If another transaction already assumes that the order is paid and the first one later runs ROLLBACK, the system ends up relying on a false fact.

Isolation prevents transactions from reading one another's unfinished changes and controls how strictly concurrent transactions are separated.

Isolation comes in levels. The stricter the level, the fewer strange effects you get under concurrency, but the higher the cost in locks, waiting, or conflicts.

You'll return to isolation levels later in this chapter. For now, keep this picture in mind:

isolation = transactions should not see one another's dangerous drafts

D — Durability: losing something that was already committed

Durability handles this situation: “the transaction was already committed, but then something failed.”

In PostgreSQL, this guarantee is supported by — the Write-Ahead Log.

The WAL principle is:

first write to the log,
then change the data pages

Why do it in that order?

At COMMIT, PostgreSQL doesn't have to physically rewrite every affected table and index page to disk immediately. That would be too expensive. Instead, the database first writes enough information to WAL to reconstruct the changes later.

In simplified form, the process looks like this:

  1. the transaction changes data;
  2. PostgreSQL writes a description of those changes to WAL;
  3. on COMMIT, WAL must be flushed to disk;
  4. the client receives confirmation of COMMIT;
  5. the table pages themselves may be written later in the background.
BEGIN;

UPDATE orders
SET status = 'paid'
WHERE id = 1;

COMMIT; -- confirmation arrives after WAL is safely written

If a failure happens after that, PostgreSQL performs crash recovery at startup: it reads WAL and restores the committed changes.

QUERY sweeps a beam of light across the log stream:

QUERY: The tables may not have time to put themselves in order. The log must. That's why it writes first.

A table to remember

LetterGuaranteeProtects againstExample
AAtomicityfailure in the middle of operationsmoney doesn't get stuck between accounts
CConsistencybroken rules and invariantsproduct stock doesn't go below zero
IIsolationother transactions' unfinished worktwo purchases of the last item don't break stock
DDurabilitylosing committed dataafter COMMIT, payment survives a restart

The biggest trap: you define the transaction boundaries

ACID works within the boundaries of a single transaction.

Suppose you do this:

BEGIN;

INSERT INTO orders (id, user_id, status)
VALUES (1001, 7, 'paid');

COMMIT;

But move the stock update into a separate transaction:

BEGIN;

UPDATE products
SET stock = stock - 1
WHERE id = 10;

COMMIT;

Now there's a gap between them. The first transaction has already committed the order, while the second hasn't reduced the stock yet. If something fails at that moment, the system can be left in an intermediate business state.

ACID can't guess that you considered those two separate transactions a single operation.

Developers and testers therefore need to know where the transaction boundary belongs.

If a business operation is indivisible, all of its steps should be inside one transaction:

BEGIN;

-- create order
-- create items
-- reduce stock
-- record payment

COMMIT;

Otherwise, the “all or nothing” guarantee applies only to the individual pieces, not to the whole business operation.

Atomicity can't save you from a “half that never failed”

Atomicity has a limit you'll run into on the first real-world task. It undoes changes when something FAILS. But if a command completes normally and simply finds no matching rows, there is no failure — so the database has nothing to roll back.

Look at this guarded transfer:

BEGIN;

UPDATE accounts
SET balance = balance - 1000
WHERE id = 1 AND balance >= 1000;

UPDATE accounts
SET balance = balance + 1000
WHERE id = 2;

COMMIT;

If the sender has less than one thousand, the first UPDATE changes zero rows. That's not an error: the command completed successfully. The second UPDATE knows nothing about that and still credits the money — money appears out of nowhere, and the transaction commits successfully.

To make the second part depend on the first, tie them together in ONE command: the change returns the affected rows, and the second change runs only if those rows exist.

WITH taken AS (
  UPDATE accounts
  SET balance = balance - 1000
  WHERE id = 1 AND balance >= 1000
  RETURNING id
)
UPDATE accounts
SET balance = balance + 1000
WHERE id = 2 AND EXISTS (SELECT 1 FROM taken);

Not enough money? Nothing changes. There's also no gap between the two parts where another transfer can slip in: this is one command, not two.

Passing account IDs and amounts as parameters

In the exercises so far, the account ID and amount have been written directly into the SQL: id = 1, 1000. In an application, these values come from the client. One request deducts 1000 from account 1; the next deducts 250 from account 7. You don't need to write a new SQL statement for every payment. Instead, use $1 and $2 as placeholders and supply the actual numbers when you execute the statement.

PREPARE debit(int, numeric) AS
UPDATE accounts
SET balance = balance - $2
WHERE id = $1 AND balance >= $2;

EXECUTE debit(1, 1000);
EXECUTE debit(7, 250);

PREPARE parses the SQL statement and saves it under the name debit. When you call EXECUTE, the database runs the statement using the values you provide. In the first call, $1 receives account ID 1, and $2 receives the amount 1000. In the second call, the values change, but the SQL stays the same. In an application, the database driver handles this by sending the SQL with $1 and $2 separately from the parameter values. The course sandbox has EXECUTE disabled, so you won't be able to run this example here.

It might seem easier to build a SQL string by inserting values directly from a form. But suppose someone enters 1 OR true instead of account ID 1. If the application inserts that text directly into the SQL, the resulting query looks like this:

UPDATE accounts
SET balance = balance - 1000
WHERE id = 1 OR true AND balance >= 1000;

The user's input is now part of the SQL condition. Because AND is evaluated before OR, the query affects account 1 and every other account with enough money. It also deducts 1000 from account 1 even if the balance is too low. This is SQL injection: a user changes the logic of a query through an input field. You may be asked to explain this kind of example in a job interview. Parameters prevent the attack. The string 1 OR true is treated as a value rather than SQL code. The database tries to convert it to the required int type, raises a type conversion error, and leaves every row unchanged.

SELECT
  o.id AS order_id,
  o.total_amount,
  SUM(oi.quantity * oi.unit_price) AS items_sum
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.id IN (1, 2, 3)
GROUP BY o.id, o.total_amount
ORDER BY o.id;
Practice: write the query
At Kotomarket, a paid order with no items is called a ghost order. The setup deletes every order_items row for orders 5, 12, and 17, and the database doesn't object. Complete the check: return the id and total_amount of orders with status = 'paid' for which order_items contains no rows with their order_id.
Column names and their order are not checked — the values are compared.
DELETE FROM order_items
WHERE order_id IN (5, 12, 17);

SELECT id, total_amount
FROM orders;
Interview question

Interview question: What is ? Explain each letter and give an example of when it protects you.

Strong answer: ACID is a set of four guarantees.

Atomicity means “all or nothing.” If a money transfer consists of debiting one account and crediting another, a failure between the two UPDATE statements must not leave the money in an intermediate state. For an order, it means the order, its items, and the stock reduction should all commit together or all roll back together.

Consistency means that after a transaction, the database must once again be in a valid state: foreign keys point to existing rows, NOT NULL fields are filled, CHECK are satisfied, and business still hold. A useful clarification is that the database protects rules expressed in the schema or through correct transactional logic.

Isolation means concurrent transactions shouldn't see one another's unsafe intermediate states. For example, if one transaction hasn't committed a payment yet, another shouldn't make final decisions based on that unfinished draft. Isolation levels control how strictly transactions are separated.

Durability means that if the database has acknowledged COMMIT, the result must survive a failure and restart. A committed payment must not disappear after the server crashes.

Interview question: How does PostgreSQL provide durability?

Strong answer: With — the Write-Ahead Log. Changes are written to the log first, and on COMMIT, PostgreSQL must reliably flush WAL to disk before the client receives confirmation that the transaction committed. The table and index pages themselves can be written later in the background. If a failure occurs after COMMIT, PostgreSQL reads WAL during startup and restores the committed changes.

One useful caveat: with typical PostgreSQL settings, COMMIT waits for WAL to be written safely; settings such as asynchronous commit can change the tradeoff between speed and the risk of losing the most recent transactions.

Another common question: Which ACID property handles the situation “the server crashed halfway through placing an order”?

Strong answer: If the transaction hadn't committed yet, Atomicity protects against a partial state: the changes roll back together. If the transaction had already received COMMIT, Durability protects the result from being lost.

Check yourself
The server crashed after creating the order but before reducing product stock. Which ACID property prevents the database from being left in this partial state?
Practice: solve the tasks
Solved 0 of 2 · any 1 is enough to pass