Two-Phase Commit
Update resources on multiple nodes in one atomic operation.
Problem
When data needs to be atomically stored on multiple cluster nodes, nodes cannot make the data accessible to clients until the decision of other cluster nodes is known. Each node needs to know if other nodes successfully stored the data or if they failed.
Solution
Comparison with Paxos and Replicated Log
Paxos and Replicated Log implementations also have two phases of execution. But the key difference is that those consensus algorithms are used when all the cluster nodes involved store the same values.
Two-phase commit works across cluster nodes storing different values—for example, across different partitions of a database. Each partition can be using Replicated Log to replicate the state involved in a two-phase commit.
The essence of two-phase commit, unsurprisingly, is that it carries out an update in two phases:
-
The prepare phase asks each node if it can promise to carry out the update.
-
The commit phase actually carries it out.
As part of the prepare phase, each node participating in the transaction acquires whatever it needs to assure that it will be able to do the commit in the second phase—for example, any locks that are required. Once each node is able to ensure it can commit in the second phase, it lets the coordinator know, promising the coordinator that it can and will commit in the second phase. If any node is unable to make that promise, then the coordinator tells all nodes to roll back, releasing any locks they have, and the transaction is aborted. Only if all the participants agree to go ahead does the second phase commence—at which point it’s expected they will all successfully update. It is crucial for each participant to ensure the durability of their decisions using a pattern like Write-Ahead Log . This means that even if a node crashes and subsequently restarts, it should be capable of completing the protocol without any issues.
In a simple distributed key-value store implementation, the two-phase commit protocol works as follows.
The transactional client creates a unique identifier called a transaction identifier. The client also keeps track of other details like the transaction start time. This is used, as described later, by the locking mechanism to prevent deadlocks. The unique ID, along with the additional details such as the start timestamp, is used to track the transaction across the cluster nodes. The client maintains a transaction reference, which is passed along with every request from the client to other cluster nodes:
Click here to view code image
class TransactionRef...
private UUID txnId;
private long startTimestamp;
public TransactionRef(long startTimestamp) {
this.txnId = UUID.randomUUID();
this.startTimestamp = startTimestamp;
}
class TransactionClient...
TransactionRef transactionRef;
public TransactionClient(ReplicaMapper replicaMapper, SystemClock systemClock) {
this.clock = systemClock;
this.transactionRef = new TransactionRef(clock.now());
this.replicaMapper = replicaMapper;
}
One of the cluster nodes acts as a coordinator which tracks the status of the transaction on behalf of the client. In a key-value store, it is generally the cluster node holding data for one of the keys. It is generally picked up as the cluster node storing data for the first key used by the client.
Before storing any value, the client communicates with the coordinator to notify it about the start of the transaction. Since the coordinator is one of the cluster nodes storing values, it is picked dynamically when the client initiates a get or put operation with a specific key.
Click here to view code image
class TransactionClient...
private TransactionalKVStore coordinator;
private void maybeBeginTransaction(String key) {
if (coordinator == null) {
coordinator = replicaMapper.serverFor(key);
coordinator.begin(transactionRef);
}
}
The transaction coordinator keeps track of the status of the transaction. It records every change in a Write-Ahead Log to make sure that the details are available in case of a crash.
Click here to view code image
class TransactionCoordinator...
Map<TransactionRef, TransactionMetadata> transactions
= new ConcurrentHashMap<>();
WriteAheadLog transactionLog;
public void begin(TransactionRef transactionRef) {
var txnMetadata = new TransactionMetadata(transactionRef, systemClock,
transactionTimeoutMs);
transactionLog.writeEntry(txnMetadata.serialize());
transactions.put(transactionRef, txnMetadata);
}
class TransactionMetadata...
private TransactionRef txn;
private List<String> participatingKeys = new ArrayList<>();
private TransactionStatus transactionStatus;
The example code shows that every put request goes to the respective servers. But since the values are not made visible until the transaction commits, they can very well be buffered on the client side, to optimize on the network round trips, until the client decides to commit.
The client sends each key which is part of the transaction to the coordinator. This way the coordinator tracks all the keys which are part of the transaction. The coordinator records the keys which are part of the transaction in the transaction metadata. The keys then can be used to know about all of the cluster nodes which are part of the transaction. Since each key-value is generally replicated with the Replicated Log, the leader server handling the requests for a particular key might change over the lifetime of the transaction, so the keys are tracked instead of the actual server addresses. The client then sends the put or get requests to the server holding the data for the key. The server is picked based on the partitioning strategy. The thing to note is that the client directly communicates with the server and not through the coordinator. This avoids sending data twice over the network—from client to coordinator and then from coordinator to the respective server.
Click here to view code image
class TransactionClient...
public CompletableFuture<String> get(String key) {
maybeBeginTransaction(key);
coordinator.addKeyToTransaction(transactionRef, key);
TransactionalKVStore kvStore = replicaMapper.serverFor(key);
return kvStore.get(transactionRef, key);
}
public void put(String key, String value) {
maybeBeginTransaction(key);
coordinator.addKeyToTransaction(transactionRef, key);
replicaMapper.serverFor(key).put(transactionRef, key, value);
}
class TransactionCoordinator...
public void addKeyToTransaction(TransactionRef transactionRef,
String key) {
var metadata = transactions.get(transactionRef);
if (!metadata.getParticipatingKeys().contains(key)) {
metadata.addKey(key);
transactionLog.writeEntry(metadata.serialize());
}
}
The cluster node handling the request detects that the request is part of a transaction with the transaction ID. It manages the state of the transaction, where it stores the key, and the value in the request. The key values are not directly made available to the key-value store but stored separately.
Click here to view code image
class TransactionalKVStore...
public void put(TransactionRef transactionRef, String key, String value) {
TransactionState state = getOrCreateTransactionState(transactionRef);
state.addPendingUpdates(key, value);
}
Locks and Transaction Isolation
Problems with Non-Serializable Isolation
The serializable isolation level has an impact on overall performance—mostly because of the locks held for the duration of the transaction. That’s why most data stores provide relaxed isolation levels where the locks are released earlier. This is a problem particularly when clients need to do read-modify-write operations. The operations can potentially overwrite the values from the previous transactions. So modern data stores like Google Spanner or CockroachDB provide serializable isolation.
In implementations using locks, the requests also take a lock on the keys. Particularly, the get requests take a read lock and the put requests take a write lock. The read locks are taken as the values are read.
Click here to view code image
class TransactionalKVStore...
public CompletableFuture<String> get(TransactionRef txn, String key) {
CompletableFuture<TransactionRef> lockFuture
= lockManager.acquire(txn, key, LockMode.READ);
return lockFuture.thenApply(transactionRef -> {
getOrCreateTransactionState(transactionRef);
return kv.get(key);
});
}
synchronized TransactionState getOrCreateTransactionState(
TransactionRef txnRef) {
TransactionState state = this.ongoingTransactions.get(txnRef);
if (state == null) {
state = new TransactionState();
this.ongoingTransactions.put(txnRef, state);
}
return state;
}
The write locks can be taken only when the transaction is about to commit and the values are to be made visible in the key-value store. Until then, the cluster node can just track the modified values as pending operations.
Click here to view code image
class TransactionalKVStore...
public void put(TransactionRef transactionRef, String key, String value) {
TransactionState state = getOrCreateTransactionState(transactionRef);
state.addPendingUpdates(key, value);
}
The key design decision is about which values are made visible to the concurrent transactions. Different transaction isolation levels give different levels of visibility. For example, in strictly serializable transactions, read requests are blocked till the transaction doing the write completes. To improve performance, data stores can get around two-phase locking and release locks earlier. But then consistency of the data is compromised. There are a lot of different choices 71 defined by different isolation levels that data stores provide.
-
[https://jepsen.io/consistency](https://jepsen.io/consistency)
It is important to note that the locks are long-lived and not released when the request completes. They are released only when the transaction commits. This technique of holding locks for the duration of the transaction and releasing them only when the transaction commits or rolls back is called two-phase locking. Two-phase locking is critical in providing the serializable isolation level. “Serializable” means that the effects of transactions are visible as if they are executed one at a time.
Deadlock Prevention
Usage of locks can cause deadlocks where two transactions wait for each other to release the locks. Deadlocks can be avoided if transactions are not allowed to wait and are aborted when a conflict is detected. There are different strategies used to decide which transactions are aborted and which are allowed to continue.
The lock manager implements these wait policies as follows:
class LockManager...
WaitPolicy waitPolicy;
The WaitPolicy decides what to do when there are conflicting requests.
public enum WaitPolicy {
WoundWait,
WaitDie,
Error
}
The lock is an object which tracks the transactions which currently own the lock and the ones which are waiting for the lock.
Click here to view code image
class Lock...
Queue<LockRequest> waitQueue = new LinkedList<>();
List<TransactionRef> owners = new ArrayList<>();
LockMode lockMode;
When a transaction requests to acquire a lock, the lock manager grants the lock immediately if there are no conflicting transactions already owning the lock.
Click here to view code image
class LockManager...
public synchronized CompletableFuture<TransactionRef>
acquire(TransactionRef txn, String key,
LockMode lockMode) {
return acquire(txn, key, lockMode, new CompletableFuture<>());
}
CompletableFuture<TransactionRef>
acquire(TransactionRef txnRef,
String key,
LockMode askedLockMode,
CompletableFuture<TransactionRef> lockFuture) {
var lock = getOrCreateLock(key);
logger.debug("acquiring lock for = " + txnRef
+ " on key = " + key + " with lock mode = " + askedLockMode);
if (lock.isCompatible(txnRef, askedLockMode)) {
lock.addOwner(txnRef, askedLockMode);
lockFuture.complete(txnRef);
logger.debug("acquired lock for = " + txnRef);
return lockFuture;
}
if (lock.isLockedBy(txnRef) && lock.lockMode == askedLockMode) {
lockFuture.complete(txnRef);
logger.debug("Lock already acquired lock for = " + txnRef);
return lockFuture;
}
class Lock...
public boolean isCompatible(TransactionRef txnRef, LockMode lockMode) {
if(hasOwner()) {
return (inReadMode() && lockMode == LockMode.READ)
|| isOnlyOwner(txnRef);
}
return true;
}
If there are conflicts, the lock manager acts depending on the wait policy.
Error On Conflict
If the wait policy is to error out, it will throw an error and the calling transaction will roll back. The error is propagated to the client, who can then decide to retry after a random timeout.
Click here to view code image
class LockManager...
private CompletableFuture<TransactionRef>
handleConflict(Lock lock,
TransactionRef txnRef,
String key,
LockMode askedLockMode,
CompletableFuture<TransactionRef> lockFuture) {
switch (waitPolicy) {
case Error: {
var e = new WriteConflictException(txnRef, key, lock.owners);
lockFuture
.completeExceptionally(e);
return lockFuture;
}
case WoundWait: {
return lock.woundWait(txnRef, key, askedLockMode, lockFuture,
this);
}
case WaitDie: {
return lock.waitDie(txnRef, key, askedLockMode, lockFuture,
this);
}
}
throw new IllegalArgumentException("Unknown waitPolicy " + waitPolicy);
}
In case of contention, when there are many user transactions trying to acquire locks and all of them need to restart, it severely limits the systems throughput. Data stores try to make sure that there are minimal transaction restarts.
A common technique is to assign a unique ID to transactions and order them. For example, Google Spanner assigns unique IDs [ Malkhi2013 ] to transactions in such a way that they can be ordered. The technique is very similar to the one discussed in Paxos to order requests across cluster nodes. When transactions can be ordered, there are two techniques used to avoid deadlock but still allow transactions to continue without restarting.
The transaction reference is created in such a way that it can be compared and ordered with other transaction references. The easiest method is to assign a timestamp to each transaction and compare based on the timestamp.
Click here to view code image
class TransactionRef...
boolean after(TransactionRef otherTransactionRef) {
return this.startTimestamp > otherTransactionRef.startTimestamp;
}
But in distributed systems system clocks are not monotonic, as discussed in the sidebar “ Wall Clocks Are Not Monotonic ” of the Lease pattern, so a different method can be used: assigning unique IDs to transactions in such a way that they can be ordered. Along with ordered IDs, the age of each is tracked so the transactions can be ordered. Google Spanner orders transactions by tracking the age of each transaction in the system.
To be able to order all the transactions, each cluster node is assigned a unique ID. The client picks up the coordinator at the start of the transaction and gets the transaction ID from the coordinator. The cluster node acting as a coordinator generates transaction IDs as follows:
Click here to view code image
class TransactionCoordinator...
private int requestId;
public MonotonicId begin() {
return new MonotonicId(requestId++, config.getServerId());
}
class MonotonicId...
public class MonotonicId implements Comparable<MonotonicId> {
public int requestId;
int serverId;
public MonotonicId(int requestId, int serverId) {
this.serverId = serverId;
this.requestId = requestId;
}
public static MonotonicId empty() {
return new MonotonicId(-1, -1);
}
public boolean isAfter(MonotonicId other) {
if (this.requestId == other.requestId) {
return this.serverId > other.serverId;
}
return this.requestId > other.requestId;
}
class TransactionClient...
private void beginTransaction(String key) {
if (coordinator == null) {
coordinator = replicaMapper.serverFor(key);
MonotonicId transactionId = coordinator.begin();
transactionRef = new TransactionRef(transactionId, clock.nanoTime());
}
}
The client tracks the age of the transaction by recording the elapsed time since the beginning of the transaction:
Click here to view code image
class TransactionRef...
public void incrementAge(SystemClock clock) {
age = clock.nanoTime() - startTimestamp;
}
The client increments the age every time a get or a put request is sent to the servers. The transactions are then ordered as per their age. The transaction ID is used to break the ties when there are same-age transactions.
Click here to view code image
class TransactionRef...
public boolean isAfter(TransactionRef other) {
return age == other.age?
this.id.isAfter(other.id)
:this.age > other.age;
}
Wound-Wait
In the wound-wait method, if there is a conflict, the transaction reference asking for the lock is compared to all the transactions currently owning the lock. If the lock owners are all younger than the transaction asking for the lock, all of those transactions are aborted. But if the transaction asking the lock is younger than the ones owning the transaction, it waits for the lock:
Click here to view code image
class Lock...
public CompletableFuture<TransactionRef>
woundWait(TransactionRef txnRef,
String key,
LockMode askedLockMode,
CompletableFuture<TransactionRef> lockFuture,
LockManager lockManager) {
if (allOwningTransactionsStartedAfter(txnRef)
&& !anyOwnerIsPrepared(lockManager)) {
abortAllOwners(lockManager, key, txnRef);
return lockManager.acquire(txnRef, key, askedLockMode, lockFuture);
}
var lockRequest = new LockRequest(txnRef, key, askedLockMode,
lockFuture);
lockManager.logger.debug("Adding to wait queue = " + lockRequest);
addToWaitQueue(lockRequest);
return lockFuture;
}
class Lock...
private boolean allOwningTransactionsStartedAfter(TransactionRef txn) {
return owners.
stream().
filter(o -> !o.equals(txn))
.allMatch(owner -> owner.after(txn));
}
One of the key things to notice is that if the transaction owning the lock is already in the prepare state of the two-phase commit, it is not aborted.
Wait-Die
The wait-die method works in the opposite way to wound-wait. If the lock owners are all younger than the transaction asking for the lock, then the transaction waits for the lock. But if the transaction asking for the lock is younger than the ones owning the transaction, the transaction is aborted.
Click here to view code image
class Lock...
public CompletableFuture<TransactionRef>
waitDie(TransactionRef txnRef,
String key,
LockMode askedLockMode,
CompletableFuture<TransactionRef> lockFuture,
LockManager lockManager) {
if (allOwningTransactionsStartedAfter(txnRef)) {
addToWaitQueue(new LockRequest(txnRef, key, askedLockMode, lockFuture));
return lockFuture;
}
lockManager.abort(txnRef, key);
lockFuture.completeExceptionally(
new WriteConflictException(txnRef, key, owners));
return lockFuture;
}
The wound-wait method generally has fewer restarts than the wait-die method, so data stores such as Google Spanner use the wound-wait method.
When the owner of the transaction releases a lock, the waiting transactions are granted the lock.
Click here to view code image
class LockManager...
private void release(TransactionRef txn, String key) {
Optional<Lock> lock = getLock(key);
lock.ifPresent(l -> {
l.release(txn, this);
});
}
class Lock...
public void release(TransactionRef txn, LockManager lockManager) {
removeOwner(txn);
if (hasWaiters()) {
var lockRequest = getFirst(lockManager.waitPolicy);
lockManager.acquire(lockRequest.txn,
lockRequest.key, lockRequest.lockMode, lockRequest.future);
}
}
Commit and Rollback
Once the client is done with its read or write operations, it initiates the commit request by sending a commit request to the coordinator.
Click here to view code image
class TransactionClient...
public CompletableFuture<Boolean> commit() {
return coordinator.commit(transactionRef);
}
The transaction coordinator records the state of the transaction as preparing to commit. The coordinator implements the commit handling in two phases.
-
It first sends the prepare request to each of the participants.
-
Once it receives a successful response from all the participants, the coordinator marks the transaction as prepared to complete. Then it sends the commit request to all the participants.
Click here to view code image
class TransactionCoordinator...
public CompletableFuture<Boolean> commit(TransactionRef transactionRef) {
var metadata = transactions.get(transactionRef);
metadata.markPreparingToCommit(transactionLog);
var allPrepared = sendPrepareRequestToParticipants(transactionRef);
var futureList = sequence(allPrepared);
return futureList.thenApply(result -> {
if (!result.stream().allMatch(r -> r)) {
logger.info("Rolling back = " + transactionRef);
rollback(transactionRef);
return false;
}
metadata.markPrepared(transactionLog);
sendCommitMessageToParticipants(transactionRef);
metadata.markCommitComplete(transactionLog);
return true;
});
}
The cluster node receiving the prepare request does two things:
-
It tries to grab the write locks for all of the keys.
-
Once successful, it writes all of the changes to the write-ahead log.
If it can successfully do these, it can guarantee that there are no conflicting transactions, and even in case of a crash the cluster node can recover all the required state to complete the transaction.
Click here to view code image
class TransactionalKVStore...
public CompletableFuture<Boolean>
handlePrepare(TransactionRef txn) {
try {
TransactionState state = getTransactionState(txn);
if (state.isPrepared()) {
//already prepared.
return CompletableFuture.completedFuture(true);
}
if (state.isAborted()) {
//aborted by another transaction.
return CompletableFuture.completedFuture(false);
}
var pendingUpdates = state.getPendingUpdates();
var prepareFuture = prepareUpdates(txn, pendingUpdates);
return prepareFuture.thenApply(ignored -> {
var locksHeldByTxn = lockManager.getAllLocksFor(txn);
state.markPrepared();
writeToWAL(new TransactionMarker(txn, locksHeldByTxn,
TransactionStatus.PREPARED));
return true;
});
} catch (TransactionException| WriteConflictException e) {
logger.error(e);
}
return CompletableFuture.completedFuture(false);
}
private CompletableFuture<Boolean> prepareUpdates(TransactionRef txn,
Optional<Map<String, String>> pendingUpdates) {
if (pendingUpdates.isPresent()) {
var pendingKVs = pendingUpdates.get();
var lockFuture = acquireLocks(txn, pendingKVs.keySet());
return lockFuture.thenApply(ignored -> {
writeToWAL(txn, pendingKVs);
return true;
});
}
return CompletableFuture.completedFuture(true);
}
TransactionState getTransactionState(TransactionRef txnRef) {
return ongoingTransactions.get(txnRef);
}
private void writeToWAL(TransactionRef txn,
Map<String, String> pendingUpdates) {
for (String key : pendingUpdates.keySet()) {
var value = pendingUpdates.get(key);
wal.writeEntry(new SetValueCommand(txn, key, value).serialize());
}
}
private CompletableFuture<List<TransactionRef>>
acquireLocks(TransactionRef txn,
Set<String> keys) {
var lockFutures = new ArrayList<CompletableFuture<TransactionRef>>();
for (String key : keys) {
var lockFuture = lockManager.acquire(txn, key, LockMode.READWRITE);
lockFutures.add(lockFuture);
}
return sequence(lockFutures);
}
When the cluster node receives the commit message from the coordinator, it is safe to make the key-value changes visible. The cluster node does three things while committing the changes:
-
It marks the transaction as committed. Should the cluster node fail at this point, it knows the outcome of the transaction, and can repeat the following steps.
-
It applies all the changes to the key-value storage.
-
It releases all the acquired locks.
Click here to view code image
class TransactionalKVStore...
public void handleCommit(TransactionRef transactionRef,
List<String> keys) {
if (!ongoingTransactions.containsKey(transactionRef)) {
return; //this is a no-op. Already committed.
}
if (!lockManager.hasLocksFor(transactionRef, keys)) {
throw new IllegalStateException("Transaction " + transactionRef
+ " should hold all the required locks for keys " + keys);
}
writeToWAL(new TransactionMarker(transactionRef,
TransactionStatus.COMMITTED, keys));
applyPendingUpdates(transactionRef);
releaseLocks(transactionRef, keys);
}
private void removeTransactionState(TransactionRef txnRef) {
ongoingTransactions.remove(txnRef);
}
private void applyPendingUpdates(TransactionRef txnRef) {
var state = getTransactionState(txnRef);
var pendingUpdates = state.getPendingUpdates();
apply(txnRef, pendingUpdates);
}
private void apply(TransactionRef txnRef,
Optional<Map<String, String>> pendingUpdates) {
if (pendingUpdates.isPresent()) {
var pendingKv = pendingUpdates.get();
apply(pendingKv);
}
removeTransactionState(txnRef);
}
private void apply(Map<String, String> pendingKv) {
for (String key : pendingKv.keySet()) {
String value = pendingKv.get(key);
kv.put(key, value);
}
}
private void releaseLocks(TransactionRef txn, List<String> keys) {
lockManager.release(txn, keys);
}
private Long writeToWAL(TransactionMarker transactionMarker) {
return wal.writeEntry(transactionMarker.serialize());
}
The rollback is implemented in a similar way. If there is any failure, the client communicates with the coordinator to roll back the transaction.
Click here to view code image
class TransactionClient...
public void rollback() {
coordinator.rollback(transactionRef);
}
The transaction coordinator records the state of the transaction as preparing to roll back. Then it forwards the rollback request to all of the servers that stored the values for the given transaction. Once all of the requests are successful, the coordinator marks the transaction rollback as complete. In case the coordinator crashes and restarts after the transaction is marked as “prepared to roll back,” it can keep on sending the rollback messages to all the participating cluster nodes.
Click here to view code image
class TransactionCoordinator...
public void rollback(TransactionRef transactionRef) {
var transactionMetadata = transactions.get(transactionRef);
transactionMetadata.markPrepareToRollback(this.transactionLog);
sendRollbackMessageToParticipants(transactionRef);
transactionMetadata.markRollbackComplete(this.transactionLog);
}
private void sendRollbackMessageToParticipants(TransactionRef transactionRef) {
var transactionMetadata = transactions.get(transactionRef);
var participants
= getParticipants(transactionMetadata.getParticipatingKeys());
for (var kvStore : participants.keySet()) {
var keys = participants.get(kvStore);
kvStore.sendRollback(transactionMetadata.getTxn(), keys);
}
}
A cluster node receiving the rollback request does three things:
-
It records the state of the transaction as rolled back in the write-ahead log.
-
It discards the transaction state.
-
It releases all of the locks.
Click here to view code image
class TransactionalKVStore...
public void handleRollback(TransactionRef transactionRef,
List<String> keys) {
if (!ongoingTransactions.containsKey(transactionRef)) {
return; //no-op. Already rolled back.
}
writeToWAL(new TransactionMarker(transactionRef,
TransactionStatus.ROLLED_BACK, keys));
this.ongoingTransactions.remove(transactionRef);
this.lockManager.release(transactionRef, keys);
}
Idempotent Operations
In case of network failures, the coordinator can retry calls to prepare, commit, or abort. So these operations need to be idempotent, as discussed in the sidebar “ Idempotent and Non-Idempotent Requests ” of the Idempotent Receiver pattern.
An Example Scenario
Atomic Writes
Consider the following scenario. Paula Blue has a truck and Steven Green has a backhoe. The availability and the booking status of the truck and the backhoe are stored on a distributed key-value store. Depending on how the keys are mapped to servers, Blue’s truck and Green’s backhoe bookings are stored on separate cluster nodes. Alice is trying to book a truck and backhoe for the construction work she is planning to start on Monday. She needs both the truck and the backhoe to be available.
The booking scenario goes as follows.
Alice checks the availability of Blue’s truck and Green’s backhoe by reading the keys truck_booking_on_monday ( Figure 21.1 ) and backhoe_booking_on_monday ( Figure 21.2 ).
Figure 21.1 Blue node acquires read lock.
Figure 21.2 Green node acquires read lock.
If the values are empty, the booking is free. She reserves the truck and the backhoe. It is important that both values are set atomically. If there is any failure, then none of the values is set.
The commit happens in two phases. The first server Alice contacts acts as the coordinator and executes the two phases ( Figure 21.3 ).
Figure 21.3 Coordinator manages two-phase commit.
The coordinator is a separate participant in the protocol, shown that way on the sequence diagram. However, usually one of the servers (Blue or Green) acts as the coordinator, thus playing two roles in the interaction.
Conflicting Transactions
Consider a scenario where another person, Bob, is also trying to book a truck and backhoe for construction work on the same Monday.
The booking scenario happens as follows:
-
Both Alice and Bob read the keys
truck_booking_on_mondayandbackhoe_booking_on_monday. -
Both see that the values are empty, meaning the booking is free.
-
Both try to book the truck and the backhoe.
The expectation is that only Alice or Bob should be able to book, because the transactions are conflicting. In case of errors, the whole flow needs to be retried—and, hopefully, one will go ahead with the booking. However, in no situation should booking be done partially. Either both bookings are done or neither is done.
The scenario gets into a deadlock because both transactions depend on the locks held by others. The way out is for transactions to back out and fail. The example implementation shown here will fail the transaction if it detects a conflicting transaction holding a lock for a given key.
To check the availability, both Alice and Bob start a transaction and contact Blue and Green’s servers, respectively. Blue holds a read lock for the key truck_booking_on_monday ( Figure 21.4 ) and Green holds a read lock for the key backhoe_booking_on_monday ( Figure 21.5 ). Since read locks are shared, both Alice and Bob can read the values.
Figure 21.4 Blue acquires read lock for both Alice and Bob.
Figure 21.5 Green acquires read lock for both Alice and Bob.
Alice and Bob see that both bookings are available on Monday. So they reserve by sending the put requests to servers. Both servers hold the put requests in the temporary storage, as shown in Figures 21.6 and 21.7 .
Figure 21.6 Blue records pending operations for both Alice and Bob.
Figure 21.7 Green records pending operations for both Alice and Bob.
When Alice and Bob decide to commit the transactions, Blue—assuming it acts as a coordinator—triggers the two-phase commit protocol and sends the prepare requests to itself and Green.
For Alice’s request, it tries to grab a write lock for the key truck_booking_on_monday , which it cannot get, because there is a conflicting read lock grabbed by another transaction. So Alice’s transaction fails in the prepare phase. The same thing happens to Bob’s request ( Figure 21.8 ).
Figure 21.8 Commit failure because of conflicts
Transactions can be retried with a retry loop as follows:
Click here to view code image
class TransactionExecutor...
public boolean executeWithRetry(Function<TransactionClient, Boolean> txnMethod,
ReplicaMapper replicaMapper,
SystemClock systemClock) {
for (int attempt = 1; attempt <= maxRetries; attempt++) {
var client = new TransactionClient(replicaMapper, systemClock);
try {
txnMethod.apply(client);
var successfullyCommitted = client.commit().get();
return successfullyCommitted;
} catch (WriteConflictException e) {
logger.error("Write conflict detected while executing."
+ client.transactionRef
+ " Retrying attempt " + attempt);
rollbackAndWait(client);
} catch (ExecutionException | InterruptedException e) {
rollbackAndWait(client);
}
}
return false;
}
private void rollbackAndWait(TransactionClient client) {
client.rollback();
randomWait(); //wait for random interval
}
While it is very easy to implement, with error-on-conflict policy there will be multiple transaction restarts, reducing the overall throughput. If the wound-wait policy is used, it will have fewer transaction restarts. In the above example, only one transaction will possibly restart instead of both restarting in case of conflicts.
Using Versioned Value
It is very constraining to have conflicts for all the read and write operations, particularly so when the transactions can be read-only. It is optimal when read-only transactions can work without holding any locks and still guarantee that the values read in a transaction do not change with a concurrent read-write transaction.
Data stores generally store multiple versions of the values, as described in Versioned Value . The version used is the timestamp following Lamport Clock . A Hybrid Clock is used in databases such as MongoDB or CockroachDB. To use it with the two-phase commit protocol, the trick is that every server participating in the transaction sends, as its response to the prepare request, the timestamp it can write the values at. The coordinator chooses the maximum of these timestamps as the commit timestamp and sends it along with the value. The participating servers then save the value at the commit timestamp. This allows read-only requests to be executed without holding locks, because it’s guaranteed that the value written at a particular timestamp is never going to change.
Consider a simple example. Philip is running a report to read all of the bookings that happened until timestamp 2. If it is a long-running operation holding a lock, then Alice, who is trying to book a truck, will be blocked until Philip’s work completes. With Versioned Value, Philip’s get requests, which are part of a read-only operation, can continue at timestamp 2, while Alice’s booking continues at timestamp 4 ( Figure 21.9 ).
Figure 21.9 Using versions for nonblocking read-only transactions
Note that read requests which are part of a read-write transaction still need to hold a lock.
The example code with Lamport Clock looks as follows:
Click here to view code image
class MvccTransactionalKVStore...
public String readOnlyGet(String key, int readTimestamp) {
adjustServerTimestamp(readTimestamp);
waitForPendingWritesBelow(readTimestamp);
return kv.get(new VersionedKey(key, readTimestamp));
}
public CompletableFuture<String> get(TransactionRef txn,
String key, int requestTimestamp) {
adjustServerTimestamp(requestTimestamp);
var lockFuture = lockManager.acquire(txn, key, LockMode.READ);
return lockFuture.thenApply(transactionRef -> {
getOrCreateTransactionState(transactionRef);
return getValue(key, this.timestamp);
//read the latest value. no write can happen below this timestamp.
});
}
private String getValue(String key, int timestamp) {
var entry = kv.floorEntry(new VersionedKey(key, timestamp));
return entry != null && entry.getKey().getKey().equals(key)
? entry.getValue() : null;
}
private void adjustServerTimestamp(int requestTimestamp) {
this.timestamp = requestTimestamp > this.timestamp
? requestTimestamp:timestamp;
}
public int put(TransactionRef txnId, String key, String value,
int requestTimestamp) {
adjustServerTimestamp(requestTimestamp);
var transactionState = getOrCreateTransactionState(txnId);
transactionState.addPendingUpdates(key, value);
return this.timestamp;
}
class MvccTransactionalKVStore...
private int prepare(TransactionRef txn,
Optional<Map<String, String>> pendingUpdates)
throws WriteConflictException, IOException {
if (pendingUpdates.isPresent()) {
var pendingKVs = pendingUpdates.get();
acquireLocks(txn, pendingKVs);
//increment the timestamp for write operation.
timestamp = timestamp + 1;
writeToWAL(txn, pendingKVs, timestamp);
}
return timestamp;
}
class MvccTransactionCoordinator...
public int commit(TransactionRef txn) {
var commitTimestamp = prepare(txn);
var transactionMetadata = transactions.get(txn);
transactionMetadata.markPreparedToCommit(commitTimestamp, this.transactionLog);
sendCommitMessageToAllTheServers(txn,
commitTimestamp, transactionMetadata.getParticipatingKeys());
transactionMetadata.markCommitComplete(transactionLog);
return commitTimestamp;
}
public int prepare(TransactionRef txn) throws WriteConflictException {
var transactionMetadata = transactions.get(txn);
var keysToServers = getParticipants(transactionMetadata.getParticipatingKeys());
var prepareTimestamps = new ArrayList<Integer>();
for (var store : keysToServers.keySet()) {
var keys = keysToServers.get(store);
var prepareTimestamp = store.prepare(txn, keys);
prepareTimestamps.add(prepareTimestamp);
}
return prepareTimestamps
.stream()
.max(Integer::compare)
.orElse((int) txn.getStartTimestamp());
}
All the participating cluster nodes then store the key-value records at the commit timestamp.
Click here to view code image
class MvccTransactionalKVStore...
public void commit(TransactionRef txn, List<String> keys, int commitTimestamp) {
if (!lockManager.hasLocksFor(txn, keys)) {
throw new IllegalStateException(
"Transaction should hold all the required locks");
}
adjustServerTimestamp(commitTimestamp);
applyPendingOperations(txn, commitTimestamp);
lockManager.release(txn, keys);
logTransactionMarker(new TransactionMarker(txn,
TransactionStatus.COMMITTED,
commitTimestamp,
keys,
Collections.EMPTY_MAP));
removePending(commitTimestamp);
}
private void applyPendingOperations(TransactionRef txnId,
long commitTimestamp) {
Optional<TransactionState> transactionState = getTransactionState(txnId);
if (transactionState.isPresent()) {
TransactionState t = transactionState.get();
Optional<Map<String, String>> pendingUpdates = t.getPendingUpdates();
apply(txnId, pendingUpdates, commitTimestamp);
}
}
private void apply(TransactionRef txnId,
Optional<Map<String, String>> pendingUpdates,
long commitTimestamp) {
if (pendingUpdates.isPresent()) {
var pendingKv = pendingUpdates.get();
apply(pendingKv, commitTimestamp);
}
ongoingTransactions.remove(txnId);
}
private void apply(Map<String, String> pendingKv, long commitTimestamp) {
for (String key : pendingKv.keySet()) {
var value = pendingKv.get(key);
kv.put(new VersionedKey(key, commitTimestamp), value);
}
}
Snapshot Isolation
The above implementation still uses locks for the read requests in read-write transactions. If the workload contains mostly read requests, this impacts overall throughput and latency of the system. A general observation is that, in most practical situations, even with read-write transactions, read requests are far more numerous than the write requests. So, data stores that favor better performance prefer an implementation choice which does not hold locks for read requests even in read-write transactions.
But it’s a well known fact that if locks are not held for the duration of a transaction, there are various anomalies [ Berenson1995 ] which can cause data inconsistencies.
For example, let’s see what happens if read locks are not held in the above example using Versioned Value . Alice and Bob are trying to book a truck for Monday. They both read the key truck_booking_on_monday at timestamp 1. Both see that there is no booking ( Figure 21.10 ).
Figure 21.10 Reads in snapshot isolation executed without read locks
First, Alice sends a write request to set the key truck_booking_on_monday and commits the transaction. This creates a new version at timestamp 2 for that key, as Figure 21.11 demonstrates.
Figure 21.11 Alice’s update creates a new version.
Now, Bob sends a write request to set the key truck_booking_on_monday . This creates a new version at timestamp 3 for the key, as shown in Figure 21.12 .
Figure 21.12 Bob’s update creates a new version.
This is the problem of a lost update: Bob’s booking overwrote Alice’s booking. This happened because there was no way for Alice’s transaction to know that a concurrent transaction from Bob has already read the booking value, and might have acted upon it.
Snapshot isolation still can’t avoid one particular anomaly called “write skew.” So, if serializable transaction isolation is absolutely needed, a read-lock-based implementation should be used. Single-node databases, like PostgresSQL, implement a variation of snapshot isolation called serializable snapshot isolation [ Cahill2009 ] which has no strict read locks and strikes the balance to avoid the write-skew anomaly without impacting the performance.
The snapshot isolation algorithm avoids most of anomalies, including lost updates, even when it does not hold locks while reading data. Distributed data stores Percolator [ Peng2010 ], TiDB, 72 and Dgraph 73 implement snapshot isolation. The implementation works as follows.
-
[https://www.pingcap.com](https://www.pingcap.com) -
[https://dgraph.io](https://dgraph.io)
-
When a new transaction starts, it is assigned a new timestamp, higher than any previously committed timestamp, as its start timestamp.
-
All the writes are buffered.
-
All reads for that transaction happen with its start timestamp. When a key is read, the buffered value, or else a value committed before the start timestamp, is returned.
-
When the client commits the transaction, it happens as a two-phase commit.
-
The prepare phase sends all the key values which are buffered to the respective servers for writing.
-
The server locks the keys which are about to be written.
-
The servers then check to see if any other transaction has updates for the same keys after the start timestamp of this transaction.
-
If the lock cannot be held, or the keys are updated after the start timestamp of the transaction, the server returns failure to the prepare request. The client can then roll back the transaction and restart.
-
If all the servers return success to the prepare request, the coordinator gets a new timestamp, called commit timestamp, which is higher than any previously assigned start or commit timestamp.
-
The request is sent to all the participant servers to write the values at the commit timestamp.
-
Timestamp Oracle
One of the key requirements of a snapshot isolation algorithm is that the start and the commit timestamps should be monotonic across all nodes in the cluster. Once a particular response is returned at a given timestamp, no write should happen at a lower timestamp than the one received in the read request. The system timestamp cannot be used because they are not monotonic, as discussed in the sidebar “ Wall Clocks Are Not Monotonic ” of the Lease pattern and clock values from two different servers should not be compared. A simple Lamport clock cannot be used as well because Lamport clock values are not totally ordered across a set of servers (refer to the section “ Partial Order ” of the Lamport Clock pattern). So a server initiating a transaction cannot assign a start timestamp based on its own Lamport clock value. To work around the issue with system timestamps, Google Percolator and TiKV (inspired by Percolator) use a separate server, called timestamp oracle, which is guaranteed to give monotonic timestamps.
Each client communicates with the timestamp oracle service to get the start and commit transactions for the transaction. The timestamp oracle can become a single point of failure, so it is typically implemented with its own Replicated Log .
The above example, using the Versioned Value , will look as follows. The read requests won’t hold lock even for the read-write transaction.
When the new transaction starts, the coordinator gets a new timestamp from the timestamp oracle ( Figure 21.13 ).
Figure 21.13 Coordinator obtains a new timestamp using timestamp oracle.
The read requests are sent with this timestamp. The server returns the value with the highest timestamp version below this timestamp. One subtle point to note here is that if there are pending write operations from a concurrent transaction, at a timestamp below the start timestamp, the read needs to be retried, because the pending operations might commit and should be visible to this read request ( Figure 21.14 ).
Figure 21.14 Alice reads without acquiring a read lock.
The write requests are buffered ( Figure 21.15 ).
Figure 21.15 Alice’s updates are stored as pending writes.
When client commits the transaction, it happens in two phases, just like the original example with Versioned Value. The prepare phase tries to lock the keys to be written and checks if the keys were updated after the start of this transaction ( Figure 21.16 ).
Figure 21.16 The prepare request checks for writes since transaction start.
Once the prepare phase returns a success, the coordinator asks for a new timestamp from the timestamp oracle. It then asks all the participants to commit the key-value records at the commit timestamp ( Figure 21.17 ).
Figure 21.17 The coordinator obtains the commit timestamp from the timestamp oracle.
Let’s look at the lost-update example with Bob’s request above. Suppose Bob’s transaction started after Alice’s ( Figure 21.18 ).
Figure 21.18 Bob’s transaction acquires a new start timestamp.
At this point, if Alice commits the transaction, the commit timestamp will be 3.
When Bob tries to commit the transaction, the prepare phase will fail because it will detect that the key truck_booking_on_monday was updated after the start timestamp of Bob’s transaction ( Figure 21.19 ).
Figure 21.19 Bob’s transaction fails due to a conflict.
Using Hybrid Clock
Databases such as MongoDB or CockroachDB use Hybrid Clock to guarantee monotonicity of transactions because every request will adjust the hybrid clock on each server to be the most up-to-date. The timestamp is also advanced monotonically with every write request. Finally, the commit phase picks up the maximum timestamp across the set of participating servers, making sure that the write will always follow a previous read request. Clock-Bound Wait is used to work around the uncertainty in timestamp ordering because of clock skew.
It is important to note that, if the client is reading at a timestamp value lower than the one at which server is writing to, it is not an issue. But if the client is reading at a timestamp while the server is about to write at that particular timestamp, then it is a problem. If a server detects that a client is reading at a timestamp for which the server might have in-flight writes (those being prepared), the server can either wait for the writes to complete or return an error, so that the client can restart the transaction. CockroachDB throws an error if a read happens at a timestamp for which there is an ongoing transaction. Google Spanner reads have a phase where the client gets the time of the last successful write on a particular partition. If a client reads at a higher timestamp, the read requests wait until the writes happen at that timestamp.
Using Replicated Log
To improve fault tolerance, cluster nodes use Replicated Log . The coordinator uses Replicated Log to store the transaction log entries.
For the example of Alice and Bob above, Blue and Green servers will be two groups of servers. All the booking data will be replicated across a set of servers. Each request which is part of the two-phase commit goes to the leader of the server group. The replication is implemented using Replicated Log.
The client communicates with the leader of each server group. The replication is necessary only when the client decides to commit the transaction, so it happens as part of the prepare request.
The coordinator replicates every state change to Replicated Log as well.
In a distributed data store, each cluster node handles multiple partitions. A Replicated Log is maintained per partition. When Raft is used as part of replication, it’s sometimes referred to as Multi-Raft. 74
-
[https://www.cockroachlabs.com/blog/scaling-raft](https://www.cockroachlabs.com/blog/scaling-raft)
Client communicates with the leader of each partition participating in the transaction.
Failure Handling
The two-phase commit protocol heavily relies on the coordinator node to communicate the outcome of the transaction. Until the outcome of the transaction is known, the individual cluster nodes cannot allow any other transactions to write to the keys participating in the pending transaction. The cluster nodes block until the outcome of the transaction is known. This puts some critical requirements on the coordinator.
The coordinator needs to remember the state of the transactions even in case of a process crash.
Coordinator uses Write-Ahead Log to record every update to the state of the transaction. This way, when the coordinator crashes and comes back up, it can continue to work on the transactions which are incomplete.
Click here to view code image
class TransactionCoordinator...
public void loadTransactionsFromWAL() throws IOException {
List<WALEntry> walEntries = this.transactionLog.readAll();
for (WALEntry walEntry : walEntries) {
var txnMetadata =
(TransactionMetadata)
Command.deserialize(
new ByteArrayInputStream(
walEntry.getData()));
transactions.put(txnMetadata.getTxn(), txnMetadata);
}
startTransactionTimeoutScheduler();
completePreparedTransactions();
}
private void completePreparedTransactions() throws IOException {
var preparedTransactions
= transactions
.entrySet()
.stream()
.filter(entry -> entry.getValue().isPrepared())
.collect(Collectors.toList());
for (var preparedTransaction : preparedTransactions) {
TransactionMetadata txnMetadata = preparedTransaction.getValue();
sendCommitMessageToParticipants(txnMetadata.getTxn());
}
}
The client can fail before sending the commit message to the coordinator.
The transaction coordinator tracks when each transaction state was updated. If no state update is received in a configured timeout period, it triggers a transaction rollback. To avoid getting rolled back unnecessarily, the client sends regular HeartBeat to the coordinator.
Click here to view code image
class TransactionCoordinator...
private ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);
private ScheduledFuture<?> taskFuture;
private long transactionTimeoutMs = Long.MAX_VALUE; //for now.
public void startTransactionTimeoutScheduler() {
taskFuture = scheduler.scheduleAtFixedRate(() -> timeoutTransactions(),
transactionTimeoutMs,
transactionTimeoutMs,
TimeUnit.MILLISECONDS);
}
private void timeoutTransactions() {
for (var txnRef : transactions.keySet()) {
var transactionMetadata = transactions.get(txnRef);
long now = systemClock.nanoTime();
if (transactionMetadata.hasTimedOut(now)) {
sendRollbackMessageToParticipants(transactionMetadata.getTxn());
transactionMetadata.markRollbackComplete(transactionLog);
}
}
}
Transactional Intents
The key-value records that are written as part of the first phase need to be stored separately than the actual data exposed to other transactions. Data stores using existing key-value stores, such as RocksDB, instead of dealing with raw files, can use pending records themselves as locks. With some additional bookkeeping to figure out which server is acting as the coordinator, they can also be used to complete pending transactions. This is useful if the commit or rollback decision does not reach the individual servers participating in the transaction.
These provisional records are often referred to as “transactional intents.” YugabyteDB, CockroachDB, and TiKV use transactional intents to implement two-phase commits.
To see how it works, consider Alice writing truck-booking-on-monday and backhoe_booking_on_monday to servers Blue and Green, respectively. Transaction begins by picking a coordinator. As discussed above, the coordinator is generally the server hosting the first key of the transaction. The coordinator records the new transaction and marks its state as pending ( Figure 21.20 ).
Figure 21.20 Coordinator tracks transaction status.
Alice then sends the write request to servers Blue and Green. The provisional records are created for both writes. The provisional records also contain the address of the server which is acting as a coordinator. Generally, the server address is not directly stored, but the first key which was used to determine the coordinator is stored. The server address can be determined from that key. In Figures 21.21 and 21.22 , the server name is directly shown to simplify the explanation.
Figure 21.21 The blue node adds pending writes as transactional intent.
Figure 21.22 The green node marks pending writes as transactional intent.
When Alice decides to commit the transaction, she sends the commit request to the coordinator ( Figure 21.23 ).
Figure 21.23 Coordinator marks the transaction as committed.
Once the coordinator successfully updates the status of the transaction, the client can send commit requests to Blue and Green for the keys truck_booking_on_monday and backhoe_booking_on_monday ( Figure 21.24 ). The main advantage of having the provisional records with the details about the coordinator is that these commit requests can be sent asynchronously, without the client waiting for their results. It is fine even if the requests fail to reach the servers.
Figure 21.24 Nodes apply transactional intents when committed.
Let’s see how intent records can be used as locks, and how they can recover pending transactions. Consider another user, Bob, reading the key backhoe_booking_on_monday from server Green while there is a pending intent record. Bob’s request finds that there is a pending intent record for backhoe_booking_on_monday . It gets the transactionId and address of the server acting as the coordinator of this transaction.
It then sends a request to the coordinator to get the status of the transaction ( Figure 21.25 ). If the transaction is committed or rolled back, the request handler commits or rolls back the transaction and removes the intent record. After this, Bob’s request is resumed.
Figure 21.25 Bob’s request applies a committed transactional intent.
But if the transaction status is pending, then Bob is returned an error to indicate that there is a pending transaction. Bob has to retry ( Figure 21.26 ).
Figure 21.26 Bob’s request fails if the transaction status is pending.
This way, transaction intents act as locks and also allow resolving pending transactions even if the commit or rollback decision does not reach the servers participating in the two-phase commit execution.
Transactions across Heterogeneous Systems
The solution outlined here demonstrates the two-phase commit implementation in a homogenous system. Homogenous means all the cluster nodes are part of the same system and store the same kind of data. Examples are a distributed data store like MongoDB or a distributed message broker like Kafka.
Historically, two-phase commit was mostly discussed in the context of heterogeneous systems. Most commonly, two-phase commits are used with XA [ XA1991 ] transactions. In the J2EE servers, it is very common to use two-phase commits across a message broker and a database. The most common usage pattern is when a message needs to be produced on a message broker like ActiveMQ or JMS and a record needs to be inserted/updated in a database.
As we’ve seen in this chapter, the fault tolerance of the coordinator plays a critical role in a two-phase commit implementation. In case of XA transactions, the coordinator is an application process making the database and message broker calls. That application, in most modern scenarios, is a stateless microservice running in a containerized environment. It is not really a suitable place to put the responsibility of the coordinator. The coordinator needs to maintain state and recover quickly from failures to commit or roll back, which is difficult to implement in this case.
For this reason, while XA transactions seem attractive, they often run into issues in practice 75 and are best avoided. In the microservices world, patterns like transactional outbox 76 are preferred over XA transactions.
-
[https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/recover-xa-transactions.html](https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/recover-xa-transactions.html) -
[https://microservices.io/patterns/data/transactional-outbox.html](https://microservices.io/patterns/data/transactional-outbox.html)
On the other hand, most distributed storage systems implement two-phase commits across a set of partitions, and it works well in practice.
Examples
-
Distributed databases such as CockroachDB, MongoDB, and others implement two-phase commits to atomically store values across partitions.
-
Apache Kafka allows producing messages across multiple partitions atomically with the implementation similar to two-phase commits.