Imagine transferring $100 from Account A to Account B.
Two operations must happen:
Subtract $100 from A Add $100 to B What happens if the first succeeds but the second fails?
Money disappears.
This is where database transactions become important.
What Is a Transaction?
A transaction groups multiple database operations into a logical unit.
Conceptually:
BEGIN Subtract money from A Add money to B COMMIT If something goes wrong:
ROLLBACK The database attempts to return to the previous consistent state.
ACID
Transactions are commonly discussed using ACID:
Atomicity
All operations succeed, or none do.
Consistency
The database moves from one valid state to another.
Isolation
Concurrent transactions shouldn't incorrectly interfere with one another.
Durability
Committed changes should survive failures according to the database's guarantees.
Why Transactions Matter
Consider an e-commerce order.
You might need to:
Create order Reserve inventory Create payment record If these operations are tightly coupled and one fails, the application may need transactional behavior.
Transactions Aren't Free
Transactions can introduce:
- Locking
- Contention
- Complexity
- Performance costs Therefore, they should be used intentionally.
Distributed Transactions Are Harder
When operations span multiple independent services, maintaining atomicity becomes significantly more complicated.
Architectures may instead use patterns such as:
Saga Outbox Pattern Event-driven workflows Final Thoughts
Transactions protect data integrity.
Whenever multiple changes must behave like one logical operation, understanding transactions becomes essential.
