Resolve MySQL lock wait timeout dealing with Laravel queues and jobs

Valerio Barbera
Dec 2 · 4 min read

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 application users do.

Thank you so much for reading it. To make Inspector more sophisticated and mature, it will not be possible to accomplish without your help. Don’t hesitate to share your thoughts on the comment below or drop in live chat on our website! Let’s make it together.

Thank you for all your support!

Inspector

Real-Time diagnosis & alerting for Laravel application.

Valerio Barbera

Written by

Head of engineer at https://inspector.dev: “Real-Time autonomous monitoring for Laravel apps”

Inspector

Inspector

Real-Time diagnosis & alerting for Laravel application.

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