skip to content

In a Rails 8.1 controller, what does calling load_async on several relations buy you, and when does it quietly run each query in the foreground instead?

level: seniorimportance: should knowfreq 28%

answer

  1. schedules the SELECT on a thread pool
  2. async_query_executor defaults to nil
  3. inside a transaction it runs synchronously
  4. ASYNC prefix in the SQL log
  5. each pool thread needs a connection

basics

~20 s

load_async schedules a relation's SELECT on a background thread pool so independent queries overlap; with the default nil executor, inside a transaction, or on an adapter without concurrent connections, it loads immediately in the calling thread.

solid answer

~40 s

`@articles = Article.published.featured.load_async` returns the relation at once and hands its SELECT to a thread pool; when the view iterates, the records are ready or the thread waits, and if no pool thread has started it yet, the calling thread runs it. Several `load_async` calls in a controller let a travel magazine's home page fetch featured, recent and popular articles in parallel. It only works when `config.active_record.async_query_executor` is `:global_thread_pool` or `:multi_thread_pool`; the default `nil` makes `load_async` an immediate synchronous `load`. Inside an open transaction it also runs synchronously, because another connection could not see uncommitted rows. Each background query takes its own connection, so `max_connections:` in database.yml must cover web threads plus pool threads. Background runs show an `ASYNC` prefix in the SQL log.

code

ruby · 10 lines
ruby
# config/application.rb
config.active_record.async_query_executor = :global_thread_pool

# in a controller
@featured = Article.featured.limit(5).load_async
@featured.scheduled?  # => true while the pool owns it

Article.transaction do
  Article.published.load_async  # runs synchronously here, no error
end

go deeper

for a junior

Recall that load_async starts a relation's query in the background and that the records are used as usual afterwards.

for a middle

Explain the executor settings, why the default nil makes load_async a synchronous load, and how the view thread waits for or runs the query.

for a senior

Show that you size max_connections for web plus async threads, keep load_async out of transactions where it buys nothing, and confirm parallelism through ASYNC log lines.

for a principal

Weigh parallel queries per request against the database's total connection budget across web, job and console processes, and against caching or denormalising the slow pages.

## What load_async does `load_async` is the asynchronous counterpart of `load` for an Active Record relation. Instead of running the SELECT in the calling thread, it **schedules** the query on a background thread pool and returns the relation straight away: ```ruby def index @featured = Article.featured.order(published_at: :desc).limit(5).load_async @recent = Article.published.order(published_at: :desc).limit(20).load_async @popular = Article.published.order(views_count: :desc).limit(10).load_async end ``` All three SELECTs are in flight while the action finishes and the template starts. When the view first iterates `@featured`: 1. if the background query has finished, the records are already there; 2. if it is running, the view thread waits for it; 3. if no pool thread has picked it up yet, the view thread runs it itself. The relation is marked as loaded immediately (`loaded?` is `true`) and `scheduled?` reports that a background result is pending. ## The executor is off by default | `config.active_record.async_query_executor` | `load_async` behaviour | |---|---| | `nil` (default) | runs `load` at once, in the calling thread | | `:global_thread_pool` | one pool for every database; size `global_executor_concurrency` (default 4) | | `:multi_thread_pool` | one pool per database, sized by `max_threads` / `min_threads` in database.yml | With the default, `load_async` is **not lazy**: it loads immediately, which is the opposite of an unloaded relation. That is harmless when the records are used anyway, and it means the code can adopt `load_async` before the pool is switched on. ## When it quietly runs in the foreground Even with an executor configured, the query runs synchronously in these cases: - **Inside a transaction.** If the connection has an open transaction, `load_async` executes the SELECT in the calling thread, because a pool thread would use another connection that cannot see the transaction's uncommitted changes. Unlike the async calculation methods, it does not raise. - **Adapters without concurrent connections**, such as an in-memory SQLite database. Separately, on a relation that is already loaded, `load_async` is a no-op and the cached records are used. The SQL log tells them apart: a query that ran on the pool is printed with an `ASYNC` prefix and how long the caller waited for it. No prefix means it ran in the foreground. ## Connections and capacity Each background query checks out its **own** database connection. The configuration guide's rule of thumb is a pool of at least web threads + `global_executor_concurrency` + 1; with 3 Puma threads and the default concurrency of 4, that is 8. In Rails 8.1 the pool key in database.yml is `max_connections:` (`pool:` is the name used before 8.1). An undersized pool turns parallel queries into connection waits. ## A worked example Suppose the three home-page queries above take 80, 120 and 60 milliseconds. Loaded one after another they cost about 260 ms before the page can render. With an enabled executor and enough connections, they run side by side, and the wait is roughly the slowest one, about 120 ms, plus a little hand-off overhead. Two conditions make that true: - the relations are created at the **start** of the action, before any of them is iterated; - nothing in between reads them, because the first iteration blocks until that query finishes. ## When it pays off - Several **independent**, individually slow queries on one page or endpoint. - Not for fast queries: hand-off and connection checkout cost more than they save. - Not across dependent steps: if the second query needs the first one's ids, it has to wait anyway. `reset` on a relation with a scheduled load cancels the pending result, and later access runs the query again. For single values such as a count, Active Record has separate async calculation methods; `load_async` is for full record sets.

  • How does `load_async` inside a transaction differ from `async_count` inside one?
    With an executor enabled, `load_async` inside a transaction quietly runs its SELECT synchronously in the calling thread. The async calculation methods raise `ActiveRecord::AsynchronousQueryInsideTransactionError` instead. Both avoid a background connection that cannot see uncommitted rows; only the reaction differs.
  • How do you prove in development that the home page's queries ran in parallel?
    Enable the executor in development, load the page and read the SQL log: queries executed by the pool carry an `ASYNC` prefix with the time the caller spent waiting. Missing prefixes mean the executor is `nil`, the queries ran inside a transaction, or the view read the relation before a pool thread started it.

  • load_async works out of the box in every new Rails app
  • load_async defers the query until the relation is first iterated
  • load_async inside a transaction raises AsynchronousQueryInsideTransactionError
  • background queries reuse the request's connection, so the pool size can stay the same
  • loaded? returning true proves the rows are already in memory

Assumes Rails 8.1, where database.yml's connection pool key is max_connections: (pool: before 8.1).