💎Rails tip: Load async

Sebastien Auriault
Feb 19, 2022
Did you know that Rails 7 added a way to run queries in parallel? This can give good performance gains if you have multiple queries in a single controller action. Example below ⬇️

# config/application.rb
config.active_record.async_query_executor = :global_thread_pool
# :multi_thread_pool executor can be used if you have multiple databases

# app/controllers/dashboards_controller.rb
class DashboardsController < ApplicationController
  def show
    # These queries will all run asynchronously
    # instead of running one by one
    @posts = Post.limit(500).load_async
    @users = User.limit(500).load_async
    @products = Product.limit(500).load_async
  end
end

Be careful using this, it will speed up your views but will spam your database faster too.