On a job board with millions of listings, what COUNT does Kaminari's total_count run for paginate @listings, and how would you keep it affordable?
answer
- drops limit, offset and order
- includes kept only when referenced
- a grouped count returns the group count
- max_pages bounds the count
- paginate accepts total_pages:
basics
~20 stotal_count runs COUNT(*) over the relation without its limit, offset and order, once per relation object. Keep it affordable with indexes on the filters, max_pages to bound it, a precomputed total_pages: for paginate, or without_count.
solid answer
~50 s`paginate` and `page_entries_info` call `total_count`. It takes the relation, removes `offset`, `limit` and `order`, drops `includes` unless the conditions reference those tables, and runs `count(:all)`. On a filtered search over millions of listings, that `COUNT(*)` visits every match on every page view, often costing more than the page query. The result is memoized per relation object, and when the records are already loaded on the last page Kaminari works the total out from them instead. With `group`, the count is a Hash and Kaminari takes its size, so one row per group comes back. To bound it: `config.max_pages = 100` (or `max_pages 100` on the model) counts at most `100 * per` rows in a limited subquery and caps `total_pages`. `paginate @listings, total_pages: n` takes a cached figure and skips the call, and `without_count` drops counting altogether.
code
ruby · 4 lines# config/initializers/kaminari_config.rb
Kaminari.configure do |config|
config.max_pages = 100 # count at most 100 pages' worth of rows
endgo deeper
Know that paginate and page_entries_info need a total, and that Kaminari gets it with a separate COUNT query.
Explain what total_count strips from the relation, when it deduces the total without a query, and how group and includes change it.
Bound the cost on big tables with indexes, max_pages, a supplied total_pages: or without_count, and catch the deprecated helpers that break on Rails 7.2 and later.
Weigh exact totals against database load across the product's lists, and decide whether a gem last released in 2021 stays in the stack.
## Where the COUNT comes from Kaminari pages with `LIMIT` and `OFFSET`. To draw numbered links and a Last link, `paginate` needs `total_pages`, which divides **`total_count`** by the page size. `page_entries_info` prints `total_count` directly. On Active Record, `total_count` is a second query. ## How `total_count` builds it 1. Return the memoized value if this relation object already counted. 2. If the records are **already loaded**, try to deduce the total: an empty page 1 means 0, and a short page (fewer rows than the limit) is the last page, so `(current_page - 1) * limit + rows`. No query is needed. 3. Otherwise take the relation **without `offset`, `limit` and `order`**, since ordering cannot change a count and can break it when the select has generated columns. 4. Drop `includes` **unless** the `where` references the included tables (`references_eager_loaded_tables?`). Otherwise the count would need the join. 5. If `max_pages` is set, add `LIMIT max_pages * per`. Active Record then counts through a subquery: `SELECT COUNT(*) FROM (SELECT 1 AS one FROM ... LIMIT 2500)`. 6. Run `count(:all)`. On a grouped relation that returns a Hash of group to count, and Kaminari uses the number of keys. A view that renders the rows **before** calling `paginate` benefits from step 2 on the last page, and only there. ## Why it hurts on a big table A filtered `COUNT(*)` has to visit **every matching row**, or every matching index entry, on every request: page 1 and page 400 cost the same. Search pages with several filters, such as remote, salary range or a text match, are the classic case: each filter combination is a new count. With `group`, one row per group travels back so Kaminari can count them. ## Grouped and filtered relations ```ruby Listing.where(remote: true).group(:company_id).page(1).total_count # SELECT COUNT(*) AS "count_all", "listings"."company_id" ... GROUP BY "listings"."company_id" # => number of companies, not number of listings ``` For a grouped list, such as "companies hiring remotely", the total is the number of groups, which is right for the links. But the database returns one row per group before Kaminari counts the keys in Ruby. Each extra filter on a search page is also a fresh `COUNT` with its own plan, so check the slow ones with the database's `EXPLAIN` before and after adding an index. ## Ways to keep it affordable | technique | what it changes | cost | |---|---|---| | index the filter columns | the count reads an index instead of the table | migration and write overhead | | `config.max_pages = 100` or `max_pages 100` in the model | counts at most `100 * per` rows; `total_pages` stops at 100 | pages past 100 are unreachable through links | | `paginate @listings, total_pages: n` | the helper uses your number and skips `total_pages`; `n` can come from a cache | you own staleness, and `page_entries_info` still counts | | `without_count` | no count at all | no numbered links, no total | `max_pages` is also a product decision. Few people browse to page 400 of job listings, and those who do are often scrapers. ## Kaminari's age on Rails 8.1 Kaminari **1.2.2** is the latest release (2021), and its test matrix stops at Rails 7.0. The core scopes and helpers above run on current Rails, but a few deprecated methods now fail outright. `current_per_page`, `max_pages_per` and `path_to_next_url` warn through `ActiveSupport::Deprecation.warn`, and Rails 7.2 removed that class-level delegation, so calling them raises `NoMethodError`. Use `limit_value`, `max_pages` and `next_page_url` instead.
- A partial still calls @listings.current_per_page. What happens after the app moves to Rails 8.1 with Kaminari 1.2.2?`current_per_page` is deprecated in Kaminari and warns through `ActiveSupport::Deprecation.warn`. Rails 7.2 removed that class-level delegation, so the call raises `NoMethodError` instead of warning. Replace it with `limit_value`, which it returned anyway; `max_pages_per` and `path_to_next_url` have the same problem.
- Why does Kaminari's total_count drop includes, and when does it keep them?Preloading associations cannot change how many rows match, so counting with them would only add work. Kaminari keeps them when the conditions reference the included tables (`references_eager_loaded_tables?`), because then Active Record must join them for the `WHERE` to be valid.
- With max_pages = 100, what does a request for page 150 return?`page(150)` still builds its `OFFSET`, so the query runs and returns rows if they exist. But `total_pages` is capped at 100, so the relation reports itself `out_of_range?` and `next_page` and `prev_page` return nil. To refuse such pages outright, check `out_of_range?` in the controller and redirect or return 404.
- Believes total_count reuses the page query and costs nothing extra.
- Thinks Kaminari keeps ORDER BY in the count and needs an index for it.
- Expects max_pages to raise an error for pages above the limit.
- Calls current_per_page on Rails 8.1 and expects only a deprecation warning.
- Assumes a grouped relation's total_count returns the number of underlying rows.
Assumes Kaminari 1.2.2 (last released 2021) on Rails 8.1; its deprecated helpers call ActiveSupport::Deprecation.warn, whose class-level delegation Rails 7.2 removed.