Perform Two Phase Commits

Synopsis

This document provides a pattern for doing multi-document updates or “multi-document transactions” using a two-phase commit approach for writing data to multiple documents. Additionally, you can extend this process to provide a rollback-like functionality.

Background

Operations on a single document are always atomic with MongoDB databases; however, operations that involve multiple documents, which are often referred to as “multi-document transactions”, are not atomic. Since documents can be fairly complex and contain multiple “nested” documents, single-document atomicity provides the necessary support for many practical use cases.

Despite the power of single-document atomic operations, there are cases that require multi-document transactions. When executing a transaction composed of sequential operations, certain issues arise, such as:

  • Atomicity: if one operation fails, the previous operation within the transaction must “rollback” to the previous state (i.e. the “nothing,” in “all or nothing”).
  • Consistency: if a major failure (i.e. network, hardware) interrupts the transaction, the database must be able to recover a consistent state.

For situations that require multi-document transactions, you can implement two-phase commit in your application to provide support for these kinds of multi-document updates. Using two-phase commit ensures that data is consistent and, in case of an error, the state that preceded the transaction is recoverable. During the procedure, however, documents can represent pending data and states.

Note

Because only single-document operations are atomic with MongoDB, two-phase commits can only offer transaction-like semantics. It is possible for applications to return intermediate data at intermediate points during the two-phase commit or rollback.

Pattern

Overview

Consider a scenario where you want to transfer funds from account A to account B. In a relational database system, you can subtract the funds from A and add the funds to B in a single multi-statement transaction. In MongoDB, you can emulate a two-phase commit to achieve a comparable result.

The examples in this tutorial use the following two collections:

  1. A collection named accounts to store account information.
  2. A collection named transactions to store information on the fund transfer transactions.

Initialize Source and Destination Accounts

Insert into the accounts collection a document for account A and a document for account B.

db.accounts.insert(
   [
     { _id: "A", balance: 1000, pendingTransactions: [] },
     { _id: "B", balance: 1000, pendingTransactions: [] }
   ]
)

The operation returns a BulkWriteResult() object with the status of the operation. Upon successful insert, the BulkWriteResult() has nInserted set to 2 .

Initialize Transfer Record

For each fund transfer to perform, insert into the transactions collection a document with the transfer information. The document contains the following fields:

  • source and destination fields, which refer to the _id fields from the accounts collection,
  • value field, which specifies the amount of transfer affecting the balance of the source and destination accounts,
  • state field, which reflects the current state of the transfer. The state field can have the value of initial, pending, applied, done, canceling, and canceled.
  • lastModified field, which reflects last modification date.

To initialize the transfer of 100 from account A to account B, insert into the transactions collection a document with the transfer information, the transaction state of "initial", and the lastModified field set to the current date:

db.transactions.insert(
    { _id: 1, source: "A", destination: "B", value: 100, state: "initial", lastModified: new Date() }
)

The operation returns a WriteResult() object with the status of the operation. Upon successful insert, the WriteResult() object has nInserted set to 1.

Transfer Funds Between Accounts Using Two-Phase Commit

1

Retrieve the transaction to start.

From the transactions collection, find a transaction in the initial state. Currently the transactions collection has only one document, namely the one added in the Initialize Transfer Record step. If the collection contains additional documents, the query will return any transaction with an initial state unless you specify additional query conditions.

var t = db.transactions.findOne( { state: "initial" } )

Type the variable t in the mongo shell to print the contents of the variable. The operation should print a document similar to the following except the lastModified field should reflect date of your insert operation:

{ "_id" : 1, "source" : "A", "destination" : "B", "value" : 100, "state" : "initial", "lastModified" : ISODate("2014-07-11T20:39:26.345Z") }
2

Update transaction state to pending.

Set the transaction state from initial to pending and use the $currentDate operator to set the lastModified field to the current date.

db.transactions.update(
    { _id: t._id, state: "initial" },
    {
      $set: { state: "pending" },
      $currentDate: { lastModified: true }
    }
)

The operation returns a WriteResult() object with the status of the operation. Upon successful update, the nMatched and nModified displays 1.

In the update statement, the state: "initial" condition ensures that no other process has already updated this record. If nMatched and nModified is 0, go back to the first step to get a different transaction and restart the procedure.

3

Apply the transaction to both accounts.

Apply the transaction t to both accounts using the update() method if the transaction has not been applied to the accounts. In the update condition, include the condition pendingTransactions: { $ne: t._id } in order to avoid re-applying the transaction if the step is run more than once.

To apply the transaction to the account, update both the balance field and the pendingTransactions field.

Update the source account, subtracting from its balance the transaction value and adding to its pendingTransactions array the transaction _id.

db.accounts.update(
   { _id: t.source, pendingTransactions: { $ne: t._id } },
   { $inc: { balance: -t.value }, $push: { pendingTransactions: t._id } }
)

Upon successful update, the method returns a WriteResult() object with nMatched and nModified set to 1.

Update the destination account, adding to its balance the transaction value and adding to its pendingTransactions array the transaction _id .

db.accounts.update(
   { _id: t.destination, pendingTransactions: { $ne: t._id } },
   { $inc: { balance: t.value }, $push: { pendingTransactions: t._id } }
)

Upon successful update, the method returns a

首页