# Optimistic Locking

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

{% hint style="info" %}
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](https://app.gitbook.com/o/z8MNPigQv25NZe33g3AV/s/d4POTWomuSS7d3dnh4Dg/).\
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.
{% endhint %}

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.

{% hint style="success" %}
*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.
{% endhint %}
