Database Transaction Atomicity and Consistency: How They Work
Learn how database transactions use logging, write-ahead logging, crash recovery, and concurrency control to support atomicity and consistency. This article explains the limits of ACID guarantees, common concurrency anomalies, and the constraints, retry handling, and transaction boundaries needed for reliable transfers and cross-system workflows.
1. Atomicity Is Not the Same as Consistency
A common misconception about database transactions is that “all operations succeed or fail together” means “the data must be correct.” The first statement describes atomicity; the second concerns consistency. They are related, but they are not equivalent.
Consider a transfer that deducts 100 from account A and adds 100 to account B. If the system fails after the debit but before the credit, the transaction has executed only partially. Atomicity requires the database not to retain this intermediate state as the transaction’s final outcome.
Now suppose the application deducts 100 from A but adds only 90 to B within the same transaction. Both updates can succeed and commit, yet the result violates the business rule that an internal transfer must preserve the total amount of money.
Understanding transactions therefore requires separating two questions:
- Is execution complete? Does a group of operations take effect as an indivisible unit?
- Is the result correct? Does the resulting data still satisfy the defined constraints and business rules?
Logging and recovery primarily address the first question. The second also requires correct application logic, database constraints, and appropriate concurrency control.
2. What the Four ACID Properties Actually Mean
Transactions are commonly described through the four ACID properties. These properties are distinct, not interchangeable.
Atomicity: No Partially Committed Results
Atomicity requires a transaction’s operations to commit or roll back as a unit. A successful statement does not mean the entire transaction has succeeded. Only after commit completes can its results be treated as committed under the database’s guarantees.
Atomicity does not mean intermediate states never exist during execution. Internally, a database may modify multiple pages sequentially or create several record versions. What matters is how those changes become visible and how they are undone or excluded if the transaction fails.
Consistency: Preserving Defined Invariants
Consistency means the database satisfies its predefined integrity constraints and business invariants before and after a transaction.
Typical rules include:
- Account balances must not be negative.
- Primary keys must be unique.
- Detail records must reference existing parent records.
- An internal transfer must not create or destroy money.
- A confirmed order must have a valid inventory reservation.
Some rules can be expressed through NOT NULL, unique, foreign key, and check constraints. Others span multiple rows, tables, or business processes and require cooperation between the application and the database.
This meaning of consistency concerns transaction correctness. It should not be confused with strong consistency or eventual consistency between distributed replicas.
Isolation: Controlling Interference Between Concurrent Transactions
When transactions run concurrently, their reads and writes can affect one another. Isolation determines which states a transaction can observe from other transactions and whether conflicting operations must wait, fail, or be retried.
Atomicity ensures that an individual transaction does not partially commit. By itself, it does not guarantee correct business outcomes when multiple transactions interleave.
Durability: Preserving Acknowledged Commits
Durability requires a successfully committed transaction to remain recoverable within the system’s stated failure scope.
This usually depends on durable logging and recovery mechanisms. The failures a system can withstand also depend on storage reliability, log-flushing policies, replication, and backup design. A process crash, a machine power failure, and the loss of an entire storage device are not equivalent events.
3. How Logging Supports Atomicity
Databases generally do not write every affected data page to stable storage immediately after each statement. To reduce random writes and improve throughput, changes often occur first in memory buffers, with background processes writing pages later.
This creates two important possibilities:
- Data pages modified by committed transactions may not yet be on stable storage.
- In some implementations, pages containing uncommitted changes may be written before the transaction commits.
Data files alone therefore cannot reliably identify which changes should be retained and which must be removed. The database needs additional recovery information.
UNDO: Removing Changes That Must Not Survive
UNDO information allows the database to restore an earlier state. It might contain previous field values or enough information to reverse an operation.
If a transaction fails, the database can use this information to remove completed changes so that no partial result remains.
UNDO is not necessarily a simple file of old values. Implementations may use logical records, physical records, version chains, or other recovery structures. In some systems, undo information also supports multiversion reads.
REDO: Reconstructing Changes That Must Survive
REDO information allows the database to reproduce changes that have not yet reached the data files.
REDO primarily supports durability. However, redo logs should not be understood as containing only committed transactions. Some recovery algorithms replay part of the execution history, potentially including uncommitted changes, and then undo the unfinished transactions.
Databases Do Not All Use the Same Recovery Design
“UNDO reverses changes; REDO reapplies changes” is a useful framework, but it is not a mandatory architecture for every database.
A system that prevents uncommitted pages from being written, or that uses shadow paging or copy-on-write, may not need traditional UNDO during recovery.
The essential requirement of atomicity is that failed transactions leave no partially committed result—not that the database has a log file with a particular name.
4. Write-Ahead Logging: Make Changes Recoverable Before Writing Data
Recovery logs work only when the database follows a strict write order. A common mechanism is write-ahead logging, or WAL.
Its central rule is:
Before a data change reaches stable storage, the corresponding recovery log information must be durably stored.
Otherwise, a power failure could leave a changed data page on disk while its recovery information exists only in lost memory. The database might then be unable to redo or undo the change.
Under a commit mode that promises durability, the database must also persist the log information required for commit before reporting success. Even if the data pages have not all been written, recovery can reconstruct the committed result.
A simplified sequence is:
- The transaction modifies in-memory data pages and generates log records.
- The database writes logs to stable storage according to the write-ahead rule.
- At commit, it persists the required log records and commit information.
- It reports successful commit to the client.
- Background processes gradually write the data pages.
Real systems may use batch flushing or group commit to reduce synchronization overhead. These optimizations do not eliminate the ordering requirements needed for recovery.
5. How Crash Recovery Restores a Valid State
After a crash, in-memory information is lost, and the data files may contain only some of the changes made before the failure. Recovery uses logs, transaction status, and checkpoints to determine which changes should remain.
A common log-based recovery model has three phases.
Analysis: Determine the Recovery Scope
The database uses checkpoint information and subsequent logs to identify transactions that were still active, pages that may need recovery, and where log scanning should begin.
Checkpoints generally limit recovery work. They do not mean that all transactions have committed, nor that every log record preceding a checkpoint can be deleted unconditionally.
REDO: Restore Missing Changes
The database uses log records to reproduce changes that are not yet reflected in the data files.
To avoid applying an operation twice, some implementations compare log-position markers with page state to determine whether a change has already been applied. Recovery must ensure that repeated application does not corrupt the result.
UNDO: Handle Unfinished Transactions
For transactions that had not committed at the time of the crash, the database must undo their effects or use version and visibility rules to prevent those effects from becoming valid committed state.
This is a representative recovery model, not a universal sequence. Databases differ in their phases, log structures, and processing order. “Redo first, then undo” should not be treated as a fixed procedure used by every system.
Recovery also has an important limit: it restores the state guaranteed by the database’s mechanisms. It does not automatically detect or repair incorrect business calculations or concurrency outcomes that violated application invariants before the crash.
6. Why Atomicity Does Not Prevent Concurrency Errors
Suppose account A starts with a balance of 1,000. Two transactions add 100 and 200 respectively. The application reads the balance, calculates a new value, and overwrites the stored balance.
| Execution order | Transaction 1 | Transaction 2 |
|---|---|---|
| 1 | Reads balance: 1,000 | |
| 2 | Reads balance: 1,000 | |
| 3 | Writes 1,100 | |
| 4 | Writes 1,200 | |
| 5 | Commits | Commits |
Without appropriate locking, version checks, or conflict rejection, the final balance may be 1,200 instead of 1,300. This is a lost update.
Both transactions executed fully and committed, so atomicity was not violated. The error arose because their concurrent operations were not sufficiently coordinated.
This outcome does not occur in every database or at every isolation level. Some implementations make conflicting operations wait; others reject them. An isolation-level name alone is not enough to predict every specific execution behavior.
Prefer Relative Updates Inside the Database
For simple increments and decrements, avoid reading a value in the application and then overwriting it:
UPDATE accountsSET balance = balance + 100WHERE account_id = :account_id;
This performs the calculation and write within one database statement. Common databases coordinate concurrent updates to the same record, avoiding the direct overwrite problem shown above.
However, a single relative update does not automatically enforce every business rule involving multiple rows or tables.
Use Pessimistic Locking for Read-Based Decisions
If the application must read a state and then decide how to modify it, a locking read can make conflicting transactions wait within the appropriate scope.
Lock duration, access order, and deadlocks must also be considered. For transfers involving multiple accounts, acquiring locks in a consistent account-ID order can reduce the risk of transactions waiting on one another in opposite directions.
Use Optimistic Concurrency Control to Detect Conflicts
Another approach is to add a version field:
UPDATE accountsSET balance = :new_balance,version = version + 1WHERE account_id = :account_idAND version = :old_version;
If the affected-row count is zero, the record may have changed, or the target condition may no longer hold. The application must not treat this as success. It should reread the data, recalculate, or report a conflict.
A retry must rerun the necessary transaction logic, rather than repeatedly submitting a result calculated from stale data.
7. MVCC Does Not Automatically Enforce Every Consistency Rule
Multiversion concurrency control, or MVCC, retains multiple versions of data and provides reads according to a transaction’s visibility rules.
It can reduce blocking between ordinary reads and writes. It does not mean that every read is lock-free or that concurrency anomalies are impossible.
For example, a system requires at least one person to remain on call. Two transactions each read that two people are currently on call, then each marks a different person as off call. Because they modify different records, their writes may not directly conflict. The final state may leave nobody on call.
This anomaly is commonly called write skew.
A consistent snapshot is therefore not sufficient to preserve every cross-record invariant. Depending on the database’s capabilities and the access pattern, possible approaches include:
- Using serializable isolation.
- Locking the relevant records or a shared coordination record.
- Expressing the rule through database constraints.
- Adjusting the data model to reduce cross-record decisions.
Serializable isolation guarantees that committed results are equivalent to some serial execution order. It still depends on each transaction having correct logic, and it may resolve conflicts by aborting transactions.
8. Designing a Complete Transfer Transaction
A reliable transfer must address transaction boundaries, business conditions, and concurrency conflicts together.
The following SQL is illustrative. Parameter syntax and error handling should be adapted to the actual database access method.
BEGIN;UPDATE accountsSET balance = balance - :amountWHERE account_id = :source_idAND balance >= :amount;-- The application must verify that exactly one row was affected.-- Otherwise, roll back and do not proceed with the credit.UPDATE accountsSET balance = balance + :amountWHERE account_id = :target_id;-- The application must verify that exactly one row was affected.-- Otherwise, roll back.INSERT INTO transfer_records(request_id, source_id, target_id, amount)VALUES(:request_id, :source_id, :target_id, :amount);COMMIT;
Several additional requirements are essential.
Validate the Amount
Reject zero or negative amounts, and explicitly decide whether transfers to the same account are allowed.
Store money using a fixed-point type with suitable precision or an integer representing the smallest currency unit, rather than floating-point values.
Abort the Entire Transaction When a Check Fails
A conditional update affecting zero rows usually does not automatically raise an error. If the application ignores the row count, it may still commit an invalid result.
Add Database Constraints
A unique constraint on the request identifier can prevent duplicate execution. Balance and amount fields should also have appropriate constraints based on the business rules.
Handle Deadlocks and Transaction Aborts
Two transactions transferring money in opposite directions may deadlock. The application should use bounded retries for retryable errors and rerun the complete transaction.
Handle an Uncertain Commit Result
A client timeout during commit does not prove that the database failed to commit. Use the unique request identifier to query the final outcome rather than blindly retrying and risking a duplicate debit.
9. What Lies Outside a Database Transaction?
A database transaction generally governs only the data resources participating in it. External API calls, notifications, and writes to an independent messaging system are not automatically reversed when the database rolls back.
For example, if an application sends a “transfer successful” notification before committing and the transaction then fails, the notification no longer matches the actual state.
A common approach is to write both the business data and a pending event within the same database transaction. After commit, a separate worker reads and sends the event.
Delivery must handle retries and duplicates, and consumers must be idempotent. This approach coordinates business completion across system boundaries; it is not a capability inherently provided by an ordinary single-database transaction.
Distributed transactions likewise require separate design. Atomic local transactions on multiple nodes do not automatically make the overall cross-node operation atomic.
10. Consistency Requires Multiple Mechanisms Working Together
Reliable transaction processing depends on several complementary layers:
- Logging and recovery allow failed work to be reversed and committed work to be restored.
- Write-ahead logging rules preserve enough recovery information before data reaches stable storage.
- Concurrency control and isolation levels limit interference between transactions.
- Database constraints reject invalid states that can be explicitly expressed.
- Application logic defines and maintains more complex business invariants.
- Idempotency, retries, and outcome queries handle duplicate requests and uncertain commits.
- Cross-system coordination addresses operations beyond a single database transaction’s scope.
Atomicity answers, “Can this operation be left half-complete?” Consistency answers, “Does the completed result still obey the rules?” One does not automatically establish the other.
Reliable data processing requires correct business operations within appropriate transaction boundaries, supported by suitable constraints, isolation, and failure handling.
