|
| 1 | +================== |
| 2 | +Optimistic Locking |
| 3 | +================== |
| 4 | + |
| 5 | +Optimistic Locking is a strategy for ensuring that your database writes are not overwritten by the writes of others. |
| 6 | +With optimistic locking, each item has an attribute that acts as a version number. If you retrieve an item from a |
| 7 | +table, the application records the version number of that item. You can update the item, but only if the version number |
| 8 | +on the server side has not changed. If there is a version mismatch, it means that someone else has modified the item |
| 9 | +before you did. The update attempt fails, because you have a stale version of the item. If this happens, you simply |
| 10 | +try again by retrieving the item and then trying to update it. Optimistic locking prevents you from accidentally |
| 11 | +overwriting changes that were made by others. It also prevents others from accidentally overwriting your changes. |
| 12 | + |
| 13 | +.. warning:: - Optimistic locking will not work properly if you use DynamoDB global tables as they use last-write-wins for concurrent updates. |
| 14 | + |
| 15 | +See also: |
| 16 | +`DynamoDBMapper Documentation on Optimistic Locking <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html>`_. |
| 17 | + |
| 18 | +Version Attribute |
| 19 | +----------------- |
| 20 | + |
| 21 | +To enable optimistic locking for a table simply add a ``VersionAttribute`` to your model definition. |
| 22 | + |
| 23 | +.. code-block:: python |
| 24 | +
|
| 25 | + class OfficeEmployeeMap(MapAttribute): |
| 26 | + office_employee_id = UnicodeAttribute() |
| 27 | + person = UnicodeAttribute() |
| 28 | +
|
| 29 | + def __eq__(self, other): |
| 30 | + return isinstance(other, OfficeEmployeeMap) and self.person == other.person |
| 31 | +
|
| 32 | + def __repr__(self): |
| 33 | + return str(vars(self)) |
| 34 | +
|
| 35 | +
|
| 36 | + class Office(Model): |
| 37 | + class Meta: |
| 38 | + read_capacity_units = 1 |
| 39 | + write_capacity_units = 1 |
| 40 | + table_name = 'Office' |
| 41 | + host = "http://localhost:8000" |
| 42 | + office_id = UnicodeAttribute(hash_key=True) |
| 43 | + employees = ListAttribute(of=OfficeEmployeeMap) |
| 44 | + name = UnicodeAttribute() |
| 45 | + version = VersionAttribute() |
| 46 | +
|
| 47 | +The attribute is underpinned by an integer which is initialized with 1 when an item is saved for the first time |
| 48 | +and is incremented by 1 with each subsequent write operation. |
| 49 | + |
| 50 | +.. code-block:: python |
| 51 | +
|
| 52 | + justin = OfficeEmployeeMap(office_employee_id=str(uuid4()), person='justin') |
| 53 | + garrett = OfficeEmployeeMap(office_employee_id=str(uuid4()), person='garrett') |
| 54 | + office = Office(office_id=str(uuid4()), name="office", employees=[justin, garrett]) |
| 55 | + office.save() |
| 56 | + assert office.version == 1 |
| 57 | +
|
| 58 | + # Get a second local copy of Office |
| 59 | + office_out_of_date = Office.get(office.office_id) |
| 60 | +
|
| 61 | + # Add another employee and persist the change. |
| 62 | + office.employees.append(OfficeEmployeeMap(office_employee_id=str(uuid4()), person='lita')) |
| 63 | + office.save() |
| 64 | + # On subsequent save or update operations the version is also incremented locally to match the persisted value so |
| 65 | + # there's no need to refresh between operations when reusing the local copy. |
| 66 | + assert office.version == 2 |
| 67 | + assert office_out_of_date.version == 1 |
| 68 | +
|
| 69 | +The version checking is implemented using DynamoDB conditional write constraints. Asserting that no value exists |
| 70 | +for the version attribute on the initial save and that the persisted value matches the local value on subsequent writes. |
| 71 | + |
| 72 | + |
| 73 | +Model.{update, save, delete} |
| 74 | +---------------------------- |
| 75 | +These operations will fail if the local object is out-of-date. |
| 76 | + |
| 77 | +.. code-block:: python |
| 78 | +
|
| 79 | + @contextmanager |
| 80 | + def assert_condition_check_fails(): |
| 81 | + try: |
| 82 | + yield |
| 83 | + except (PutError, UpdateError, DeleteError) as e: |
| 84 | + assert isinstance(e.cause, ClientError) |
| 85 | + assert e.cause_response_code == "ConditionalCheckFailedException" |
| 86 | + except TransactWriteError as e: |
| 87 | + assert isinstance(e.cause, ClientError) |
| 88 | + assert e.cause_response_code == "TransactionCanceledException" |
| 89 | + assert "ConditionalCheckFailed" in e.cause_response_message |
| 90 | + else: |
| 91 | + raise AssertionError("The version attribute conditional check should have failed.") |
| 92 | +
|
| 93 | +
|
| 94 | + with assert_condition_check_fails(): |
| 95 | + office_out_of_date.update(actions=[Office.name.set('new office name')]) |
| 96 | +
|
| 97 | + office_out_of_date.employees.remove(garrett) |
| 98 | + with assert_condition_check_fails(): |
| 99 | + office_out_of_date.save() |
| 100 | +
|
| 101 | + # After refreshing the local copy our write operations succeed. |
| 102 | + office_out_of_date.refresh() |
| 103 | + office_out_of_date.employees.remove(garrett) |
| 104 | + office_out_of_date.save() |
| 105 | + assert office_out_of_date.version == 3 |
| 106 | +
|
| 107 | + with assert_condition_check_fails(): |
| 108 | + office.delete() |
| 109 | +
|
| 110 | +Transactions |
| 111 | +------------ |
| 112 | + |
| 113 | +Transactions are supported. |
| 114 | + |
| 115 | +Successful |
| 116 | +__________ |
| 117 | + |
| 118 | +.. code-block:: python |
| 119 | +
|
| 120 | + connection = Connection(host='http://localhost:8000') |
| 121 | +
|
| 122 | + office2 = Office(office_id=str(uuid4()), name="second office", employees=[justin]) |
| 123 | + office2.save() |
| 124 | + assert office2.version == 1 |
| 125 | + office3 = Office(office_id=str(uuid4()), name="third office", employees=[garrett]) |
| 126 | + office3.save() |
| 127 | + assert office3.version == 1 |
| 128 | +
|
| 129 | + with TransactWrite(connection=connection) as transaction: |
| 130 | + transaction.condition_check(Office, office.office_id, condition=(Office.name.exists())) |
| 131 | + transaction.delete(office2) |
| 132 | + transaction.save(Office(office_id=str(uuid4()), name="new office", employees=[justin, garrett])) |
| 133 | + transaction.update( |
| 134 | + office3, |
| 135 | + actions=[ |
| 136 | + Office.name.set('birdistheword'), |
| 137 | + ] |
| 138 | + ) |
| 139 | +
|
| 140 | + try: |
| 141 | + office2.refresh() |
| 142 | + except DoesNotExist: |
| 143 | + pass |
| 144 | +
|
| 145 | + assert office.version == 2 |
| 146 | + assert office3.version == 2 |
| 147 | +
|
| 148 | +Failed |
| 149 | +______ |
| 150 | + |
| 151 | +.. code-block:: python |
| 152 | +
|
| 153 | + with assert_condition_check_fails(), TransactWrite(connection=connection) as transaction: |
| 154 | + transaction.save(Office(office.office_id, name='newer name', employees=[])) |
| 155 | +
|
| 156 | + with assert_condition_check_fails(), TransactWrite(connection=connection) as transaction: |
| 157 | + transaction.update( |
| 158 | + Office(office.office_id, name='newer name', employees=[]), |
| 159 | + actions=[Office.name.set('Newer Office Name')] |
| 160 | + ) |
| 161 | +
|
| 162 | + with assert_condition_check_fails(), TransactWrite(connection=connection) as transaction: |
| 163 | + transaction.delete(Office(office.office_id, name='newer name', employees=[])) |
| 164 | +
|
| 165 | +Batch Operations |
| 166 | +---------------- |
| 167 | +*Unsupported* as they do not support conditional writes. |
0 commit comments