Laravel Defibrillator: Keep Application Tasks Running At a Normal Rhythm


September 9th, 2021


Laravel Defibrillator is a package by Michael Dyrynda that helps you ensure that aspects of your application should be running regularly are doing so.

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:

1// app/Console/Kernel.php
4// app/Jobs/NotifyUsers.php
5public function handle()
7 if ($this->hasAbnormalRhythm()) {
8 $this->defibrillate();
10 return;
11 }
13 // Regular processing
14 $this->defibrillate();

You can also prevent lagging notifications from being sent if the heartbeat enters an abnormal rhythm:

1// app/Notifications/CustomerNotification.php
2public function shouldSend(): bool
4 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:

1use Defibrillator;
3public function interval(): int
5 return 30;

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners