Optimistic Locking in REST API

Talha Toparli
3 min readJan 16, 2024

--

Optimistic concurrency control (OCC), also known as optimistic locking, is a non-locking concurrency control method applied to transactional systems such as relational database management systems and software transactional memory. OCC assumes that multiple transactions can frequently complete without interfering with each other. While running, transactions use data resources without acquiring locks on those resources. Before committing, each transaction verifies that no other transaction has modified the data it has read. If the check reveals conflicting modifications, the committing transaction rolls back and can be restarted. (https://en.wikipedia.org/wiki/Optimistic_concurrency_control)

The application is used to unlock the rows which is in processing (update/delete etc.) One of the advantages of the optimistic locking is improved concurrency, other users or applications can read or write the row simultaneously.

Optimistic Locking in Sequelize;

Optimistic locking is disabled in sequelize by default and can be enabled by setting the version property to true in a specific model definition. See more https://sequelize.org/docs/v6/other-topics/optimistic-locking/

Optimistic Locking is possible in API?

The question is the aim of this essay. In a huge project which has lots of tables that are combined directly or indirectly with each other. In one transaction affects more than one table at the same time. Also, if you have lots of users that want to use the same transactions including(update, delete or create operations) how can you save the variables correctly and keep your data safe? Here is the complex question that needs to be solved.

To make the API clean simple clever, the following example will help you for further projects.

Here is the one clean solution to prevent other users when the service is under processing. Set one variable out of the service which will be zero initial value, then the variable will be one after the process is started. The line # 218–220 helps us to prevent the service from any corruption from the other users and return them out of the service when the variable is not one. If the variable is one, the service will complete the process soon.

The service should also have try..catch..finally statements. As you know, the statement helps to catch the error during the process. If the system collapses, it will raise an error including an error message to the user. At the end of the transaction, you can add finally statement to do the last response even if the transaction raises an error. Here, we will write another critical code to finalize it smoothly.

The variable should be zero at the end of the transaction for continuity.

I hope that small, basic but critical attachment will enhance your way in your project.

Happy coding…

--

--

Talha Toparli

Full Stack Developer | Electrical and Electronics Engineer | Former Diplomat | Chess Addict |