A customer transfers 5,000 DZD from a savings account to a current account. Your code runs two statements: subtract from one balance, add to the other. Now imagine the server crashes between them. The money has left one account and never arrived in the other. Or imagine two transfers from the same account running at the same moment, both reading the old balance and both deciding there is enough money.
Transactions exist to make these problems go away. This article explains what a transaction is, what each letter of ACID really promises, and how to use transactions well.
What a transaction is
A transaction is a group of database operations that the database treats as a single unit. You start it, run your statements, and then either commit (make all the changes permanent) or roll back (undo all of them).
BEGIN;
UPDATE accounts SET balance = balance - 5000 WHERE id = 1;
UPDATE accounts SET balance = balance + 5000 WHERE id = 2;
COMMIT;
If anything goes wrong before COMMIT, whether an error in a statement, a failed check in your application or a crash, the database returns to the state it was in before BEGIN. Other sessions never see a half-finished transfer.
In application code it usually looks like this (Python with a DB-API driver):
with conn: # commits on success, rolls back on exception
cur = conn.cursor()
cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (5000, 1))
cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (5000, 2))
The guarantees a transaction gives are summarized by four letters: ACID.
A is for Atomicity
Atomic means indivisible. Either every change in the transaction takes effect, or none does. There is no state where the first UPDATE happened and the second did not.
How it works: the database records what each transaction changes (in PostgreSQL, through row versions and a log; in InnoDB, with undo logs). On rollback or after a crash, changes from transactions that never committed are discarded or undone.
Note what atomicity is not about: it says nothing about other transactions running at the same time. That is isolation.
C is for Consistency
Consistency means a transaction moves the database from one valid state to another valid state. "Valid" is defined by your rules: constraints such as NOT NULL, UNIQUE, foreign keys and CHECK (balance >= 0), plus business rules that live in your code.
The database enforces the constraints you declare. If the transfer would make a balance negative and you have a CHECK constraint, the statement fails and the transaction cannot commit. But the database cannot know rules you never told it about. If your rule is "the sum of all balances never changes", it is your code that must keep it, by writing transactions that respect it. In that sense, C is partly the application's job, helped by the other three letters.
I is for Isolation
Isolation is about concurrency. Many transactions run at the same time, and isolation controls how much they can see of each other's unfinished work.
The ideal is serializability: the result is the same as if transactions ran one after another in some order. In the double-spend example, two withdrawals from the same account would behave as if one ran fully before the other, and the second would see the reduced balance.
Full serializability costs performance, so databases offer weaker isolation levels: Read Uncommitted, Read Committed, Repeatable Read and Serializable. Each one allows certain anomalies, such as non-repeatable reads or phantom rows, in exchange for more concurrency. Many databases default to Read Committed (PostgreSQL) or Repeatable Read (MySQL InnoDB), not Serializable. This is the letter developers most often misunderstand, and it deserves its own article.
Databases implement isolation with locks, with multi-version concurrency control (MVCC), or with a mix of both.
D is for Durability
Durability means that once the database says "committed", the change survives a crash or power loss.
The usual mechanism is the write-ahead log (WAL). Before confirming a commit, the database writes a record of the changes to a log file and forces it to stable storage with fsync. The actual table pages can be written later. After a crash, the database replays the log to restore every committed change.
Durability has limits. If the disk itself is lost, you need replicas and backups. Some settings trade durability for speed, such as PostgreSQL's synchronous_commit = off or relaxed log flushing in InnoDB, where the last moments of commits can be lost in a crash. Know which settings your database runs with.
Using transactions well
Keep transactions short. A transaction may hold locks or keep old row versions alive. Do not call an external API, send an email or wait for user input inside one.
Do the read and the write in the same transaction. "Read balance, check in code, then update" is only safe if the read and update are protected together, for example with SELECT ... FOR UPDATE, a stricter isolation level, or a single conditional statement:
UPDATE accounts SET balance = balance - 5000
WHERE id = 1 AND balance >= 5000;
-- 0 rows updated means not enough money
Handle failures and retries. Under higher isolation levels, the database may abort a transaction with a serialization failure or deadlock error. The correct response is to retry the whole transaction.
Watch autocommit. Most drivers and the database shell run each statement in its own transaction unless you start one. Two statements that must go together need an explicit transaction.
Common mistakes
- Assuming ACID means no concurrency bugs. With the default isolation level, lost updates and other anomalies are still possible. Check what your level guarantees.
- Catching an error and carrying on. In PostgreSQL, after an error the transaction is aborted and later statements fail until you roll back.
- Long transactions in web requests. They hold resources and, in MVCC databases, prevent cleanup of old row versions.
- Spreading one logical operation across several transactions. If two writes must happen together, put them in one transaction, or design for partial failure explicitly.
- Expecting ACID across services. A transaction covers one database. Coordinating changes across services needs other patterns, such as the outbox pattern or sagas.
In short
- A transaction groups operations into one unit: commit all or roll back all.
- Atomicity: all or nothing. Consistency: valid state to valid state, using your constraints. Isolation: concurrent transactions do not trip over each other, to the degree your isolation level allows. Durability: committed means saved, thanks to the write-ahead log.
- Keep transactions short, read and write in the same transaction, and retry on serialization failures.
Originally published at abdeldjalilchougui.biz.
Top comments (0)