#How are atomic locks used with requests?

25 messages · Page 1 of 1 (latest)

plain elm
#

I tried to find the solution online, but most setups are basic.
Lets say you have a product in stock, and you want to make sure nobody buys the product if it isn't is stock.
Good, I will make a form request that checks the stock, then I will reduce the quantity in the controller.
But the problem is, with parallel requests, the product can reach negative value.

Now, most tutorials I saw online, will check the stock inside the controller, not inside the form request. But how to do it in my case? I wanna send the stock error back to the user. not throw an error. Do I have to duplicate my logic inside the controller as well?

agile pawn
#

You should do this using DB locks

#

Let's say the stock model performs this operation, so this would look like:

DB::transaction(function () {
    $stock= Stock::lockForUpdate()->where('product_id', x)->get/find();
    $stock->balance -= 100;
    $stock->save();
});
#

The lock needs to be done inside a transaction

#

This is just a simple example. In the ideal world, you need to add layers to avoid deadlocks and long waiting times

#

If you use some sort of cache layer, you need to lock them as well for operations

plain elm
agile pawn
#

Then you keep the lock/open a new one right after to decrease the balance

#

If the first step fails due to insufficient stock, just cancel de request

#

You only reserve the stock for a sell if the payment process has started

#

They past beyond the cart and starting check-out

#

You'll need some sort of CQRS and Event Sourcing for the whole feature to work properly, but this i'm assuming a real software

plain elm
#

My problem was more into how to make the validation lock the stock

plain elm
#

Thank you

boreal pumice
plain elm
#

I forgot about middlewares...

#

But i have to test if i can put $next($request) inside the cache block function

#

Without breaking anithing