How Two-Phase Commit Protocols Coordinate Distributed Database Writes to Guarantee Atomicity
Distributed databases use a strict two-step voting mechanism to ensure data is never partially written during a network failure. The protocol forces participating servers to lock resources and cast binding votes before finalizing a transaction.
By Wei Zhang
Share this story
In short
- Two-phase commit protocols guarantee that distributed database transactions are either fully applied across all servers or completely discarded.
- Participants must lock their local data and cast a binding vote during the prepare phase, promising they can complete the write.
- The protocol's reliance on a central coordinator creates a blocking vulnerability, where a crashed coordinator can freeze locked resources indefinitely.
Two-phase commit protocols coordinate distributed database writes by forcing every participating server to cast a binding vote on whether they can complete the transaction, guaranteeing that either all servers commit the data or none do. This mechanism prevents partial updates when a network fails mid-transaction.[1]
While cloud providers frequently market their distributed databases as seamlessly scalable and infinitely available, the underlying physics of data consistency remain rigid. When a user transfers funds between two accounts stored on different servers, the system cannot simply deduct the money from one and assume the other will receive it.[1][5]
If a power failure or network partition severs the connection exactly between those two operations, the money vanishes. To prevent this, computer scientist Jim Gray formalized the two-phase commit protocol in 1978, establishing a mathematical guarantee of atomicity across distributed systems.[3]
"The essential property of a transaction is that it is an all-or-nothing proposition," Gray wrote in his foundational paper on database operating systems. "Either all the actions are completed, or the transaction has no effect."[3]
To achieve this, the protocol designates one server as the coordinator, which manages the transaction across all other participating nodes. The coordinator does not simply command the participants to write the data; it orchestrates a strict, two-step voting process.[2]
The Prepare and Commit Phases
During the first phase, known as the prepare phase, the coordinator sends a message asking each participant if it is ready to commit the transaction. The participants do not apply the changes to their active tables yet, but they must guarantee they have the ability to do so.[2][4]
To make this guarantee, each participant writes the proposed changes to a durable write-ahead log on its local disk. It also acquires exclusive locks on the specific rows of data involved, preventing any other transaction from modifying them while the vote is pending.[4]
Once the data is safely on disk and the locks are secured, the participant replies to the coordinator with a "Yes" vote. This vote is a binding contract; the participant is mathematically promising that it will not crash or fail to apply the transaction if instructed to proceed.[2]
If a participant cannot secure the locks, or if its disk is full, it replies with a "No" vote. The coordinator collects all the responses and evaluates the results to determine the final outcome of the distributed transaction.[1][4]
This brings the system to the second phase, the commit phase. If every single participant voted "Yes," the coordinator writes a commit record to its own log and broadcasts a final commit command to all nodes, instructing them to apply the changes and release their locks.[2]
The Blocking Problem Vulnerability
If even one participant votes "No," or if a participant fails to respond within a designated timeout window, the coordinator immediately broadcasts an abort command. Every participant then discards the prepared changes, releases the locks, and the database remains exactly as it was before the transaction began.[4]
While this voting mechanism guarantees strict atomicity, it introduces a severe vulnerability known as the blocking problem. Because participants must hold their database locks while waiting for the final decision, a failure at the coordinator level can freeze the entire system.[2][5]
"If the coordinator crashes after the participants have voted yes, but before they receive the final commit or abort message, the participants are stuck," notes the AWS Builders' Library documentation on distributed challenges. "They cannot unilaterally decide to abort, because the coordinator might have already decided to commit."[5]
During this frozen state, any other application attempting to read or write to those locked rows will be blocked, potentially causing cascading timeouts across an entire microservice architecture. Administrators must often intervene manually to resolve the hung transactions and release the locks.[4][5]
This vulnerability exposes the gap between marketing claims of "high availability" and the reality of strict consistency. A system using a traditional two-phase commit is only as reliable as its coordinator, making it a single point of failure despite being distributed across multiple machines.[1][2]
Latency and the Speed of Light
Beyond the blocking problem, the protocol imposes a massive performance penalty due to the sheer number of network round trips required. Every transaction must traverse the network at least twice—once for the prepare vote, and once for the final commit command.[2]
In a local data center, these round trips take less than a millisecond, making the overhead negligible. However, when databases are distributed across wide-area networks to survive regional disasters, the speed of light becomes a hard physical limit on transaction throughput.[1][5]
A standard wide-area network link between New York and London has a round-trip time of roughly 50 milliseconds. Because the two-phase commit requires two sequential round trips, a strict implementation imposes a hard mathematical floor of at least 100 milliseconds of latency per transaction.[1][5]
This 100-millisecond floor exists regardless of how much processing power or memory the cloud provider allocates to the database servers. It explains why applications that require thousands of transactions per second frequently abandon strict two-phase commits when operating across multiple geographic regions.[1]
To hide this latency, modern database vendors often employ sophisticated tricks. Some systems batch multiple commits together, while others use advanced clock synchronization hardware to reduce the need for constant coordination between nodes.[6]
Modern Alternatives and Consensus
Rather than relying on a single vulnerable coordinator, newer distributed databases like CockroachDB and Google Spanner utilize consensus algorithms such as Paxos or Raft. These protocols require only a majority of nodes to agree, rather than demanding unanimous consent from every participant.[6]
"By using parallel commits and consensus replication, we can acknowledge a transaction to the client before the second phase fully completes," CockroachDB's architecture documentation explains. This approach masks the latency of the commit phase without sacrificing the underlying atomicity guarantees.[6]
In the realm of microservices, developers frequently replace two-phase commits entirely with the Saga pattern. Instead of locking resources across multiple databases, a Saga executes a sequence of local transactions, issuing compensating transactions to undo the work if a later step fails.[5]
While the Saga pattern prevents the blocking problem and improves performance, it sacrifices strict isolation. Other users might temporarily see intermediate states—such as an account balance that has been deducted but not yet credited elsewhere—before the compensating transaction corrects the discrepancy.[2][5]
This trade-off highlights the enduring relevance of Jim Gray's original 1978 protocol. When a financial institution processes a high-value wire transfer, the risk of exposing an intermediate state or dropping a partial update far outweighs the cost of a 100-millisecond delay.[1][3]
The Enduring Necessity of Atomicity
Despite decades of attempts to engineer around it, the fundamental requirement for a prepare and commit phase remains embedded in nearly every relational database engine. PostgreSQL, for example, natively supports the PREPARE TRANSACTION command specifically to allow external coordinators to manage distributed writes.[4]
As cloud architectures push toward increasingly decentralized, serverless models, the tension between consistency and latency will only intensify. Marketing materials will continue to promise databases that are simultaneously global, instantaneous, and perfectly consistent, but the physics of distributed systems refuse to bend.[1]
As cloud architectures push toward increasingly decentralized, serverless models, the tension between consistency and latency will only intensify.
The next verifiable shift in this space relies on deterministic execution models, where databases agree on the exact order of transactions before executing them. Until those experimental systems reach mainstream commercial viability, the two-phase commit's strict voting mechanism remains the definitive safeguard against corrupted data.[1][6]
How we did this
- Method
- We calculated the minimum latency overhead of strict two-phase commit (2PC) against single-node transactions by computing the required network round-trips across a standard wide-area network link.
- What we found
- A strict 2PC implementation imposes a hard mathematical floor of at least 100 milliseconds of latency per transaction across a WAN, explaining why modern distributed databases often abandon it for eventual consistency.
- What we worked from
- 2PC protocol phase sequence (Prepare + Commit): 2 sequential round trips — O'Reilly Media
- Standard WAN round-trip time: 50 milliseconds — Amazon Web Services
- Limits of this analysis
- This calculation assumes a perfect network without packet loss or coordinator failure, which would trigger timeouts and exponentially increase the delay.
Key terms
- Atomicity
- The database property ensuring that a transaction is treated as a single, indivisible unit that either completely succeeds or completely fails.
- Coordinator
- The central server node responsible for managing the voting process and deciding the final outcome of a distributed transaction.
- Write-Ahead Log
- A durable file on a disk where a database records planned changes before applying them, ensuring data can be recovered after a crash.
- Blocking Problem
- A vulnerability where participant nodes are stuck holding database locks because the coordinator failed before sending the final commit or abort command.
Reader questions
What happens if a participant crashes during the prepare phase?
If a participant crashes before voting, the coordinator will eventually time out waiting for its response and automatically broadcast an abort command to all other nodes.
Can a participant change its vote from 'Yes' to 'No'?
No. Once a participant votes 'Yes', it is mathematically bound to that decision and must wait for the coordinator's final instruction, even if it takes hours.
Why don't microservices use two-phase commits?
Microservices typically span different teams and technologies, making it dangerous to let one service lock the database tables of another service, which could cause cascading system failures.
Where opinion splits
Strict Consistency Advocates
Argue that financial and critical systems cannot tolerate intermediate states or partial failures.
This camp, heavily represented in traditional banking and enterprise resource planning, maintains that the latency penalty of a two-phase commit is a necessary cost of doing business. They point out that compensating transactions in a Saga pattern shift the burden of handling data anomalies onto the application developers, often leading to edge-case bugs that corrupt ledgers. For these engineers, the mathematical certainty of Jim Gray's 1978 protocol outweighs the marketing appeal of infinite scalability. They argue that if a database cannot guarantee atomicity across nodes, it is pushing the hardest problems of distributed state management back onto the user.
Distributed Systems Engineers
Prioritize system availability and partition tolerance over strict, immediate consistency.
Engineers building global-scale applications argue that the blocking problem makes two-phase commits fundamentally unsuited for cloud environments. They advocate for consensus protocols like Raft or eventual consistency models, arguing that it is better to serve slightly stale data than to freeze an entire database because a single coordinator node crashed. From this perspective, the 100-millisecond latency floor of a wide-area two-phase commit is a non-starter for modern consumer applications. They view strict ACID compliance across geographic regions as an architectural anti-pattern, preferring to design applications that can gracefully handle temporary data discrepancies.
NewSQL Vendors
Attempt to bridge the gap by combining strict atomicity with consensus-based replication.
Companies developing modern distributed SQL databases market their platforms as offering the best of both worlds. They utilize parallel commits and advanced clock synchronization to hide the latency of the two-phase commit, claiming they can provide strict ACID guarantees without the traditional performance bottlenecks that plagued earlier implementations. These vendors argue that developers should not have to choose between consistency and scale. By replacing the single vulnerable coordinator with a resilient consensus group, they aim to eliminate the blocking problem while preserving the developer-friendly semantics of traditional relational databases.
- Strict Consistency Advocates
- Argue that financial and critical systems cannot tolerate intermediate states or partial failures.
- Distributed Systems Engineers
- Prioritize system availability and partition tolerance over strict, immediate consistency.
- NewSQL Vendors
- Attempt to bridge the gap by combining strict atomicity with consensus-based replication.
Perspectives this story doesn't cover
- Application Developers handling Saga rollbacks
- Cloud Infrastructure Providers managing network partitions
Sources
[1]Factlen Editorial TeamStrict Consistency AdvocatesSynthesis by Factlen editorial team
Read on Factlen Editorial Team →
[2]O'Reilly MediaDistributed Systems EngineersDesigning Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems
Read on O'Reilly Media →
[3]ACM Digital LibraryStrict Consistency AdvocatesNotes on Data Base Operating Systems
Read on ACM Digital Library →
[4]PostgreSQL Global Development GroupNewSQL VendorsPostgreSQL Documentation: PREPARE TRANSACTION
Read on PostgreSQL Global Development Group →
[5]Amazon Web ServicesDistributed Systems EngineersChallenges with distributed systems
Read on Amazon Web Services →
[6]Cockroach LabsNewSQL VendorsCockroachDB Architecture: Transaction Layer
Read on Cockroach Labs →
More in Technology
See all →App Distribution
Google Play Opens Private Installs for AI-Generated Apps Without Developer Fees
7 sources
Local-First Sync
How Join-Semilattices Ensure Offline Document Replicas Converge Without Central Servers
3 sources
AI Privacy
Meta's Muse AI Is Compiling Hourly Dossiers on Users and Their Unregistered Contacts
6 sources
Mobile Architecture
Single Persistent OS Connections to Push Gateways Spare Smartphone Batteries from Cellular Radio Drain
4 sources
Comments
Every angle. Every day.
Get Technology stories with full source coverage and perspective breakdowns, free every day.




