J
J
JaguXam2020-01-17 10:44:09
MySQL
JaguXam, 2020-01-17 10:44:09

How to make mysql process requests one by one in laravel 5.5?

The problem is the following.
The site can have 2-3 requests per second from one user.
There is a balance in the database, when he presses the pay button simultaneously with a millisecond, it is debited only 1 time, since the site or database does not have time to process this request, it goes at the same time.
At the moment I do so, do not judge strictly this is my first experience with the balance.
$this->user->money - $amount
$this->user->save();
Is it possible to somehow force the site to process requests to change balances in turn?
Thanks in advance for your reply.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Shumov, 2020-01-17
@JaguXam

And this is solved ... drum roll ... in bursts! Rabbitmq, Kafka and more. By the way, Keeping the balance directly in the user is a bad idea.
And if you think carefully, then you need to read about idempotent operations and not withdraw money from the account, but create a transaction initially and close it, Ama background, asynchronously, recalculate the balance

A
Alex Wells, 2020-01-17
@Alex_Wells

Open a transaction, pull out a user with a lock ->lockForUpdate(), perform your manipulations / checks, save, commit the transaction.

DB::transaction(function () use (&$user) {
    $user = User::whereKey($user->getKey())->lockForUpdate()->firstOrFail();
    if ($user->balance) // blabla
    $user->balance -= 100;
    $user->save();
});

Nothing more is needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question