I recently started using dynamo DB and was wondering if it's possible to do transactions involving fetching an item and updating another item based on data from first item? My initial belief is it is not possible with transactional server side api provided by dynamodb but it is possible with client side dynamodb-transactions library provided by awslabs. Any example code for the same in server side api will be much appreciated.
Update: My data model looks like this:
| objectId(Hash Key) | startTime(Sort Key) | endTime | nextStartTime |
|---|---|---|---|
| 1 | 1 | 5 | 4 |
| 1 | 4 | 6 | 8 |
| 1 | 8 | 10 | 9 |
So, it's possible a new entry comes in whose start time is 5. So, in transaction I will have to update nextStartTime for second entry to 5 and insert a new entry after the second entry which contains nextStartTime as start time of third entry. During this another entry might come in which also has start time between second and third entry(say 7 for eg.). Now I want the two transactions to be isolated of each other. In traditional SQL DBs it would be possible as second entry would be locked for the duration of transaction but Dynamo doesn't lock the items. So, I am wondering if I use transaction would the two transactions protect the data integrity.
The way to solve it with DynamoDB is to use the conditional expressions in put_item, update_item, or delete_item. The put will fail (similar to the rollback of a transaction) if the condition is not met.
aws dynamodb update-item \
--table-name SortedList \
--key '{"objectId": {"N": "1"}, "startTime": {"N": "4"}}' \
--update-expression "SET nextStartTime = 5" \
--expression-attribute-values "{"nextStartTime": { "N": "4"}}"
With the above expression-attribute-values you make sure that the update will fail if the current value is not as you expected, and maybe someone already updated the value in a different thread. In such a failure case, you can read the records again, and try to update with the current value, and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With