Rails 7
Schedule queries on the background thread pool for asynchronous processing

Apr 19, 2021

It is quite common to execute multiple queries in a controller action. Just as an example, there might be a dashboard that displays data from multiple models or scopes.

class DashboardController < ApplicationController
  def index
    @recent_comments = Comment.recent(10)
    @overdue_tasks = Task.overdue
    @my_projects = Project.assigned_to(current_user)
  end
end

These queries will be executed sequentially, which might not be an issue in most cases. But as the amount of data grows, it can get noticeable after a while.

It has been possible to defer this to a separate thread even before, but it usually means a little bit of tailoring and it can easily get messy. It also has a tendency to break certain "Rails magic" features.

But not anymore. Coming in Rails 7 is a new method called load_async which effectively schedules the query to be executed asynchronously. It also resolves the scenarios where you are trying to access the result before the background process has finished, in which case it is simply processed in the foreground just as it normally would be.

@recent_comments = Comment.recent(10).load_async
@overdue_tasks = Task.overdue.load_async
@my_projects = Project.assigned_to(current_user).load_async

Do note that this requires some thought into when this actually makes sense. For this feature to be useful, it is important that you can start the longer running queries early, continue with some additional processing, then return to check the result of the background query when it almost certainly has finished.

Thank you for reading and Happy Coding!