DEV Community

Saravana Sai
Saravana Sai

Posted on

Atomic locks in laravel explained in depth

What is Atomic lock?

Atomic lock is not a term directly related to a laravel itself.The term is actually from database.I hope you have know about ACID principle in database.They are

  1. Atomicity
  2. Consistency
  3. Isolation
  4. Durability

Atomic lock comes under the first property atomicity.To learn more about ACID property.

Let jump into practical usage:

Scenario:

In at some point of your dev life or else you may have built a e-commerce application or some kind of reservation system.just think of the situation in e-commerce application two user where placing the order at same time.but,the stocks left is only 1.As we know all web application process request in concurrently it may cause some in-consistency.

example: 2-orders may placed but we know that only 1 left in stock.

How will handle this situation? roll up your heads for some time for solution just share your idea in comments if you faced the same kind of situation and how did you handle this problem?

if you are love to watch video based content for the solution then just watch the video below & subscribe the channel in YouTube called LaravelDaily.This article is inspired from this video content

For this kind of solution where the Laravel Atomic lock come into play which help us to handle this problem like pro.

Image description

You can write application logic inside the Cache::lock method & the that time you specified it wont process other request under the hood laravel uses database driver to implement this feature for you.Once the specified time is completed it will process the next request in a queue.

So,The first order get placed after that the stock left would become 0,because we are processing the request in a queue.when a second request comes in the stock left is 0.the second order get rejected.you can use this for all kind of raced scenario also example ticket reservation & hotel bookings etc.

Hopefully this will be useful to some of you :)

I'd love to hear what you're comments & more example let me know in the comments below!

Follow for more content like this & share

Top comments (3)

Collapse
 
naucode profile image
Al - Naucode

Hey, that was a nice read, you got my follow, keep writing 😉

Collapse
 
nova_ardiansyah_bd808ca22 profile image
Nova Ardiansyah

"in depth", really i hope better article lol

Collapse
 
emadevto profile image
Emanuel Aguirre

I think you should remove the "in depth" word from the title. I was expecting to see the under the hood logic on the redis driver too.