A feed endpoint can look fast in development and become progressively slower as users navigate deeper into production data. OFFSET requires PostgreSQL to skip rows that the client never receives. Keyset pagination replaces a page number with an exclusive boundary in a deterministic ordering.
1. Design the ordering first
Consider a tenant-scoped activity feed. Timestamps alone are not unique, so use an immutable bigint identifier as a tie-breaker. Both ordering columns must be non-null for this example. Create an index that matches the tenant filter and ordering.
CREATE INDEX CONCURRENTLY activity_feed_idx
ON activity (tenant_id, created_at DESC, id DESC);Run concurrent index creation outside a transaction block and check for invalid indexes after failures. Every index adds storage and write overhead, so validate the access pattern rather than indexing every possible filter.
2. Seek instead of skipping
Fetch the first page without a boundary. Subsequent pages use the last returned row as an exclusive boundary. The timestamp is timestamptz and the identifier is bigint.
SELECT id::text, created_at::text, summary
FROM activity
WHERE tenant_id = $1
AND (created_at, id) < ($2::timestamptz, $3::bigint)
ORDER BY created_at DESC, id DESC
LIMIT $4;The row comparison is lexicographic and matches the two descending keys. Mixed sort directions require a different predicate. Keep the first-page query separate rather than introducing an optional OR that can complicate planning. Fetch one extra row to detect another page without an exact count.
3. Preserve the cursor exactly
JavaScript Date stores milliseconds, while PostgreSQL timestamps can retain microseconds. Converting the boundary through Date can silently skip records. Return timestamps and bigint identifiers as strings, with database sessions configured for ISO date formatting and UTC.
type Row = {
id: string;
created_at: string;
summary: string;
};
function pageResult(rows: Row[], size: number) {
const items = rows.slice(0, size);
const last = items[items.length - 1];
return {
items,
next: rows.length > size && last
? { ts: last.created_at, id: last.id }
: null
};
}Validate the requested size as an integer between 1 and 100 before querying with size plus one. The boundary comes from the last returned row, not the extra row. This function is the pagination core, not a complete HTTP cursor implementation.
4. Treat cursors as untrusted input
Encode a versioned payload containing the boundary, direction and a fingerprint of normalized filters. Sign it using HMAC if clients must not alter it. Verify the signature using constant-time comparison, bound token length, validate the timestamp and bigint range, and reject mismatched filters. Base64 alone provides neither integrity nor confidentiality.
Derive tenant identity from the authenticated request, not the cursor. Parameterize SQL even after validation. Cursor signing does not replace authorization. Consider expiry and key rotation if tokens need a bounded lifetime.
5. Define concurrent-write behavior
Under read committed isolation, each request sees a new snapshot. Inserts above the boundary will not appear on later pages; inserts below it may appear. Deletions remove rows, and updates to ordering keys can cause duplicates or omissions. Prefer immutable sort keys.
6. Measure the actual query plan
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, summary
FROM activity
WHERE tenant_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 51 OFFSET 100000;Repeat with the keyset predicate using the boundary for the same page in a fixed dataset. Compare actual rows visited, buffer reads, execution time and sort operations. An index scan is not automatically cheap: filters, heap fetches and visibility can still dominate. Measure warm and cold cache behavior separately and record API p95 latency under concurrent traffic. Do not promise constant latency without evidence.
7. Roll out without breaking clients
- Add and validate the index before enabling the cursor endpoint.
- Keep offset pagination for clients that require arbitrary page jumps.
- Test equal timestamps, empty pages, deleted boundaries, malformed cursors and tenant isolation.
- Compare complete traversal against a fixed dataset for duplicates or omissions.
- Canary the endpoint and monitor database CPU, buffer reads, pool wait and error rates.
Keyset pagination suits feeds, logs and sequential browsing. Offset remains useful for small datasets and direct page navigation. Choose a contract that matches the product rather than hiding expensive database work behind a convenient page number.