DynamoDB knowledge portalHow do I handle versioning of items in DynamoDB?3 min

One of the common use cases for DynamoDB is to store and track changes to data over time, such as the state of a device, the status of an order, or the history of a document. Depending on specific requirements in each use case, this can be achieved in multiple ways.

Time-based versioning

In simpler cases where items update regularly over time and concurrent updates to an item version are not possible, time-based versioning is often the best solution. An example of a use case that would fit this model is devices that regularly report their current status.

Time-based versioning is implemented by using a timestamp as the sort key. When using a sort key, items with the same partition key are stored together as an item collection, enabling flexibility through queries.

To find the latest version of an item, a query with the ScanIndexForward parameter set to false is used. This means results are sorted from the latest to earliest. The Limit parameter can also be set to “1” to retrieve only the most recent item – the latest version written.

Number-based versioning

In some cases, version numbers may be desirable instead of timestamps. This is particularly true where multiple processes may be independently updating a version and controls must be put in place to ensure consistency. An example of a use case that would fit this model is a wallet balance which can increase or decrease as transactions are processed.

Number-based versioning is implemented by using a version number as the sort key, with “v0” always containing the most current version of the record as well as a “Latest” attribute pointing to the most recent version number. When an update is made, both the “v0” record is updated and a new item is written for the new current version.

When writing a new version, “v0” can first be read to retrieve current values and the latest version number. Attribute values can then be modified as desired, such as adding to a wallet balance, and the item updated using a condition-expression on the “Latest” attribute. Using a condition-expression as part of the update only allows it to succeed if the item has not been changed by another process. The new item for the current version can be written together with the “v0” update as part of a transaction or after the update, depending on use case requirements.

Further Reading

A more in-depth discussion of these designs for item versioning, along with example data models and code snippets, can be found at https://aws.amazon.com/blogs/database/implementing-version-control-using-amazon-dynamodb/


Created by: