Job and/or message queues is an important component of a modern web application. Simple calls like sending verification emails should always be pushed to a queue instead of done directly, as these calls are expensive and will cause the user to wait a while for the website to finish loading.
In this blog post I will write how to keep a stable queue-worker running on an ElasticBeanstalk environment with the help of the watchdog: Supervisor.
You will then most probably come to the conclusion that you need to run the following command for your queue to be actually processed:
$ php artisan queue:listen
Now, I have already seen the weirdest setups, but the most prominent might be maybe something like this:
$ nohup php artisan queue:listen &
The ampersand at the end will cause the call to go into the background, and the preceding nohup will make sure that it will keep running even if you exit your shell.
Personally I would always do something like this in a screen for various reasons – especially for convenience.
Anyways, on your server you will want this to run stable, for as long as possible, and automatically restart on crashes or server reboots.
This is especially true on ElasticBeanstalk, Amazon’s poorly but unfortunately popular implementation of a “Platform as a Service”:
- Nothing really has a state – instances can go down and up independently of the application
- This is especially true when AutoScaling is configured
- Deploying can crash the queue-listener
- The server could reboot for various reasons
- Your queue-listener could crash for various reasons (this happens the most)
- Application error (PHP exception, for example while working off a malformed payload)
- SQS is down (yup, it happens!)
To get a grip of this you definitely need to use some kind of watchdog. You can either go with monit or use Supervisor which I found was easier to configure.
Use the following .ebextension to achieve the following (abstract, but checkout the source 😉 ):
- Install Supervisor
- Make sure it runs after a reboot
- stop the queue-worker shortly before a new application version goes live
- start the queue-worker shortly after a new application version went live
You will notice that you have to set a new param SUPERVISE and set it to “enable” for the script to run. This allows me to switch it on – depending on the environment – or off, if a script is causing problems.
Also be aware, this will only work with newer ElasticBeanstalk versions (1.3+).
I almost forgot to mention the following commands (do not run as root!) that will help you around.
Display last Worker Output
$ supervisorctl tail -1000 laravel_queue
Display last Worker Errors
$ supervisorctl tail -1000 laravel_queue stderr
Display Worker Status
$ supervisorctl status
$ supervisorctl start laravel_queue
$ supervisorctl stop laravel_queue