Laravel Defibrillator: Keep Application Tasks Running At a Normal Rhythm
Published on by Paul Redmond
Laravel Defibrillator is a package by Michael Dyrynda that helps you ensure that aspects of your application should be running regularly are doing so.
📣 I *really* went off the deep end and now present to you Laravel Defibrillator - a small package to help your application tasks keep a normal rhythm.
— Michael Dyrynda 💉💉 (@michaeldyrynda) September 6, 2021
Prevent your tasks from overwhelming your database, queue workers, mail provider, and more!https://t.co/7yIqUuyFV8
This package can help by delaying the adding of jobs to overwhelmed queue workers while they catch up on a backlog of queue jobs, for example:
Consider a scheduled task that communicates with your application users on a regular interval. This scheduled task queues notifications to your users based on some condition within your application. In a normal situation, there is a handful of notifications to go out, and they are dispatched with in a few seconds. But an application error causes your application to spiral out of control. Queued notifications back up, your database is not being updated to flag notifications as having been sent, your error tracker floods with exceptions.
And then your scheduled task runs again.
Suddenly your queue has tens of thousands of pending jobs in it and you're stuck in a cycle that you can't keep up with.
Here's an example from the readme of how you might use this trait to keep an normal rhythm:
// app/Console/Kernel.php$schedule->job(NotifyUsers::class)->everyMinute(); // app/Jobs/NotifyUsers.phppublic function handle(){ if ($this->hasAbnormalRhythm()) { $this->defibrillate(); return; } // Regular processing $this->defibrillate();}
You can also prevent lagging notifications from being sent if the heartbeat enters an abnormal rhythm:
// app/Notifications/CustomerNotification.phppublic function shouldSend(): bool{ return Cache::get('NotifyUsers')?->isFuture() ?? false;}
This package has sensible defaults for an interval between normal rhythms, which are customizable when using the package's Defibrillator
trait:
use Defibrillator; public function interval(): int{ return 30;}
You can learn more about this package, get full installation instructions, and view the source code on GitHub.