Optimistic Locking
Ensure smooth simultaneous work for multiple users with optimistic locking mechanism.
Last updated
Was this helpful?
Ensure smooth simultaneous work for multiple users with optimistic locking mechanism.
Last updated
Was this helpful?
Optimistic locking is a concurrency control mechanism that prevents overriding another user's changes when multiple transactions accessing the same data are happening simultaneously. The main idea behind it is to avoid the use of locks and instead assume that conflicts between operations are rare. With optimistic locking, we can ensure better performance of the Emporix applications.
Within Commerce Engine, optimistic locking is based on the metadata.version
field. It's supported at the API level, but it also works within Management Dashboard directly.
All the metadata
fields are set during a document creation in the database, and their values are as follows:
version = 1
createdAt = Instant.now()
modifiedAt = Instant.now()
Here’s how optimistic locking works:
Version check: Triggered by an API request or an action within Management Dashboard, the optimistic locking mechanism checks if the request includes the metadata.version
field.
Transaction processing: The transaction proceeds with the requested changes and updates the data tentatively only in memory, excluding id
and metadata
fields from the payload.
Document update: The mechanism updates the metadata
fields:
metadata.version
increased by 1
metadata.modifiedAt
set to the current time
Database update: The relevant document with matching id
and metadata.version
is found in the database and updated accordingly. However, if the document cannot be found due to the fact that another operation that has run in the system modified the same data in the meantime, the system throws an exception error, prompting the user to retry the operation.
Example
The Management Dashboard user, Tom, opens the ABC
product to edit it. At the same time, another user, Michael, opens the same ABC
product for edition. Michael is quicker to complete and save his changes. When Tom wants to save the product after he's done with his changes, he gets an error notification, because in the meantime the document version has changed. Tom needs to reload the product in order to make his updates.