James Kwon

5 min read

Jan 25, 2022

Table of Contents 目录

Introduction 导言

Consensus is one of the most important and fundamental problems in distributed computing. The goal of consensus algorithms is pretty simple: get multiple machines (a.k.a nodes) to agree on something. In reality, this is quite hard to achieve due to various failure scenarios (e.g., network partition). 共识是分布式计算中最重要和最基本的问题之一。共识算法的目标非常简单:让多台机器(也称为节点)就某事达成一致。实际上,由于各种故障场景(例如,网络分区),这很难实现。

What is Two Phase Commit (2PC)?

什么是两阶段提交(2PC)?

Two-phase commit (a.k.a 2PC) is an algorithm for achieving atomic transaction commit across multiple nodes. By definition of atomic transaction, all nodes participating in 2PC must either successfully commit or abort together. 两阶段提交(又名2PC)是一种跨多个节点实现原子事务提交的算法。根据原子事务的定义,参与2PC的所有节点必须一起成功提交或中止。

One node would be acting as a coordinator (a.k.a transaction manager) to initiate 2PC. There are two phases to this algorithm: 一个节点将充当协调器(也称为事务管理器)来启动2PC。该算法有两个阶段:

Figure 1. Two Phase Commit Flow Diagram 图1。两阶段提交流程图

Prepare Phase: 1. prepare -> 2. acquire lock -> 3. ack (yes/no) 准备阶段:1。准备->2。获取锁定->3。ack(是/否) Commit Phase: 1. commit -> 2. commit & release lock -> 3. ack (ok) 提交阶段:1。提交->2。提交和释放锁->3。ack(确定)

What does Saying “Yes” Mean?

说“是”是什么意思?

During the prepare phase, once a node accepts the proposed transaction, it must commit the transaction if the coordinator sends the commit request, regardless of any failure scenarios. In order to respect this promise, the participant node must write transaction data in disk before sending the commit promise to the coordinator. So when it recovers from failure, it knows which transaction to commit. The coordinator will retry forever to broadcast to either abort/commit. 在准备阶段,一旦节点接受了提议的事务,如果协调器发送了提交请求,它就必须提交事务,而不管任何失败场景。为了尊重这个承诺,参与者节点必须在向协调器发送提交承诺之前将事务数据写入磁盘。因此,当它从失败中恢复时,它知道要提交哪个事务。协调器将永远重试以广播中止/提交。

When to Use Two Phase Commit?

何时使用两阶段提交?