Understanding Locking and Conditional Writes in AWS DynamoDB

Optimistic locking is a strategy to ensure that the client-side item that you are updating (or deleting) is the same as the item in DynamoDB. Optimistic concurrency depends on checking a value upon save to ensure that it has not changed. If you use this strategy, then your database writes are protected from being overwritten by the writes of others — and vice-versa.

By default, the DynamoDB write operations (PutItemUpdateItemDeleteItem) are unconditional: each of these operations will overwrite an existing item that has the specified primary key.

DynamoDB optionally supports conditional writes for these operations. A conditional write will succeed only if the item attributes meet one or more expected conditions. Otherwise, it returns an error. Conditional writes are helpful in many situations. For example, you might want a PutItem operation to succeed only if there is not already an item with the same primary key. Or you could prevent an UpdateItem operation from modifying an item if one of its attributes has a certain value. Conditional writes are helpful in cases where multiple users attempt to modify the same item.

In the AWS SDK for PHP, there is a PessimisticLockingStrategy class for DynamoDB. This locking strategy uses pessimistic locking (similar to how the native PHP session handler works) to ensure that sessions are not edited while another process is reading/writing to it. Pessimistic locking can be expensive and can increase latencies, especially in cases where the user can access the session more than once at the same time (e.g. ajax, iframes, or multiple browser tabs).