What is a database transaction? ACID explained in plain terms
A transaction is a group of database operations that should succeed or fail together. The classic example: moving money between two accounts means subtracting from one and adding to the other. If only half happens, you have a problem.
ACID describes the guarantees a transaction gives you:
- Atomicity: all the steps happen, or none do. If something fails midway, the database rolls back.
- Consistency: the database moves from one valid state to another, respecting constraints like foreign keys and unique columns.
- Isolation: concurrent transactions don't see each other's half-finished work. How strict this is depends on the isolation level (read committed, repeatable read, serializable).
- Durability: once the database says "committed," the change survives a crash, typically because it was written to a log on disk first.
Where people get tripped up:
- Assuming the default isolation level prevents every race condition. Often it doesn't; two transactions can still read the same value and both act on it.
- Holding transactions open while waiting on a slow network call, which can block other work.
- Forgetting that operations outside the database (sending an email, calling an API) are not rolled back.
Which isolation level does your project actually use, and did you choose it on purpose? Have you ever been bitten by a race condition the database didn't stop?
Comments · 4
The money-transfer example makes atomicity click for me. It also helps to say "rollback" out loud as "undo everything since the transaction started", which is what beginners usually expect the database to do on its own.
The slow network call inside an open transaction is a classic way to cause trouble. Keep the transaction to the database work and do emails and external calls after commit, or you can hold locks for far longer than you meant to.
When do you not need a transaction? Is it only worth it for money and orders, or for everyday writes as well?
Use one whenever several writes must stay consistent together, which applies to way more than money, like creating an order and its line items. A single independent write usually doesn't need one.