ActiveRecord #load_async speeds up queries in Rails 7.0

The load_async method allows you to speed up queries by loading threads in an asynchronous way. It helps reduce the response time dramatically, especially for large databases. This method handles loading records, before they are referenced in the view, making the foreground thread do the work before it is sent to the background.

Instead of calling Relation#to_a in the background thread, which loses context, or even thread safety issues, the new Rails 7.0 method executes queries in parallel.

1
2
@cities = City.all.load_async
@companies = Company.order(updated_at: :desc).load_async

To enable this functionality, we need to set the value for async_query_executor in config/environments. By default, Rails initializes async_query_executor to nil. If load_async is called and the executor is not defined, the query runs in the foreground. There are two configuration options for aync_query_executor:

1
2
# config/environments/development.rb
config.active_record.async_query_executor = :global_thread_pool

Creates a common thread pool for all database connections.

1
2
# config/environments/development.rb
config.active_record.async_query_executor = :multi_thread_pool

Creates a unique thread pool for each database connection.