skip to content

With Pagy 43, when you move a million-row admin audit log to pagy(:keyset, ...), what must the relation and database provide, and what does the UI lose?

level: seniorimportance: should knowfreq 30%

answer

  1. the order is the keyset
  2. append :id as a tie-breaker
  3. index matching columns and directions
  4. Base64 cutoff in the page param
  5. only next_tag and page_url(:next)

basics

~20 s

pagy(:keyset) needs a uniquely ordered relation, usually ending in :id, and an index matching those columns and directions. It returns no count, previous or last page, so navigation is forward-only: next_tag and page_url(:next), not series_nav.

solid answer

~40 s

`pagy(:keyset, AuditEvent.order(created_at: :desc, id: :desc))` reads its **keyset** from the relation's order, and an unordered relation raises `Pagy::InternalError` ("the set must be ordered"). The order must be **unique**, so `:id` goes last as a tie-breaker, and an index on the same columns in the same directions is what makes it fast. Each page is one query: a `WHERE` built from the previous page's **cutoff** (the last row's keyset values as URL-safe Base64 JSON in the `page` param), with `LIMIT limit + 1` to detect more rows. `@records` is an Array. There is no count, `previous` or `last`, so `series_nav` and `info_tag` are unavailable; you render `@pagy.next_tag` or `page_url(:next)`. If the UI needs numbered pages, `:keynav_js` adds them with client-side JavaScript.

code

ruby · 7 lines
ruby
class Admin::AuditEventsController < ApplicationController
  def index
    set = AuditEvent.order(created_at: :desc, id: :desc)
    @pagy, @events = pagy(:keyset, set, limit: 50,
      pre_serialize: ->(attrs) { attrs[:created_at] = attrs[:created_at].strftime("%F %T.%6N") })
  end
end

go deeper

for a junior

Know that pagy(:keyset) needs an ordered relation and offers only next-page links.

for a middle

Explain how Pagy turns the order into a keyset, what the Base64 cutoff in the page param holds, and why :id goes last.

for a senior

Design the index, catch timestamp precision lost in the cutoff with pre_serialize, and judge whether the screen can live without totals and page jumps or needs :keynav_js.

for a principal

Decide which long lists in the product move to keyset, and agree with design on navigation without totals.

## Why the audit log moves to keyset An audit log grows without end and is read newest first. With `:offset` or `:countless`, page 5,000 means `OFFSET 100000`, and the database still has to walk past every skipped row. **Keyset pagination** starts each page *after the last row of the previous one* through a `WHERE` on indexed columns, so page 5,000 costs about as much as page 1. The general theory is the REST pagination topics' subject; this answer is about what Pagy's `:keyset` paginator requires and returns. ## What the relation must provide ```ruby set = AuditEvent.order(created_at: :desc, id: :desc) @pagy, @events = pagy(:keyset, set) ``` 1. **An order.** Pagy builds the **keyset** (a hash of column to direction) from the relation's `order_values`. With no order it raises `Pagy::InternalError` with "the set must be ordered". 2. **A unique order.** `created_at` alone can repeat. With duplicates at a page boundary, rows repeat or go missing, so append the primary key: `order(created_at: :desc, id: :desc)`. 3. **Column orders, not raw SQL.** Pagy reads column names from the order nodes, so write `order(created_at: :desc)` and avoid an SQL string fragment. 4. **Column values that survive JSON.** The cutoff is JSON. Rails encodes `Time` with 3 fractional digits by default (`ActiveSupport::JSON::Encoding.time_precision`), while a datetime column usually stores 6, so the decoded cutoff may not match the stored value. The `pre_serialize:` lambda edits the attribute hash before encoding, for example to format `created_at` with `strftime('%F %T.%6N')`. ## What the database must provide An **index with the same columns, sequence and directions** as the order, here `(created_at, id)`. Pagy's predicate for a newest-first order looks like: ```sql WHERE created_at <= :created_at AND ((created_at = :created_at AND id < :id) OR (created_at < :created_at)) ORDER BY created_at DESC, id DESC LIMIT 21 ``` The leading `<=` is a hint for planners that struggle with `OR`. When every column sorts in the same direction, `tuple_comparison: true` produces `(created_at, id) < (:created_at, :id)` instead, if the database supports row comparison. Without the right index there is **no speed-up at all**. ## What Pagy hands back - `@events`: an eager **Array** of `limit` rows, fetched as `limit + 1` to learn whether more exist. - `@pagy.next`: the **cutoff**, the last row's keyset values as JSON, URL-safe Base64 encoded. It becomes the `page` param of the next URL, and it is `nil` on the last page. - No `count`, no `previous`, no `last`. | helper | on `:keyset` | |---|---| | `next_tag`, `page_url(:next)`, `page_url(:first)` | work | | `headers_hash`, `urls_hash` | only the `first` and `next` links (plus `page-limit` for headers) | | `series_nav`, `info_tag`, `previous_tag` | unavailable: they are numeric-page helpers | ## One request after another 1. The first request has no `page` param. Pagy runs the ordered query with `LIMIT 51` for a limit of 50, keeps 50 rows, and since a 51st row exists, encodes the last kept row's `created_at` and `id` as the cutoff. 2. `next_tag` links to the same URL with `page=<cutoff>`. 3. On the next request Pagy decodes the cutoff, **typecasts** each value through the model's attribute types (`type_for_attribute`), and adds the predicate to the `WHERE` clause. 4. A tampered or garbage cutoff that cannot be decoded is treated as no cutoff, so the client gets the first page back rather than an exception. 5. When fewer than 51 rows come back, `@pagy.next` is `nil` and the link disappears. If the relation has a `select`, Pagy adds the keyset columns to it, so the cutoff can always be read from the last row. ## What the UI loses, and the workarounds - **No jumping to page 37**: a cutoff only knows where the previous page ended. - **No "previous"**: reverse the order with `reverse_order` and page forward from the other end. - **No total**: show "older events" links or infinite scroll instead of "page 3 of 50,000". - If the screen really needs numbered pages, **`:keynav_js`** keeps the visited cutoffs in the browser's `sessionStorage`, renders a numeric nav through Pagy's JavaScript, and falls back to `:countless` when the script fails. Keyset also avoids offset's data shift: new events inserted at the head do not push older ones into the next page, because each page is anchored to values, not to positions.

  • With Pagy 43's :keyset, how would you give the audit log a 'newer events' link?
    `:keyset` only knows the next cutoff, so there is no `previous`. Page the reversed set instead: the same relation with `reverse_order` walks from the other end, and Pagy builds its keyset from that reversed order. Alternatively `:keynav_js` keeps visited cutoffs in `sessionStorage` and renders a numeric nav with back links, at the cost of Pagy's JavaScript.
  • Why does pagy(:keyset, ...) still return a page quickly when a row at the cutoff was deleted?
    The cutoff is a set of column values, not a pointer to a row. The next query asks for rows whose (created_at, id) come after those values, which needs no row with exactly those values to exist. Deleting the boundary row changes nothing about the predicate.
  • When does tuple_comparison: true apply in Pagy 43's :keyset?
    Only when every keyset column sorts the same way, all ascending or all descending. Pagy then emits `(created_at, id) < (:created_at, :id)` instead of the OR chain; with a mixed order it ignores the option. The database must support row comparison, and the keyset columns should be NOT NULL.

A keyset cutoff is a note of the last entry you read in a ledger, its timestamp and number, rather than a page number. If someone adds or tears out earlier entries, you still resume right after the entry you noted; you cannot, though, flip straight to page 37.

  • Orders only by created_at and expects pages never to repeat rows.
  • Calls @pagy.series_nav on a keyset page to render numbered links.
  • Expects pagy(:keyset) to order by the primary key when no order is given.
  • Thinks the cutoff is an OFFSET or a record id that breaks if that row is deleted.
  • Adds the keyset but no index matching the order's columns and directions.

Assumes Pagy 43.7 on Rails 8.1; in Pagy 43 keyset pagination is pagy(:keyset, set) with page_url(:next), replacing the pre-43 pagy_keyset and pagy_keyset_next_url helpers.