How Write-Ahead Logging and Two-Phase Locking Guarantee Atomicity and Isolation in a Relational Database
Relational databases rely on Write-Ahead Logging to prevent data loss during crashes and Two-Phase Locking to manage concurrent transactions. Understanding these mechanisms reveals the fundamental trade-offs between write throughput, isolation, and recovery time.
By Lila Morgan
- Pessimistic Concurrency Advocates
- Prioritize guaranteed transaction completion and strict isolation over raw parallel throughput.
- Optimistic Concurrency Advocates
- Prioritize lock-free parallel execution, accepting higher abort rates in exchange for lower latency.
- Durability Engineers
- Focus on the physical storage layer, optimizing sequential I/O to ensure data survives hardware failures.
Perspectives this story doesn't cover
- Hardware Manufacturers
- NoSQL Database Architects
The competing cases
Pessimistic Concurrency (Two-Phase Locking)
Assumes transactions will conflict and locks data upfront to guarantee isolation.
FOR: Guarantees conflict serializability without wasting CPU cycles on aborted transactions. AGAINST: Imposes severe latency overhead under high contention due to lock queueing delays. EVIDENCE: By forcing a transaction to acquire all necessary locks during its growing phase before releasing any in its shrinking phase, 2PL mathematically prevents isolation anomalies. FITS WELL WHEN: Write contention is high and the computational cost of rolling back a complex transaction is prohibitive. DOES NOT FIT WHEN: Workloads are overwhelmingly read-heavy, making conflicts statistically rare and lock acquisition an unnecessary bottleneck.
Optimistic Concurrency Control (OCC)
Assumes conflicts are rare, allowing transactions to execute freely and validating them only at commit time.
FOR: Eliminates lock queueing delays, allowing massive parallel throughput for non-conflicting queries. AGAINST: Suffers from crippling abort rates when multiple transactions frequently target the same rows. EVIDENCE: Transactions read data and perform computations in a private workspace, entering a validation phase only at the end; if a conflict is detected, the transaction is discarded and retried. FITS WELL WHEN: Workloads are overwhelmingly read-heavy or when transactions touch disjoint sets of data, keeping the abort rate near zero. DOES NOT FIT WHEN: Operating in highly contested environments like inventory management or financial ledgers, where constant retries consume more resources than upfront locking.
Append-Only Durability (Write-Ahead Logging)
Prioritizes immediate write throughput by logging changes sequentially before modifying the actual database files.
FOR: Drastically reduces write latency by converting slow random disk I/O into fast sequential appends. AGAINST: Increases crash recovery time, as the database must replay the sequential log before accepting new queries. EVIDENCE: Writing directly to a database's main storage files requires random I/O, which risks corrupting the database if a crash occurs mid-write; WAL bypasses this by appending every change to a log file first. FITS WELL WHEN: Deployed in almost all modern relational databases, because the continuous benefit of high write throughput vastly outweighs the rare penalty of a slower crash recovery. DOES NOT FIT WHEN: Used in niche embedded systems where instantaneous reboot times are strictly prioritized over write speed.
The binding constraint for any relational database is that the underlying storage medium must actually persist sequential writes before acknowledging them, and that concurrent operations can be mathematically serialized. If a disk lies about an fsync completion, or if 2 processes overwrite the same memory simultaneously, the entire illusion of a reliable database collapses.
While modern database vendors often market "infinite scale" and "zero-latency" transactions, the actual capability relies on 2 foundational algorithms shipped decades ago: Write-Ahead Logging (WAL) and Two-Phase Locking (2PL). Together, they enforce the 4 core properties of the ACID (Atomicity, Consistency, Isolation, Durability) model.[3][5]
Atomicity dictates a 100 percent success or failure rate for a transaction—there is no partial completion. If a server loses power halfway through transferring funds, the database must revert to its exact state before the transaction began, ensuring 0 data loss.
The mechanism that guarantees this is Write-Ahead Logging. As Bytebase outlines, WAL operates on a strict "log-first, data-second" rule. Before any changes are applied to the main database files, they are appended to a persistent log.[4]
This design solves a critical hardware bottleneck. Writing directly to database tables requires random disk I/O, which is physically slow. By appending changes to a sequential log, WAL converts random writes into fast sequential writes, drastically improving throughput while guaranteeing that a record of the transaction exists on disk.
"Operations included in a transaction either all succeed or none succeed despite temporary failures of the process/machine running the DB," notes the syllabus for Columbia University's Course 4113 on distributed systems. If a crash occurs, the database simply replays the sequential log upon reboot to restore the exact state.[1]
If a crash occurs, the database simply replays the sequential log upon reboot to restore the exact state.
While WAL handles the physical reality of crashes, Two-Phase Locking (2PL) manages the logical chaos of concurrency. In a system operating 24 hours a day, 7 days a week, thousands of users might attempt to read and write the exact same rows simultaneously.[2]
Marketing materials frequently promise "perfect isolation," but the engineering reality requires strict mathematical serializability—the guarantee that the final database state looks exactly as if the transactions were executed 1 by 1, in a serial order.
In a 1997 paper for Carnegie Mellon University, Michael Franklin explains that the responsibility for maintaining this isolation resides in the concurrency control software. "Recovery ensures that the database is fault tolerant; that is, that the database state is not corrupted as the result of a software, system, or media failure," Franklin writes, separating the roles of WAL and 2PL.[2]
2PL achieves serializability by dividing a transaction into exactly 2 distinct phases: a growing phase and a shrinking phase. During the 1st phase, the transaction acquires locks on the data it needs (read or write) but cannot release any.[2]
Once the transaction reaches its peak and begins its 2nd phase—the shrinking phase—it can release locks but is strictly forbidden from acquiring new ones. This mathematical strictness prevents the classic "deadlock" scenarios where transactions wait on each other infinitely.
However, this pessimistic approach comes with a severe performance trade-off. Because 2PL assumes conflicts will happen, it forces transactions to wait in line. Under high contention, this locking overhead can throttle the database's throughput, leaving CPU cycles idle while processes wait for lock releases.
The alternative is Optimistic Concurrency Control (OCC), which assumes conflicts are rare. OCC allows transactions to execute without locks, validating them only at the very end. If a conflict is detected during validation, the transaction is simply aborted and retried.
The choice between 2PL and OCC depends entirely on the workload's conflict rate. In environments with heavy write contention, the cost of constantly aborting and retrying OCC transactions quickly exceeds the overhead of 2PL's upfront locking. Conversely, read-heavy workloads often benefit from the lock-free nature of OCC.
Key takeaways
- Write-Ahead Logging (WAL) ensures durability by appending changes to a sequential log before modifying the main database.
- WAL improves write throughput by converting slow random disk I/O into fast sequential I/O.
- Two-Phase Locking (2PL) guarantees isolation by forcing transactions to acquire all locks before releasing any.
- Optimistic Concurrency Control (OCC) offers a lock-free alternative to 2PL but suffers from high abort rates under heavy write contention.
- 100%
- Required transaction success/failure rate (Atomicity)
- 2
- Distinct phases in 2PL (Growing and Shrinking)
- 24/7
- Uptime requirement for mission-critical databases
- 0
- Acceptable data loss under ACID guarantees
Sources
[1]Columbia UniversityPessimistic Concurrency AdvocatesDistributed Systems 1, Columbia Course 4113, Implementing Transactions. (Single Node).
Read on Columbia University →
[2]CMU School of Computer SciencePessimistic Concurrency Advocates1 Introduction (Serializability, Two-Phase Locking, Write Ahead Logging)
Read on CMU School of Computer Science →
[3]IEEE Technology NavigatorOptimistic Concurrency AdvocatesTransaction databases
Read on IEEE Technology Navigator →
[4]BytebaseDurability EngineersWhat is Write Ahead Logging (WAL)
Read on Bytebase →
[5]Varsity TutorsDurability EngineersUnderstand transactions conceptually (BEGIN/COMMIT/ROLLBACK) (intro)
Read on Varsity Tutors →
[6]Factlen Editorial TeamDurability EngineersSynthesis by Factlen editorial team
Read on Factlen Editorial Team →
Comments
More in Content Types
See all →Social Cognition
How Perceptual Salience and Effortful Correction Separate Dispositional from Situational Attributions in Social Perception
7 sources
Cognitive Architecture
How the Primacy Effect and the Recency Effect Separate Long-Term from Working Memory in Recall
5 sources
GNSS Architecture
How Pseudorange and Trilateration Separate the GPS Receiver's Clock Error from the Satellite's Position
6 sources
Cognitive Science
The Science of Steelmanning: How Constructive Disagreement Upgrades Our Thinking
4 sources
Every angle. Every day.
Get Content Types stories with full source coverage and perspective breakdowns delivered to your inbox.




