First, the key terms.
- Atomicity
- A transaction’s changes are treated as a unit rather than partially committed.
- Invariant
- A condition that must remain true across valid system states.
The idea, explained
Transactions are useful when multiple records must change consistently. A database can hide uncommitted changes from other transactions according to its isolation rules. Applications still need appropriate constraints and error handling: a transaction does not automatically express every business rule.
Describe the protected condition
For a transfer, the intended invariant might be that the combined account balance does not change. Debiting one account and crediting another are one logical operation even though they require several database actions.
Consider failure between actions
If the process crashes after the debit, separate committed statements can leave an incomplete transfer. A transaction lets the database commit the related changes together or roll them back under its guarantees. Isolation and external side effects still need separate thought.
Follow a worked example.
A transfer reduces one balance and increases another. If the second operation fails, committing only the first would leave an inconsistent result. A transaction can roll back both operations instead. The application must separately enforce sufficient funds and authorization.
Walk it through, one step at a time
- Account A has $100 and B has $20. Transfer $30: A should become $70 and B $50.
- The combined total remains $120. A crash before transaction commit should not leave only the debit visible as a committed transfer.
- Sending an external email is not automatically rolled back with SQL. Use a suitable delivery pattern for external actions.
Where people get stuck
Two successful database writes are not automatically one atomic operation unless they are grouped using the database’s transaction mechanism.
Now try it yourself.
1. Check the core idea
What should happen when the second operation in an atomic transfer fails?
Reveal the answer & reasoning
The transaction should not leave the first operation committed on its own; the group must be rolled back or otherwise handled consistently.
2. Apply what you learned
Does a database transaction automatically undo an email already sent by a provider?
Reveal the answer & reasoning
No. The provider is a separate system. Transactional database state and external side effects require coordination, retries and deduplication.