Background jobs are a crucial component of many Ruby on Rails applications. With the introduction of ActiveJob, Rails developers can now manage background jobs as seamlessly as they do their database records. However, ActiveJob requires the selection and support of a backend adapter to implement its backend functionality. Many developers opt to use Redis, a memory cache, to queue and process background jobs due to its incredible speed. Despite this, Redis adds another dependency that needs to be maintained.
Solid Queue is a new backend for ActiveJob that was unveiled at Rails World, along with Solid Cache. Unlike Redis, Solid Queue moves away from memory solutions and utilizes the database for queuing and processing background jobs. This approach takes advantage of the speed improvements in databases over the years, enabling efficient background job processing at scale. While processing background jobs in the database may be slower, it provides more queue space at a lower cost compared to memory. When combined with Mission Control, Solid Queue simplifies background job processing and monitoring for developers, making it more affordable as well.
To demonstrate how to write a background job using ActiveJob in Rails, we will create a simple animal shelter app. This app will allow users to create, read, update, and delete dogs from the database. Additionally, we will add a feature to track the last time a dog was walked and set up a background job to update the model attribute if the dog needs to be walked.
Setting up the Rails app involves creating a new Rails 7.1 app and generating the necessary components for tracking dogs using the scaffold command. After setting up the app, we will write a background job to send a notification when a dog has not been walked for more than 8 hours. This job will be triggered whenever a new dog is created in the app.
Using Solid Queue for ActiveJob is straightforward. By adding the Solid Queue gem to the Gemfile, installing the gem, generating migrations and configurations, and setting the ActiveJob adapter to :solid_queue, developers can leverage Solid Queue for efficient background job processing.
Deploying a Rails app with Solid Queue is simplified compared to Redis-backed alternatives like Sidekiq, as Solid Queue eliminates the need to manage a separate Redis instance. While deploying Solid Queue alongside the app server may consume shared resources, using the Puma plugin can streamline deployment. Additionally, Mission Control – Jobs offers a tool for monitoring and managing background jobs within the application, providing insight and facilitating incident response. By adding the Mission Control gem to the Gemfile, mounting it in the routes file, and accessing it through the localhost, developers can effectively monitor and manage background jobs.
Source link