[Resolved] – MySQL lock wait timeout exceeded using Laravel queues and jobs

Valerio Barbera

Hi, I’m Valerio, software engineer and CTO at Inspector.

One of the most readed article I’ve posted on our blog is related to a queue and jobs configuration in a Laravel application. Queues and Jobs introduces parallel tasks execution in your app that is one of the most interesting field for any developers committed to grow a digital business and it’s also the first step to scale your app keeping server resources cost-friendly.

So I decided to write about some side effects that queues adoption can causes in your application providing possible solutions based on my real life experience.

Use database transactions

One of the most known uses of database transactions is that when an error occurs the transaction can rollback, and any changes you made to the database within that transaction are rolled back as well.

Data Integrity

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);

    DB::table('posts')->delete();
});

This is a really useful thing when your code needs to update multiple tables and run some complicated task that could produce exceptions. In that case all previous data changes will not be applyed to the database keeping your data consistent with itself.

Concurrency

Another thing database transaction can help us with is “concurrency”.

In a highly concurrent environment (that’s what we want to build) where the application needs to update resources on the database a lot like multiple jobs that want update the same record in the same table, you can handle this situation retrying to execute e blocked transaction:

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);

    DB::table('posts')->delete();
}, 5);

Where the second parameter “5” is the number of times a transaction should be reattempted before close the transaction (rolled back) and thrown the “Lock wait timeout” exception.


After becoming familiar with queues and jobs you risk to see a bunch of exceptions appearing in your log files.

That was my case.

My experience

I was struggling with this issue in a scenario where I needed to update a date-time field in a table called “recently_executed_at” from many concurrent jobs that try to execute the update on the same record in the same time, causing the “lock wait timout” execption as descibed above.

This is not a solution:

DB::transaction(function () use ($project) {
    $task->update(['recently_executed_at' => now()]);
}, 5);

because after attempting the execution for 5 times it throw an exception.

For me was not important to have this field updated with the real last execution time from the last executed job, I just need a reasonable recently timestamp to show in the frontend as additional information.

So if another job is locking the row for update I just want to skip this statement in all others jobs.

Reading and dealing with Pessimistic/Optimistic locking sent me off the road for several days. In such scenario the solution was to deal with “Race Condition” (multiple jobs try to update the same database record at the same time).

In the Laravel documentation you can find the solution in the Cache section as “Atomic Lock”. It took me almost a week of research to understand that the “Atomic Lock” in the Cache driver could solve my problem 🤕 🤕 🤕 .

Final code

Cache::lock("task-{$task->id}-update")->get(function () use ($task) {
    $task->update(['recently_executed_at' => now()]);
});

It was enough to wrap the update statement in a closure whose execution is conditioned by the LOCK. If the lock isn’t available (another job is executing the update) the code block will be skipped.

Note that you need to create the lock name based on the “record id” to manage the race condition on a specific record at a time and not on entire table.

Monitoring

Running in background you can’t see immediately if your jobs consume all server resources or generate errors.

You will no longer have immediate feedback like from the result of an http request.

If the job fails he will do it silently, without anyone noticing. That’s exactly what Inspector was desgined to do.

If background jobs or artisan command are an indispensable component for the operation of your app you can learn more about monitoring in our step by step guide: Laravel background jobs & commands monitoring with Inspector.

Conclusion

If you want learn more about Inspector visit our website (https://www.inspector.dev) and start monitoring your application for free in just two minutes to find out issues before your users do.

Related Posts

NodeJs Real-Time Execution Monitoring with Inspector

Have you ever desired to watch your code running, instead of just imagining it? Hi, I’m Valerio software engineer from Italy and CTO at Inspector. As product owner I learned on my skin how an application issue can be so hard to fix, creating a negative impact on the users experience, or block new potential

How to accelerate application performance with smart SQL queries.

Why so many performance issues are caused by the database? We often forget that each request is not independent of other requests. If one request is slow, it’s unlikely to affect the others… right? Database is a shared resource used by all processes that runs in your application. Even just one poorly designed access can

Application monitoring tools – Why, when, what!

In this article I reported my experience working on large applications, and how monitoring cames in my journey when I started producing software designed to solve business critical problems. Hi, I’m Valerio, software engineer from Italy and CTO at Inspector. Solve customers critical problems can generate great business opportunities, but in these situations you need

Stop losing customers and money
due to technical problems in your applications

Monitor performance of your code execution in real-time and identify bugs and bottlenecks before your users do.
Real-Time Application Monitoring Platform.
2020 © Inspector S.R.L - VAT: 09552901218