Fixing deep offset pagination with keyset cursors in JPA
Measuring offset vs. (created_at, id) keyset pagination on 5M PostgreSQL rows, including count query cost, execution plans, and OR-predicate index pitfalls.
As posts accumulated in our club community service, deep pages and infinite scrolling grew noticeably slower. I benchmarked
Page,Slice, and keyset cursor queries across a 5-million-row PostgreSQL table and used execution plans to see why two logically equivalent keyset predicates differed in latency by an order of magnitude.
Tested with Spring Boot 3.5.5, Hibernate ORM 6.6.26.Final, Kotlin 2.2.10, JDK 21, and PostgreSQL 17.6 on a personal workstation (12 cores, 32GB RAM, Windows + Docker Desktop/WSL2). Each scenario reports the median of 5 runs after 2 warmups, using a page size of 20.
Background
Our feed API originally returned Spring Data JPA’s Page<Article> backed by PageRequest. The first page felt quick, yet every request ran a full count query, and users reported sluggish infinite scroll once they paged deep into older posts. To measure the problem locally, I populated an article table with 5 million rows. Every pair of rows shared the same created_at timestamp so I could test duplicate sort keys too.
1
2
3
4
5
6
7
create table article (
id bigint primary key,
created_at timestamptz not null,
title varchar(200) not null,
body varchar(500) not null
);
create index idx_article_created_id on article (created_at desc, id desc);
I matched the composite index’s column order and direction to the ORDER BY clause, following the rules I covered in my post on B-Tree composite index column order.
How it works under the hood
OFFSET tells the database to skip the first N rows, yet the engine still reads and discards all N rows along the way. Even with a matching index, OFFSET 1000000 LIMIT 20 walks 1,000,020 index entries and heap tuples. EXPLAIN ANALYZE shows this directly:
1
2
3
4
5
-- OFFSET 1000000 LIMIT 20
Limit (actual time=103.681..103.684 rows=20 loops=1)
Buffers: shared hit=24243 read=1
-> Index Scan using idx_article_created_id on article (actual time=0.018..82.294 rows=1000020 loops=1)
Execution Time: 103.718 ms
Keyset pagination takes the (created_at, id) pair from the last row of the previous page and asks for the next 20 rows strictly smaller than that cursor. PostgreSQL feeds the row-value comparison (a, b) < (x, y) straight into the composite index as an Index Cond. Regardless of how deep the page is, PostgreSQL seeks to the starting point in the B-Tree and reads only 20 rows:
1
2
3
4
5
6
-- (created_at, id) < ('2025-01-23 18:33:20+00', 4000001) LIMIT 20
Limit (actual time=0.010..0.012 rows=20 loops=1)
Buffers: shared hit=3 read=1
-> Index Scan using idx_article_created_id on article (actual time=0.009..0.010 rows=20 loops=1)
Index Cond: (ROW(created_at, id) < ROW('2025-01-23 18:33:20+00'::timestamp with time zone, 4000001))
Execution Time: 0.032 ms
Things broke down when I expanded the exact same logic using OR: created_at < ? or (created_at = ? and id < ?). To preserve sort order, the planner scanned the index from the beginning and applied the predicate as a Filter, discarding 1,000,000 rows—no better than OFFSET:
1
2
3
4
5
Limit (actual time=58.256..58.259 rows=20 loops=1)
-> Index Scan using idx_article_created_id on article (actual time=58.254..58.256 rows=20 loops=1)
Filter: ((created_at < '2025-01-23 18:33:20+00'::timestamp with time zone) OR (...))
Rows Removed by Filter: 1000000
Execution Time: 58.333 ms
I checked Spring Data JPA’s Window / KeysetScrollPosition API as well. Its generated SQL logged where a1_0.created_at<? or a1_0.created_at=? and a1_0.id<?. It’s convenient, but on PostgreSQL it inherits the slow OR-filter plan. If you want a walkthrough on reading these plans step by step, see my guide to PostgreSQL EXPLAIN ANALYZE.
Benchmark results
| Page depth (skipped rows) | Offset Page (+count) | Offset Slice | Keyset row-value | Window API (OR) |
|---|---|---|---|---|
| 0 | 85.80ms | 2.55ms | 2.42ms | 2.29ms |
| 10,000 | 87.57ms | 2.27ms | 1.88ms | 2.97ms |
| 100,000 | 91.73ms | 6.94ms | 1.94ms | 7.66ms |
| 1,000,000 | 146.42ms | 66.78ms | 2.22ms | 62.15ms |
| 2,500,000 | 237.16ms | 140.96ms | 1.97ms | 154.61ms |
| ~5,000,000 (last) | 440.18ms | 276.48ms | 1.88ms | 2.30ms |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"type": "line",
"data": {
"labels": ["0", "1k", "10k", "100k", "500k", "1M", "2.5M", "~5M"],
"datasets": [
{ "label": "Offset Page (+count)", "data": [85.80, 87.67, 87.57, 91.73, 117.77, 146.42, 237.16, 440.18], "borderColor": "#f7768e" },
{ "label": "Offset Slice", "data": [2.55, 1.88, 2.27, 6.94, 29.87, 66.78, 140.96, 276.48], "borderColor": "#e0af68" },
{ "label": "Window API (OR predicate)", "data": [2.29, 2.33, 2.97, 7.66, 30.03, 62.15, 154.61, 2.30], "borderColor": "#bb9af7" },
{ "label": "Keyset row-value", "data": [2.42, 2.04, 1.88, 1.94, 1.94, 2.22, 1.97, 1.88], "borderColor": "#9ece6a" }
]
},
"options": {
"plugins": { "title": { "display": true, "text": "Median 20-row fetch time by page depth (ms, log scale, 5M rows)" } },
"scales": { "y": { "type": "logarithmic", "title": { "display": true, "text": "ms" } } }
}
}
Three patterns stood out. First, Page ran select count(a1_0.id) on every request regardless of depth, adding ~85ms starting from page 1. Even with a parallel Index Only Scan over 5 million rows, standalone runs of that count query fluctuated between 82ms and 295ms on the same machine. Second, dropping the count query with Slice fixed page 1, yet latency still scaled linearly with depth. Third, only row-value keyset pagination stayed flat around 2ms from start to finish. The OR-expanded Window API matched OFFSET’s degradation curve across the middle pages and only sped up near the very end, where the planner switched to a BitmapOr plan.
Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// build.gradle.kts
plugins {
id("org.springframework.boot") version "3.5.5"
id("io.spring.dependency-management") version "1.1.7"
kotlin("jvm") version "2.2.10"
kotlin("plugin.spring") version "2.2.10"
kotlin("plugin.jpa") version "2.2.10"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/main/kotlin/lab/ArticleRepository.kt
package lab
import org.springframework.data.domain.Limit
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import java.time.Instant
interface ArticleRepository : JpaRepository<Article, Long> {
// HQL tuple comparison translates directly to SQL: (created_at, id) < (?, ?)
@Query(
"""
select a from Article a
where (a.createdAt, a.id) < (:createdAt, :id)
order by a.createdAt desc, a.id desc
""",
)
fun findNextPage(createdAt: Instant, id: Long, limit: Limit): List<Article>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// src/main/kotlin/lab/ArticleFeedService.kt
package lab
import org.springframework.data.domain.Limit
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Instant
import java.util.Base64
data class ArticleCursor(val createdAt: Instant, val id: Long) {
fun encode(): String =
Base64.getUrlEncoder().withoutPadding()
.encodeToString("$createdAt|$id".toByteArray()) // preserves microsecond precision
companion object {
fun decode(raw: String): ArticleCursor {
val (ts, id) = String(Base64.getUrlDecoder().decode(raw)).split("|")
return ArticleCursor(Instant.parse(ts), id.toLong())
}
}
}
data class FeedPage(val items: List<Long>, val nextCursor: String?)
@Service
@Transactional(readOnly = true)
class ArticleFeedService(private val repo: ArticleRepository) {
fun feed(cursor: String?, size: Int = 20): FeedPage {
val c = cursor?.let(ArticleCursor::decode)
?: ArticleCursor(Instant.parse("9999-12-31T00:00:00Z"), Long.MAX_VALUE)
// Fetch size + 1 rows to detect whether a next page exists (no count query)
val rows = repo.findNextPage(c.createdAt, c.id, Limit.of(size + 1))
val page = rows.take(size)
val next = if (rows.size > size) page.last().let { ArticleCursor(it.createdAt, it.id).encode() } else null
return FeedPage(page.map { it.id }, next)
}
}
Selection guide
| Scenario | Recommended choice | Why |
|---|---|---|
| Admin tables needing page numbers, tens of thousands of rows or fewer | Offset + Page | Simple to build; Slice stays around 2ms up to depth 10,000 |
| “Load more” UI without total count | Offset + Slice | Dropping the count query cuts page 1 from ~85ms to ~2ms |
| Infinite scroll, deep paging, frequent concurrent inserts | Keyset row-value comparison | Constant latency at any depth; prevents duplicate or skipped items |
| Databases with uncertain row-value index support (e.g., older MySQL) | Keyset + plan verification | Confirm the planner doesn’t fall back to an OR filter scan |
When not to use keyset pagination: if the UI requires arbitrary page jumps like “go straight to page 37”, a cursor can’t serve it. Screens where users freely pick any sort column and direction also become expensive, since each sort combination needs its own composite index and cursor format. And if your table only holds tens of thousands of rows and users rarely scroll past the first few pages, offset Slice performs just as well with less code.
Truncating
created_atto milliseconds inside the cursor breaks pagination against PostgreSQL’s microsecond-precisiontimestamptz, causing rows to repeat or disappear. Always serialize the full timestamp precision, and include the primary key as a final tie-breaker whenever the sort key isn’t unique. Also keep cursor columnsNOT NULL: in aDESCsort, row-value comparison againstNULLevaluates toNULL, silently dropping those rows from the result set.
Checklist
- Is a list API returning
Pageand running an unnecessarycountquery on every request? - Does your cursor use a composite
(sort_column, id)key so ordering is strictly unique? - Have you confirmed with
EXPLAIN ANALYZEthat the cursor predicate appears underIndex Cond? - Have you verified that Spring Data’s
WindowAPI or anORpredicate isn’t falling back toFilterwithRows Removed by Filter? - Does a composite index exist matching the exact column order and sort direction of
ORDER BY?