Image for post
Image for post

Pessimistic vs Optimistic Locking in Laravel

Ali AslRousta
Nov 17, 2017 · 4 min read

Introduction

When two or more clients want to update the same record, a conflict may occur which is known as a race condition. To prevent such a conflict, a pessimist system assumes the worst, i.e., the updates always occur at the same time. Thus, it eliminates the race condition by locking the record. Pessimist systems typically rely on the database locking facilities; for example InnoDB’s row-level lock.


Application

To benchmark both mechanisms, we consider a simple application: a banking system consisted of several accounts, and each account having a balance. The system is supposed to provide an API, called transfer, which transfers a given amount from one account to the another. To prevent race conditions, which can cause transferring an insufficient fund or losing the transferred amount on the receiving account, the application has to use a locking mechanism.

Pessimistic Transaction
Optimistic Transaction

Benchmark

Both implementations are run using valet³ and MySQL database. Then, they are put into test using locust with the same initial dataset⁴ on the same machine⁵.

  • The pessimistic approach results in about 3 RPS with 45% of the requests being failed.

SUMMARY

Both pessimistic and optimistic locking mechanisms have use cases that they fit in, however, for systems with high loads of updates which hold locks for a significant time interval, the latter shows better efficiency. Also, it must be noted that the higher RPS doesn’t necessarily means a faster algorithm, since an important amount of requests are failed because of the lock-wait errors in the pessimistic mechanism.


Next Step

This article represents a naive, error-prone implementation for optimistic locking. There are third-party libraries which provide a more robust implementation with more features. The same benchmark can be performed by such implementations.


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store