/
perform-two-phase-commits.txt
310 lines (230 loc) · 11.2 KB
/
perform-two-phase-commits.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
=========================
Perform Two Phase Commits
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
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 :ref:`rollback-like <2-phase-commits-rollback>`
functionality.
Background
----------
Operations on a single :term:`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 :ref:`recoverable
<2-phase-commits-rollback>`. 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:
#. A collection named ``accounts`` to store account information.
#. 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``.
.. code-block:: javascript
db.accounts.insert(
[
{ _id: "A", balance: 1000, pendingTransactions: [] },
{ _id: "B", balance: 1000, pendingTransactions: [] }
]
)
The operation returns a :method:`BulkWriteResult()` object with the
status of the operation. Upon successful insert, the
:method:`BulkWriteResult()` has :data:`~BulkWriteResult.nInserted` set
to ``2`` .
.. _initialize-transfer-record:
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:
.. code-block:: javascript
db.transactions.insert(
{ _id: 1, source: "A", destination: "B", value: 100, state: "initial", lastModified: new Date() }
)
The operation returns a :method:`WriteResult()` object with the status
of the operation. Upon successful insert, the :method:`WriteResult()`
object has :data:`~WriteResult.nInserted` set to ``1``.
Transfer Funds Between Accounts Using Two-Phase Commit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/steps/perform-two-phase-commit-transaction.rst
.. _2-phase-commits-recovery:
Recovering from Failure Scenarios
---------------------------------
The most important part of the transaction procedure is not the
prototypical example above, but rather the possibility for recovering
from the various failure scenarios when transactions do not complete
successfully. This section presents an overview of possible
failures and provides steps to recover from these kinds of events.
Recovery Operations
~~~~~~~~~~~~~~~~~~~
The two-phase commit pattern allows applications running the sequence
to resume the transaction and arrive at a consistent state. Run the
recovery operations at application startup, and possibly at regular
intervals, to catch any unfinished transactions.
The time required to reach a consistent state depends on how long the
application needs to recover each transaction.
The following recovery procedures uses the ``lastModified`` date as an
indicator of whether the pending transaction requires recovery;
specifically, if the pending or applied transaction has not been
updated in the last 30 minutes, the procedures determine that these
transactions require recovery. You can use different conditions to make
this determination.
Transactions in Pending State
`````````````````````````````
To recover from failures that occur after step
"`Update transaction state to pending.`_" but before
"`Update transaction state to applied.`_" step, retrieve from
the ``transactions`` collection a pending transaction for recovery:
.. code-block:: javascript
var dateThreshold = new Date();
dateThreshold.setMinutes(dateThreshold.getMinutes() - 30);
var t = db.transactions.findOne( { state: "pending", lastModified: { $lt: dateThreshold } } );
And resume from step "`Apply the transaction to both accounts.`_"
Transactions in Applied State
`````````````````````````````
To recover from failures that occur after step
"`Update transaction state to applied.`_" but before
"`Update transaction state to done.`_" step, retrieve from
the ``transactions`` collection an applied transaction for recovery:
.. code-block:: javascript
var dateThreshold = new Date();
dateThreshold.setMinutes(dateThreshold.getMinutes() - 30);
var t = db.transactions.findOne( { state: "applied", lastModified: { $lt: dateThreshold } } );
And resume from
"`Update both accounts' list of pending transactions.`_"
.. _2-phase-commits-rollback:
Rollback Operations
~~~~~~~~~~~~~~~~~~~
In some cases, you may need to "roll back" or undo a transaction; e.g.,
if the application needs to "cancel" the transaction or if one of the
accounts does not exist or stops existing during the transaction.
Transactions in Applied State
`````````````````````````````
After the "`Update transaction state to applied.`_" step, you should
**not** roll back the transaction. Instead, complete that transaction
and :ref:`create a new transaction <initialize-transfer-record>` to
reverse the transaction by switching the values in the source and the
destination fields.
Transactions in Pending State
`````````````````````````````
After the "`Update transaction state to pending.`_" step, but before the
"`Update transaction state to applied.`_" step, you can rollback the
transaction using the following procedure:
.. include:: /includes/steps/perform-two-phase-commit-rollback.rst
.. _2-phase-commits-concurrency:
Multiple Applications
---------------------
Transactions exist, in part, so that multiple applications can create
and run operations concurrently without causing data inconsistency or
conflicts. In our procedure, to update or retrieve the transaction
document, the update conditions include a condition on the ``state``
field to prevent reapplication of the transaction by multiple
applications.
For example, applications ``App1`` and ``App2`` both grab the same
transaction, which is in the ``initial`` state. ``App1`` applies the
whole transaction before ``App2`` starts. When ``App2`` attempts to
perform the "`Update transaction state to pending.`_" step, the update
condition, which includes the ``state: "initial"`` criterion, will not
match any document, and the :data:`~WriteResult.nMatched` and
:data:`~WriteResult.nModified` will be ``0``. This should signal to
``App2`` to go back to the first step to restart the procedure with
a different transaction.
When multiple applications are running, it is crucial that only one
application can handle a given transaction at any point in time. As
such, in addition including the expected state of the transaction in
the update condition, you can also create a marker in the transaction
document itself to identify the application that is handling the
transaction. Use :method:`~db.collection.findAndModify()` method to
modify the transaction and get it back in one step:
.. code-block:: javascript
t = db.transactions.findAndModify(
{
query: { state: "initial", application: { $exists: false } },
update:
{
$set: { state: "pending", application: "App1" },
$currentDate: { lastModified: true }
},
new: true
}
)
Amend the transaction operations to ensure that only applications that
match the identifier in the ``application`` field apply the transaction.
If the application ``App1`` fails during transaction execution, you can
use the :ref:`recovery procedures <2-phase-commits-recovery>`, but
applications should ensure that they "own" the transaction before
applying the transaction. For example to find and resume the pending
job, use a query that resembles the following:
.. code-block:: javascript
var dateThreshold = new Date();
dateThreshold.setMinutes(dateThreshold.getMinutes() - 30);
db.transactions.find(
{
application: "App1",
state: "pending",
lastModified: { $lt: dateThreshold }
}
)
.. _2-phase-commits-in-production:
Using Two-Phase Commits in Production Applications
--------------------------------------------------
The example transaction above is intentionally simple. For example, it
assumes that it is always possible to roll back operations to an
account and that account balances can hold negative values.
Production implementations would likely be more complex. Typically,
accounts need information about current balance, pending credits, and
pending debits.
For all transactions, ensure that you use the appropriate level of
:doc:`write concern </reference/write-concern>` for your deployment.