skip to content

In Rails 8.1, what do async_count and async_sum return, and what must be configured before a dashboard's totals actually run in parallel?

level: seniorimportance: nice to knowfreq 22%

answer

  1. added in Rails 7.1
  2. ActiveRecord::Promise, read with value
  3. async_query_executor defaults to nil
  4. :global_thread_pool, 4 threads by default
  5. enabled pool plus open transaction raises

basics

~20 s

async_count, async_sum and the other async calculations return an ActiveRecord::Promise whose value blocks for the result; they only run in the background when config.active_record.async_query_executor is set, and the default nil runs them in the foreground.

solid answer

~30 s

`Sale.where(store_id: 7).async_sum(:amount)` returns an `ActiveRecord::Promise` instead of a number; calling `value` waits for the query and returns the same result `sum` would, re-raising any database error. With `config.active_record.async_query_executor` left at its default `nil`, the query simply runs immediately in the calling thread, so nothing is gained. Setting it to `:global_thread_pool` (with `global_executor_concurrency`, default 4) or `:multi_thread_pool` lets several totals run on background threads while the controller does other work. Each background query holds its own connection, so `max_connections:` in database.yml must cover web threads plus executor threads. Inside an open transaction an enabled async calculation raises `ActiveRecord::AsynchronousQueryInsideTransactionError`.

code

ruby · 3 lines
ruby
# config/application.rb
config.active_record.async_query_executor = :global_thread_pool
config.active_record.global_executor_concurrency = 4

go deeper

for a junior

Recall that async_count and friends return an ActiveRecord::Promise and that you read the number with value.

for a middle

Explain that the default executor is nil, what :global_thread_pool and :multi_thread_pool change, and why value blocks.

for a senior

Show that you size max_connections for web threads plus executor threads, keep async calls out of transactions, and verify ASYNC in the logs before claiming a speed-up.

for a principal

Weigh parallel aggregate queries against caching or precomputed rollups, considering connection budgets across every process that shares the database.

## What the async calculations are Rails 7.1 added asynchronous versions of the Active Record calculation and value methods: `async_count`, `async_sum`, `async_average`, `async_minimum`, `async_maximum`, `async_pluck`, `async_pick` and `async_ids`. Each takes the same arguments as its synchronous twin but returns an **`ActiveRecord::Promise`** instead of the value. A Promise exposes a small API: - `value` returns the result, **blocking** until the query has finished, and raises the query's error if it failed. - `pending?` reports whether the query is still running. - `then { |result| ... }` returns a new Promise that applies the block when `value` is read. The point is to overlap independent slow aggregates. A hardware chain's dashboard might need this month's revenue, the number of open orders and the largest sale. Run synchronously they add up; started together, total wall time approaches the slowest one. ```ruby revenue = Sale.where(sold_on: Date.current.all_month).async_sum(:amount) orders = Order.where(status: "open").async_count largest = Sale.where(sold_on: Date.current.all_month).async_maximum(:amount) @revenue, @orders, @largest = revenue.value, orders.value, largest.value ``` ## The executor: off by default Nothing runs in the background until an executor is configured. | `config.active_record.async_query_executor` | Behaviour | |---|---| | `nil` (default) | the query runs immediately in the calling thread; the Promise is already resolved | | `:global_thread_pool` | one thread pool for all databases, sized by `config.active_record.global_executor_concurrency` (default 4) | | `:multi_thread_pool` | one pool per database, sized by `max_threads` and `min_threads` in that database's database.yml entry | With the default, `async_sum` behaves like `sum` with an extra `.value`. Code written against the async API keeps working when the executor is switched on later, which is why teams sometimes adopt the methods first and enable the pool once connections are sized. When a query did run on a background thread, the SQL log line is prefixed with `ASYNC`, which is the quickest way to confirm the configuration took effect. ## Connections are the real cost Every background query checks out its own database connection. The Rails configuration guide's rule is that the pool should hold at least **web server threads + `global_executor_concurrency` + 1**: with 3 Puma threads and an executor of 4, that is 8. In Rails 8.1 the pool size key in database.yml is `max_connections:` (`pool:` is its older name). Undersize it and requests start waiting for connections, which is slower than the synchronous code the change tried to speed up. ## Rules and edge cases 1. **Transactions.** Inside a joinable transaction, an enabled async calculation raises `ActiveRecord::AsynchronousQueryInsideTransactionError`, because a background thread on another connection could not see the transaction's uncommitted rows. 2. **Unread promises.** If `value` is called before a pool thread has picked the query up, the calling thread runs it itself, so the result is never lost, only the parallelism. 3. **Adapters.** An adapter that cannot hold concurrent connections, such as an in-memory SQLite database, runs the query in the foreground. 4. **Only independent queries benefit.** If one total feeds the next query's conditions, the second must wait anyway. ## Start everything, then read The order of calls decides whether anything overlaps. The pattern is to **create every Promise first and read the values afterwards**: - Correct: three `async_*` calls, then three `value` reads. All three queries are queued before the first read blocks. - Wasted: `Sale.async_sum(:amount).value` on one line. The read blocks straight away, so the code is a slower `sum`. - Readable: do the reads in the controller and hand plain numbers to the view, so a template never blocks halfway through rendering and errors surface where they can be rescued. Exceptions travel with the Promise. A timeout or a missing column raised on the pool thread is re-raised in the calling thread when `value` is read, so the usual `rescue` around the read still works. ## When to reach for it - A page or API endpoint that issues several independent, individually slow aggregates. - Not for fast queries: thread hand-off and connection checkout add overhead. - Not as a substitute for indexing, caching or precomputed rollups when a single aggregate is slow. Loading records asynchronously with `load_async` on a relation is the sibling feature for full result sets; the async calculations are the variant for single values.

  • Why does an enabled async_count inside `transaction do ... end` raise instead of running?
    The background thread would use a different connection, which cannot see the transaction's uncommitted writes, so its count could disagree with the data the block just changed. Active Record refuses with `ActiveRecord::AsynchronousQueryInsideTransactionError`; compute the number synchronously inside the transaction or asynchronously after it commits.
  • How do you confirm in development that the dashboard's totals ran in the background?
    Look at the SQL log: a query executed by the async pool is logged with an `ASYNC` prefix and its lock wait time. If the lines lack the prefix, the executor is still `nil`, the adapter cannot run concurrent connections, or `value` was read before a pool thread took the query.

  • async_sum returns the number directly, just computed on another thread
  • the async methods run in the background out of the box in a new Rails app
  • background queries share the request's connection, so the pool size can stay unchanged
  • an async calculation inside a transaction quietly waits until commit
  • global_executor_concurrency can be set while async_query_executor is :multi_thread_pool

Assumes Rails 8.1; the async calculation methods arrived in Rails 7.1, and database.yml's pool key is max_connections: in 8.1 (pool: before).