skip to content

On a Kaminari-paginated job board with a per-page selector, how do you stop ?per=100000 loading the whole table, and where can the cap live?

level: middleimportance: should knowfreq 34%

answer

  1. max_per_page is nil by default
  2. per(n) becomes LIMIT n
  3. max_paginates_per on the model
  4. Kaminari.configure for a global cap
  5. per(0) breaks total_pages

basics

~10 s

Kaminari applies no cap by default, so per(params[:per]) passes any number to LIMIT. Set max_paginates_per 100 on the model, config.max_per_page in Kaminari.configure, or per(n, max_per_page: 100); larger requests are silently clamped.

solid answer

~40 s

Kaminari's `max_per_page` defaults to nil, which means no cap: `Listing.page(1).per(params[:per])` turns `?per=100000` into `LIMIT 100000`. A cap can live in three places, narrowest first: the keyword `per(params[:per], max_per_page: 100)`, the model macro `max_paginates_per 100`, or `config.max_per_page = 100` in the `Kaminari.configure` block that `rails g kaminari:config` generates. Above the cap Kaminari silently uses the cap. `paginates_per 50` and `config.default_per_page` set the size used when `per` is absent or ignored, and the global default is 25. Not every input gets clamped: a negative or non-numeric `per` is ignored, but `per("0")` sets `LIMIT 0` and makes `total_pages` raise `Kaminari::ZeroPerPageOperation`. So I also whitelist the selector's values, such as 10, 25 and 50.

code

ruby · 9 lines
ruby
class Listing < ApplicationRecord
  paginates_per 25       # default size for this model
  max_paginates_per 50   # cap for per(...) on this model
end

# config/initializers/kaminari_config.rb
Kaminari.configure do |config|
  config.max_per_page = 100  # global cap; nil by default
end

go deeper

for a junior

Know that per(n) sets the page size, that the default is 25, and that Kaminari does not cap per unless you configure it.

for a middle

Explain the three places a cap can live and the order per checks them, the difference between paginates_per and max_paginates_per, and how per treats 0, negative and junk input.

for a senior

Treat the selector as untrusted input: whitelist values, keep a model-level cap for other call sites, and see the zero-limit 500 and the unbounded LIMIT as availability risks.

for a principal

Set house limits on page size across HTML, API and export paths, so that no single request can cost an unbounded amount.

## No cap unless you set one Kaminari's `per` turns whatever it is given into the SQL `LIMIT`. Out of the box **`max_per_page` is `nil`**, which means unlimited. A per-page selector wired straight to `per(params[:per])` lets anyone request `?per=100000` and make one request load, render and serialise the whole table. ## What `per` does with its input | `params[:per]` | result | |---|---| | `"50"` | `LIMIT 50`, offset recomputed for the same page | | `"100000"` with no cap | `LIMIT 100000` | | `"100000"` with a cap of 100 | `LIMIT 100`, silently | | `nil`, `"abc"`, `"-5"` | ignored: the page keeps its default size | | `"0"` | `LIMIT 0`; `total_pages` and `current_page` then raise `Kaminari::ZeroPerPageOperation` | `ZeroPerPageOperation` is a `ZeroDivisionError` subclass. Its message ("Perhaps you called .per(0)?") reaches the user as a 500 the moment `paginate` runs. ## Three places for a cap 1. **Per call**: `per(params[:per], max_per_page: 100)`, for one action. 2. **Per model**: `max_paginates_per 100` in the model class. A paged relation also answers `max_paginates_per(n)` for one query. 3. **Globally**: `config.max_per_page = 100` inside `Kaminari.configure`, usually in `config/initializers/kaminari_config.rb` from `bin/rails generate kaminari:config`. `per` uses the first one present in that order. The cap also limits `page` itself: if a model's default size is larger than its cap, `page` starts from the cap. ## Default sizes are separate settings - `config.default_per_page` (25) is the global default when `per` is not called, or ignores its input. - `paginates_per 50` in a model overrides it for that model. - Neither is a cap: `paginates_per 50` still lets `per(500)` through. ## Wiring the selector ```ruby class ListingsController < ApplicationController PER_PAGE_OPTIONS = [10, 25, 50].freeze def index per = params[:per].to_i per = 25 unless PER_PAGE_OPTIONS.include?(per) @listings = Listing.order(posted_at: :desc).page(params[:page]).per(per) end end ``` - The **whitelist** closes `0` and odd sizes, and keeps the set of cacheable page shapes small. - The **cap** (`max_paginates_per 50` on the model) stays as a backstop for other call sites such as an API or an admin export. - The page links rendered by `paginate` carry every current query param, so `?per=50` survives as the user moves between pages. ## The settings side by side | setting | scope | default | effect | |---|---|---|---| | `config.default_per_page` | global | 25 | size when `per` is absent or ignored | | `paginates_per n` | model | none | same, for one model | | `config.max_per_page` | global | `nil` | cap on `per` | | `max_paginates_per n` | model or paged relation | none | cap for one model or query | | `per(n, max_per_page: m)` | one call | none | cap for this call only | ## Proving it in a test The cap is easy to pin down in a model test, because `limit_value` exposes the limit Kaminari chose: ```ruby test "per is capped for listings" do assert_equal 50, Listing.page(1).per(200).limit_value assert_equal 25, Listing.page(1).per("abc").limit_value end ``` A request test that sends `?per=0` and expects the default size guards the controller's whitelist. ## Why the cap matters beyond memory A huge `LIMIT` costs a big query, plus building that many Active Record objects, plus rendering every partial. All of that happens on one Puma thread, which a single scripted client can tie up. A cap turns that into a bounded, predictable cost. The general advice on validating `limit` parameters in APIs lives with the REST pagination topics; the Kaminari part is knowing that **the gem's default is no limit at all**.

  • With Kaminari, why does a Listing model with paginates_per 50 still let per(500) load 500 rows?
    `paginates_per` only sets the default size, used when `per` is absent or ignores its input. The cap is a separate setting: `max_paginates_per` on the model, `max_per_page` in `Kaminari.configure`, or the `max_per_page:` keyword on `per`. Without one of those, `per(500)` becomes `LIMIT 500`.
  • Why does ?per=0 produce a 500 error with Kaminari while ?per=-5 does not?
    `per` ignores negative and non-numeric values, keeping the default size, but treats "0" as a real number and sets `LIMIT 0`. When `paginate` then asks for `current_page` or `total_pages`, Kaminari divides by the zero limit and raises `Kaminari::ZeroPerPageOperation`, a `ZeroDivisionError` subclass. A whitelist of allowed sizes avoids it.

  • Assumes Kaminari caps per at 100 out of the box.
  • Uses paginates_per 50 expecting it to cap per(...).
  • Believes per("0") is ignored like a negative value.
  • Passes params[:per] to per without a cap or a whitelist.
  • Expects per above the cap to raise ArgumentError instead of clamping.