ACID in Practice: What Breaks at Each Letter
What actually goes wrong when a transaction gives up atomicity, consistency, isolation or durability, with the PostgreSQL settings that decide it.
Knowing the acronym is the easy part
Atomicity, consistency, isolation, durability. Most developers can recite it, and then they ship a counter that is off by one under load. The definitions are fine. What’s missing is the link from each letter to the bug you get without it, so that’s what this article is about, one letter at a time, using PostgreSQL.
Atomicity
A transaction either happens completely or not at all. Take a transfer that debits one account and credits another.
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
-- the server crashes here
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
Without a transaction, a crash between the two statements makes 100 disappear. Wrap both in BEGIN and COMMIT and PostgreSQL rolls the first one back on recovery.
That part is obvious. The version that slips into real code is an ORM where every save() commits on its own.
await order.save(); // committed
await inventory.save(); // if this throws, the order is already saved
await payment.save();
await db.transaction(async (tx) => {
await tx.insert(orders).values(order);
await tx.update(inventory).set({ stock: sql`stock - 1` });
await tx.insert(payments).values(payment);
});
The first three lines are three transactions. The block below them is one.
Consistency
Consistency means a transaction moves the database from one valid state to another, and “valid” means whatever your constraints say. PostgreSQL only enforces the rules you wrote down. Without CHECK (balance >= 0), a balance can go negative inside a perfectly atomic transaction.
ALTER TABLE accounts ADD CONSTRAINT positive_balance CHECK (balance >= 0);
With the constraint in place, a transfer that would overdraw the account fails and rolls back as a whole. So I put invariants in the schema whenever I can. Application code can be skipped by a migration script, a manual query or another service. A constraint can’t.
Isolation
Isolation decides what concurrent transactions see of each other, and most of the surprises live here. PostgreSQL’s default level is READ COMMITTED, which re-reads committed data on every statement.
Non-repeatable reads
BEGIN;
SELECT balance FROM accounts WHERE id = 'A'; -- 1000
-- another transaction sets it to 500 and commits
SELECT balance FROM accounts WHERE id = 'A'; -- 500
COMMIT;
The same query returns two different values inside one transaction. Anything that reads, computes and then reads again on the assumption that nothing changed is exposed to this. A report that sums several queries is the classic case.
Phantoms
The same thing happens to whole sets of rows. SELECT count(*) FROM orders WHERE status = 'pending' returns 5, another transaction inserts a pending order, and the same count returns 6.
Lost updates
This is the one I see most.
-- Transaction A -- Transaction B
SELECT stock FROM products WHERE id = 1; SELECT stock FROM products WHERE id = 1;
-- 10 -- 10
UPDATE products SET stock = 9 WHERE id = 1;
UPDATE products SET stock = 9 WHERE id = 1;
Two items sold and the stock went down by one. Both transactions read 10 and both wrote 9. There are two simple fixes. Let the database do the arithmetic, so there is no read before the write.
UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0;
Or put a version number on the row and make every update check it. That’s optimistic concurrency, and it’s what the services in Loom do with their Postgres rows. An update that read an old version changes zero rows, and the service knows it lost the race.
UPDATE tickets SET price = 40, version = version + 1 WHERE id = 7 AND version = 3;
Stronger levels
REPEATABLE READ takes a snapshot when the transaction starts, so every read sees the database as of that moment. When two transactions try to change the same row, one of them fails with could not serialize access due to concurrent update.
SERIALIZABLE goes further. The result has to equal some order of running the transactions one by one, and PostgreSQL aborts a transaction when it detects that this could be broken. Under high concurrency you get more aborts, so both levels need a retry around the transaction. The error code to retry on is 40001.
Durability
Once a commit returns, the data survives a crash. PostgreSQL gets there with its write-ahead log. The change is written to the log and flushed to disk before the commit is confirmed, and after a crash the log is replayed. (I used the same idea in Crystal, where Raft’s safety depends on it.)
There is one switch to know about. With synchronous_commit = off, PostgreSQL confirms the commit before the flush. It’s faster, and the last few commits can disappear in a crash. That’s a fair trade for analytics events and a bad one for payments, and it can be set per transaction.
SET LOCAL synchronous_commit = off;
What I check in code review
- Related writes sit inside one explicit transaction.
- Counters are updated with
x = x - 1, never read and then written. - Anything that reads and then writes based on what it read uses
SELECT ... FOR UPDATE, a version column, or a stricter isolation level. - Invariants live in the schema as constraints.
- Code that runs at
REPEATABLE READorSERIALIZABLEretries on40001.