Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Fundamentals 29 min read

Distributed Transaction Algorithms: 2PC, 3PC, Saga & TCC with CAP/BASE Theory

This article explains major distributed transaction algorithms including two-phase commit (2PC), three-phase commit (3PC), Saga pattern, and TCC, comparing their consistency guarantees, complexity, and trade-offs, while also covering CAP theorem and BASE theory for distributed system design decisions.

1. Two-Phase Commit (2PC)

Two-phase commit (2PC) is a consistency protocol algorithm that guarantees strong data consistency and handles many transient system failures (process, network node, communication). It is widely used in relational database systems.

1.1 2PC Process

The system divides into a coordinator and participants. The process has two phases:

2PC diagram
2PC diagram

Phase 1: Prepare Request

Coordinator sends CanCommit request to all participants, asking them to prepare for commit or abort.

Participants execute the transaction operations, record undo/redo logs, and lock the current records.

Participants respond with YES if execution succeeds, NO if it fails.

When all participants have responded, the system enters the commit phase.

Phase 2: Commit

Coordinator sends DoCommit or DoAbort based on all responses.

Only if all participants return YES does the coordinator send DoCommit to commit; otherwise it sends DoAbort to abort. Participants that voted YES will roll back using undo logs.

Participants send HaveCommitted acknowledgment after receiving the coordinator's message.

Coordinator receiving all HaveCommitted messages marks the transaction complete.

1.2 2PC Drawbacks

Synchronous blocking: All participants remain blocked during execution, unable to perform other operations while waiting for responses.

Single point of failure: Coordinator is critical; if it fails, the whole protocol stalls. If it fails in phase 2, participants stay locked indefinitely.

Data inconsistency: If coordinator crashes after sending Commit to only some participants, those participants commit while others do not, causing inconsistency.

Unresolvable scenario: Coordinator sends DoCommit then crashes, and the sole participant that received it also crashes. Even with a new coordinator elected, the transaction state remains uncertain.

2. Three-Phase Commit (3PC)

To address 2PC's synchronous blocking and data inconsistency, 3PC introduces timeout mechanisms on both coordinator and participants, and splits the first phase into two steps: CanCommit, PreCommit, and DoCommit.

2.1 3PC Process

3PC diagram
3PC diagram

1) CanCommit Phase

Similar to 2PC's prepare phase. Coordinator sends commit request; participants respond Yes if they can commit, No otherwise.

2) PreCommit Phase

Coordinator decides based on responses:

If all participants respond Yes: coordinator sends PreCommit requests and enters Prepared state. Participants execute transaction operations, record undo/redo logs, and return ACK while waiting for final instruction.

If any participant responds No or times out: coordinator sends abort requests to all; participants abort on receiving abort or on timeout.

3) DoCommit Phase

Two possible outcomes:

Commit: Coordinator receives ACK from all participants, sends doCommit. Participants commit formally, release all resources, send ACK. Coordinator completes transaction after receiving all ACKs.

Abort: Coordinator does not receive ACK (non-ACK response or timeout), executes abort.

2.2 3PC Pros and Cons

Advantages:

Reduces synchronous blocking scope: In phase 2, once participants receive PreCommit they execute the transaction; regardless of receiving DoCommit, they will commit, avoiding blocking.

Solves single point problem: In phase 3, if coordinator fails or network partitions prevent DoCommit delivery, participants timeout and commit anyway.

Disadvantage:

Data inconsistency: If network partition occurs after PreCommit, participants timeout and commit, potentially causing inconsistency.

3. Saga Pattern

Saga is a long-transaction solution. Its core idea: decompose a distributed transaction into multiple local transactions, each with a corresponding execution module and compensation module . When any local transaction fails, invoking compensations restores previous transactions, achieving eventual consistency.

Saga consists of three parts:

LLT (Long Live Transaction): A chain of local transactions.

Local transactions: LLT = T1 + T2 + T3 + ... + Ti.

Compensations: Each local transaction Ti has a corresponding compensation Ci.

Normal execution order: T1 → T2 → T3 → ... → Ti. On exception, compensations run in reverse: T1 → T2 → T3 → ... → Ti → Ci → ... → C3 → C2 → C1.

Saga execution flow
Saga execution flow

Saga recovery has two modes:

Backward Recovery: Undo all previously successful sub-transactions. If any local sub-transaction fails, compensate completed ones. Order: T1, T2, T3, … Ti, Ci, … C3, C2, C1.

Forward Recovery: Retry the failed transaction; suitable for must-succeed scenarios, no compensations needed. Order: T1, T2, …, Tj (fail), Tj (retry), …, Ti.

Saga satisfies ACD of ACID:

Atomicity: Saga coordinator ensures all local transactions either all commit or all roll back.

Consistency: Saga achieves eventual consistency.

Durability: Based on local transactions, so durability is well supported.

However, Saga lacks isolation, leading to dirty reads, phantom reads, and non-repeatable reads. Business design must address this, typically using logical locks or serialized operations at the application layer.

Implementation notes for Saga:

Implementation considerations for Saga:
(1) Ti and Ci must be idempotent. Non-idempotent operations during backward or forward recovery cause data inconsistency.
(2) Ci must be able to succeed; if not, manual intervention is required.
(3) Execution results of Ti→Ci and Ci→Ti must be identical.

4. TCC Pattern

TCC (Try-Confirm-Cancel) was proposed by Pat Helland in the 2007 paper "Life beyond Distributed Transactions: an Apostate's Opinion". TCC uses a compensation mechanism: for each operation, register a corresponding confirm and cancel. By reserving resources early, it releases locks early; commit confirms reserved resources, rollback releases them. TCC requires each service to provide try, confirm, cancel interfaces , fully implemented by business logic, resulting in high business intrusion.

Try phase: Attempt execution, complete all business checks (consistency), reserve required business resources (quasi-isolation).

Confirm phase: Confirm business execution, no business checks, only use resources reserved in Try. Confirm must be idempotent; retry on failure.

Cancel phase: Cancel execution, release resources reserved in Try. Exception handling similar to Confirm, must be idempotent.

TCC flow
TCC flow

TCC processing flow involves three components:

Main business program: Initiates and completes the entire business activity; registers TCC transaction with TM and starts distributed transaction.

Branch services: Participants implementing Try, Confirm, Cancel actions for the main program to call. Correspond to microservices A and B; execute Try, then Confirm or Cancel based on TM result.

Transaction manager: Manages the entire business activity, including recording transaction state and invoking branch services' Confirm/Cancel operations.

Compared to Saga, TCC allows applications to customize data operation granularity, reducing lock conflicts and improving concurrency; however, it has stronger application intrusion and higher development effort due to the required Try/Confirm/Cancel interfaces.

5. Comparison of Distributed Transaction Algorithms

The four approaches compared across key dimensions:

Transaction consistency: 2PC (Strong), 3PC (Strong), TCC (Weak), Saga (Weak)

Complexity: 2PC (Low), 3PC (Medium), TCC (Medium), Saga (High)

Business intrusion: 2PC (Low), 3PC (Low), TCC (Low), Saga (High)

Usage limitations: 2PC (Medium), 3PC (Medium), TCC (Medium), Saga (High)

Performance: 2PC (Low), 3PC (Medium), TCC (High), Saga (Medium)

Maintenance cost: 2PC (Low), 3PC (Medium), TCC (Medium), Saga (High)

Typical use cases:

2PC/3PC: Database-dependent, provide strong consistency and transactionality but high latency. Suitable for traditional monolithic applications with cross-database operations within a single method. Not suitable for high-concurrency, high-performance scenarios.

Saga: Cannot guarantee isolation; requires business-layer concurrency control. Suitable when concurrent operations on the same resource are rare. Compensation implementation can be complex (e.g., sending a cancellation SMS after sending an SMS). Best for scenarios where compensations are easy to handle.

TCC: Suitable for deterministic, short execution times, high real-time requirements, and high data consistency needs, such as financial transactions and payment services.

6. CAP Theorem

Proposed by Eric Brewer in 2000, proven in 2002. In a distributed system, it is impossible to simultaneously satisfy all three properties:

C: Consistency — system remains in a consistent state after operations.

A: Availability — all operations receive a response within a reasonable time.

P: Partition Tolerance — system continues to operate despite network partitions.

6.1 Consistency

CAP consistency means linearizability (serializability), a special form of strong consistency. It differs from ACID consistency: CAP consistency means "all nodes see the same data at the same time" — after a successful update, all nodes have identical data at the same time.

From client perspective: strong consistency means updated data is immediately visible to subsequent requests; weak consistency tolerates partial or no visibility; eventual consistency guarantees visibility after some time.

From server perspective: consistency is about how data updates synchronize across the distributed system to ensure eventual consistency.

Consistency issues arise during concurrent reads/writes.

Consistency illustration
Consistency illustration

Left: Client updates N1 from V0 to V1. Subsequent reads from N1 return V1, from N2 return V0 — inconsistency across nodes.

Right: On write to N1, N1 synchronizes to N2, both become V1. Reads from both return V1 — consistency achieved.

If operation B occurs after successful completion of operation A, then the entire system must appear to B as if A has already completed or the updated state is visible.

If internal failures prevent consistency (e.g., N2 cannot sync N1's data), some nodes may serve stale data. To guarantee external consistency, the system may choose to return no data at all.

6.2 Availability

Availability means "reads and writes always succeed" — every node receiving a request must process and respond. Conditions:

Response must be within a reasonable time defined by business; exceeding it violates availability.

All nodes capable of receiving requests must return results. If some nodes are down but others respond, the system is still available. If all nodes respond but with inconsistent data (e.g., one node returns 1-day-old data, another 1-second-old), the system is still considered available.

Availability often measured by uptime: "five nines" (99.999%) means annual downtime ≤ 5.256 minutes.

6.3 Partition Tolerance

Distributed systems have multiple nodes communicating over networks. Network failures or other issues cause partitions. Partition tolerance means "the system continues to operate despite arbitrary message loss or failure of part of the system" — the system still provides services satisfying consistency and availability despite node or network partition failures.

6.4 CAP Trade-offs

In a distributed system, you cannot have all three. How to choose in practice?

6.4.1 CA Model

Sacrificing partition tolerance means placing all servers in one network node, violating distributed scalability. P is a basic requirement for distributed systems; without P, a partition error makes the whole system unusable. CA examples: single-site databases, clustered databases, LDAP, XFS file systems, typically implemented via two-phase commit and cache validation protocols.

6.4.2 CP Model

Sacrifice availability for consistency. Nodes must keep data consistent, but network instability may delay updates. If a system does not require strong availability (allows downtime or long unresponsiveness), it can guarantee CP. On network failure or message loss, the system sacrifices user experience, waiting for data consistency before allowing access. Typical CP: distributed databases using pessimistic locks or making minority partitions unavailable to prioritize consistency. Examples: Redis, ZooKeeper — data consistency is a fundamental requirement.

6.4.3 AP Model

Sacrifice consistency for high availability and partition tolerance. Nodes must return immediately to clients, possibly causing global data inconsistency. This trades strong consistency for eventual consistency (BASE theory). AP is widely used: high-concurrency systems use queuing and optimistic locking to prioritize availability and avoid blocking.

7. BASE Theory

When facing CAP trade-offs, systems often choose AP, sacrificing strong consistency but guaranteeing eventual consistency — this is BASE theory. BASE stands for Basically Available, Soft State, Eventual Consistency. It extends CAP: even if strong consistency is impossible, each application can adopt suitable ways to achieve eventual consistency based on its business characteristics.

Even if strong consistency cannot be achieved, every application can adopt appropriate methods according to its business characteristics to make the system reach eventual consistency.

7.1 Basically Available

Allows partial loss of availability during failures — core availability is preserved.

Response time loss: Normal 0.5s response may become 1-2s under basic availability; beyond a threshold users cannot tolerate.

Functional loss: On an e-commerce site, normal checkout works, but during promotions some users may be redirected to a degraded service page to protect system stability.

7.2 Soft State

Relative to atomicity (hard state).

Atomicity (hard state): Requires all data replicas to be consistent — a "hard state".

Soft state (weak state): Allows intermediate states in system data, believing this does not affect overall availability — permits replication delays across nodes.

Example: In MySQL replication, multiple replicas of the same data are allowed to have sync delays — this embodies soft state.

7.3 Eventual Consistency

System cannot remain in soft state indefinitely; there must be a time limit. After that limit, all replicas must become consistent, achieving eventual consistency. The time limit depends on network latency, system load, data replication design, etc. Eventual consistency is a specific form of weak consistency. Official definition:

The system guarantees that in the absence of new updates, data will eventually reach a consistent state, so all client accesses will eventually return the latest value.

References

Distributed Series: Distributed Consistency Algorithms Introduction (https://mp.weixin.qq.com/s?__biz=MzI3MzUzMjIxNA==&mid=2247484746&idx=1&sn=5e208358960af9b2673d00482bb4401e&scene=21#wechat_redirect)

Distributed Series: Distributed Transaction Algorithms Introduction (https://mp.weixin.qq.com/s?__biz=MzI3MzUzMjIxNA==&mid=2247484763&idx=1&sn=4158b7ff79ce767a186c3ee958e21006&scene=21#wechat_redirect)

Distributed Series: CAP Theory Analysis (https://mp.weixin.qq.com/s?__biz=MzI3MzUzMjIxNA==&mid=2247484669&idx=1&sn=f8e359550cfbfbb5ec5b5605967682b7&scene=21#wechat_redirect)

https://www.cnblogs.com/seven97-top/p/18739846

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

distributed systemsBASE theoryCAP theorem2PCTCCdistributed transactionsSaga3PC

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion