Optimistic Locking

Ensure smooth simultaneous work for multiple users with optimistic locking mechanism.

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 entities that have metadata.version field defined use the optimistic locking. Entities that don't have such field defined, don't support optimistic locking. You can check if a particular entity has that field defined in our API Documentation. For API calls, ensure to provide the correct metadata.version in PUT operations to turn on the optimistic locking feature. For PATCH operations, providing metadata.version is optional, so if you don't provide the value, optimistic locking is skipped.

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:

  1. 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.

  2. 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.

  3. Document update: The mechanism updates the metadata fields:

    • metadata.version increased by 1

    • metadata.modifiedAt set to the current time

  4. 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.

Last updated

Was this helpful?