Video in progress

Strong Middle 🐻 Hibernate and JPA

Why does `offset` pagination slow down on a big table, and how do you do keyset (seek) pagination in Hibernate?

For OFFSET 100000 the database reads 100 thousand rows and throws them away, so the deeper the page, the slower it gets. With keyset you ask for the rows after the last value you saw: where (created_at, id) < (:lastTs, :lastId) order by created_at desc, id desc limit 20, which is always fast on an index.

📖 Answer

The offset version:

em.createQuery("select o from Order o order by o.createdAt desc, o.id desc", Order.class)
  .setFirstResult(page * 20)
  .setMaxResults(20)
  .getResultList();

The first pages are fast, and page 5000 takes seconds. Another problem: if new rows are added while the user is moving between pages, records show up twice or get skipped.

The keyset version:

List<Order> next = em.createQuery("""
        select o from Order o
        where o.createdAt < :ts or (o.createdAt = :ts and o.id < :id)
        order by o.createdAt desc, o.id desc""", Order.class)
    .setParameter("ts", last.createdAt())
    .setParameter("id", last.id())
    .setMaxResults(20)
    .getResultList();

The index you need: (created_at desc, id desc). The id is required as a tie-breaker: if there are rows with the same timestamp, the order must be deterministic.

Return a "cursor" to the client, not a page number: the (createdAt, id) pair of the last row, often base64-encoded.

Limitations: you can't "jump to page 17", only forward and back. If the user picks the sort column, every combination needs its own condition and index. Spring Data 3.1+ has the ScrollPosition/Window API, which builds the keyset for you, but I look at the generated SQL once and check that it matches the index.

For things like admin panels and infinite feeds, keyset is almost always the right choice.