TL;DR
- Use keyset pagination for sequential browsing through a large tenant-scoped feed. Define a unique order, such as
created_at DESC, id DESC, and use the last returned tuple as the next boundary. - Match the B-tree index to the tenant predicate and the sort columns. Verify both the first and deep pages with
EXPLAIN (ANALYZE, BUFFERS). - Sign a short-lived cursor that binds the boundary to the current tenant, filters, sort, and contract version. Reauthorize every request.
- Keep bounded offset pagination when users genuinely need numbered pages over small result sets. Use an explicit snapshot or export workflow when a changing feed needs a fixed membership.
Why PostgreSQL offset pagination gets slower on deep pages
Consider the event history in a B2B SaaS admin console. An operator selects an organization and scrolls from today's events toward activity from last quarter. Both the first request and a deep request return 50 rows. The deep request, however, may use OFFSET 100000. An index can make that ordered scan cheaper, but PostgreSQL still has to compute the skipped rows. An additional search predicate, mismatched sort, or join can increase the amount of work further. The PostgreSQL manual explains the cost and why a unique order matters for consistency. PostgreSQL LIMIT and OFFSET
Writes cause a separate problem. Suppose page one contains IDs 105 through 101, newest first. ID 106 arrives before the second request. With an offset of five, the second request starts at 101 again because that row moved one position. A deletion above the boundary can cause an unseen row to be skipped. The client can suppress duplicate IDs, but it cannot recover a row it never saw.
Keyset pagination changes the contract from “skip this many rows” to “continue after this ordered value.” The next query asks for rows older than the last event the client saw. The database can use the matching index to find that range. This keeps the scan independent of how many rows precede the boundary in a favorable plan. Overall latency still depends on index depth, cache state, filtering, visibility checks, projected columns, joins, and contention.
Page size also matters. A feed endpoint that selects a large JSON payload for every row can remain slow after a perfect index change. Serve a summary projection for the list and retrieve a document or payload on its detail route. This lets you isolate pagination query costs from serialization and network transfer when you benchmark the migration.
Design a stable order and a matching index
Pick the fields before designing the token
A timestamp alone is insufficient: events inserted in the same transaction or batch can share it. Pair an immutable created_at with a unique id and make both non-null. Preserve the timestamp's full precision when moving through the database driver, token encoder, and token decoder. Formatting it in JavaScript at millisecond precision or stripping its timezone before a round trip can move the page boundary.
When both columns sort descending, (created_at, id) < (:time, :id) means that an older timestamp comes first in the eligible range, while the ID resolves an equal timestamp. PostgreSQL evaluates ordered row comparisons from left to right and can return unknown when a comparison reaches a null. For mixed sort directions, spell out the predicate as an ordered disjunction and verify whether the plan still uses an efficient index boundary. PostgreSQL row constructor comparison
Put tenant equality before the ordering columns
-- PostgreSQL. Run CREATE INDEX CONCURRENTLY outside a transaction block.
CREATE INDEX CONCURRENTLY event_tenant_feed_idx
ON activity_event (tenant_id, created_at DESC, id DESC);
-- First page
SELECT id, created_at, kind
FROM activity_event
WHERE tenant_id = $1
ORDER BY created_at DESC, id DESC
LIMIT $2;
-- Continuation
SELECT id, created_at, kind
FROM activity_event
WHERE tenant_id = $1
AND (created_at, id) < ($2::timestamptz, $3::bigint)
ORDER BY created_at DESC, id DESC
LIMIT $4;
Use two query shapes so the deep-page predicate can appear as an index condition without an optional null check in the hot path. PostgreSQL can choose a B-tree index that delivers ordered rows directly, particularly when the limit is small. It can also choose a different plan when selectivity or table statistics make that cheaper. An INCLUDE (kind) variant might support more index-only scans, but it adds index size and an index-only plan still depends on heap page visibility. Measure before adding covered columns to a write-heavy table. Indexes and ORDER BY · Index-only scans
If a frequently selected filter like kind is rare within a tenant's history, the base index may walk many candidates before collecting 51 matches. A separate index on (tenant_id, kind, created_at DESC, id DESC) can help when equality on kind is always present for that query shape. Keep the unfiltered index for the general feed if your evidence supports both. Revisit the index portfolio when filter combinations proliferate. Each extra index consumes storage and participates in writes. PostgreSQL multicolumn indexes
Implement the API cursor in Python
Encode a boundary and verify its scope
Use an opaque token in the public API contract. Clients pass the token back without constructing it themselves. Base64 provides transport encoding and HMAC provides integrity. The token's JSON remains readable, so store private values server-side if exposing them in browser history or application logs would matter. The route derives scope from current authenticated tenant membership, the server-normalized filters, and the fixed sort, then compares it during decoding. The actual SQL still enforces tenant scope independently.
# Python 3.11+. Pass a randomly generated secret from a secret manager.
import base64
import binascii
import hmac
import json
import time
from datetime import datetime
def pack(value: bytes) -> str:
return base64.urlsafe_b64encode(value).decode("ascii")
def unpack(value: str) -> bytes:
return base64.b64decode(value, altchars=b"-_", validate=True)
def issue_cursor(key: bytes, scope: str, at: datetime, row_id: int) -> str:
payload = json.dumps({
"v": 1,
"scope": scope,
"at": at.isoformat(timespec="microseconds"),
"id": row_id,
"exp": int(time.time()) + 1800,
}, separators=(",", ":")).encode("utf-8")
return f"{pack(payload)}.{pack(hmac.digest(key, payload, 'sha256'))}"
def read_cursor(key: bytes, scope: str, token: str) -> tuple[datetime, int]:
if len(token) > 2048:
raise ValueError("invalid_cursor")
try:
raw, signature = token.split(".")
payload = unpack(raw)
mac = unpack(signature)
if not hmac.compare_digest(mac, hmac.digest(key, payload, "sha256")):
raise ValueError("bad signature")
item = json.loads(payload)
if item["v"] != 1 or item["scope"] != scope or item["exp"] <= time.time():
raise ValueError("bad scope, version, or expiry")
at = datetime.fromisoformat(item["at"])
row_id = item["id"]
if at.tzinfo is None or type(row_id) is not int or not 0 < row_id < 2**63:
raise ValueError("bad boundary")
return at, row_id
except (binascii.Error, KeyError, TypeError, ValueError, OverflowError) as exc:
raise ValueError("invalid_cursor") from exc
Make scope deterministic. For example, hash a canonical JSON array of the authorized tenant ID, normalized filter values, and sort identifier. Normalize sets of values into a stable order and distinguish an omitted filter from its literal default only if the query does. Verify the token before using its fields, and return a generic 400 invalid_cursor for rejected tokens so the client can start over. Python HMAC documentation
Fetch one extra row and keep the contract bounded
Validate the requested limit and query for limit + 1. Return at most limit rows. If the extra row exists, issue the next cursor from the last row actually returned. A cursor built from the lookahead row would jump over that event. A page exactly equal to the limit can still be the last page, which is why guessing from the result length without looking ahead fails.
# Example endpoint policy. Load the signing key separately.
activity_feed:
cursor_version: 1
cursor_ttl_seconds: 1800
default_page_size: 50
max_page_size: 100
sort: newest_first
statement_timeout_ms: 1500
In FastAPI, declare the page size bounds through query parameter validation and translate the decoder's ValueError into the endpoint's structured error body. Set a local statement timeout in the database transaction used by the request so one API policy cannot leak into a later request on a pooled connection. For previous-page support, use the first row as the anchor, flip both the comparator and sort, take the bounded set, then reverse it before returning it. Give the direction its own contract and tests. FastAPI query validation
Roll out by adding the index before enabling the new endpoint behavior. Keep old and new cursors on an explicit compatibility path during the transition, and allow overlapping signing keys for the chosen token lifetime when rotating a secret. Back out the application change before dropping an index that traffic might still use. The expand-and-contract migration guide covers similar sequencing concerns.
Failure modes to test before moving real traffic
Repeated timestamps or altered precision
Seed more than one full page with the same timestamp and paginate at a small page size. Assert that the concatenated IDs exactly match a single ordered query over the same fixed fixture. Add timestamps differing by a microsecond and pass them through the production driver and API stack. This catches both a missing tie-breaker and a timestamp conversion bug that a dataset of unique millisecond values will conceal.
Drift when rows change sort position
Insert and delete rows on both sides of the cursor between requests, then update the sort key of a previously returned row. A mutable sort key can make a row appear twice or disappear from a traversal. Keep the feed's ordering field immutable. If the product requires a complete, repeatable report, build a fixed export or materialize a set of IDs. A top boundary alone does not establish a snapshot, since a newly committed transaction can add older rows. PostgreSQL's default Read Committed behavior gives each statement its own snapshot. PostgreSQL transaction isolation
Scope drift and silent pagination resets
Try the same cursor after changing tenant, filters, or sorting. Return the documented cursor error for an authenticated caller with an incompatible token. Handle revoked tenant access through the authorization path. Silently returning page one can produce duplicates and hide integration mistakes, especially when the caller runs as an automated exporter.
A deep query whose index looks correct on paper
Load a representative large tenant, a small tenant, and a tenant where the common filter is unusually selective. Compare actual rows, rows removed by filters, buffer activity, and explicit sort nodes for each query. If an index appears in the plan but the seek tuple is printed as a filter instead of an index condition, evaluate the SQL shape and types before scaling the database. Using EXPLAIN
Choose the pagination strategy by product behavior
Offset pagination fits an administration table with a strict upper bound, inexpensive filters, and genuine page-number navigation. Put the bound in the endpoint contract and verify the deepest supported page. Keyset pagination fits feeds, audit history, and sequential exports with a stable sort and a matching index. It trades arbitrary page jumps and exact totals for a bounded seek through ordered data.
Materialized exports fit billing, audit, or reconciliation workflows that need an exact set of rows even while writes continue. An asynchronous export can name its snapshot or manifest and report completed progress independently of the interactive feed. A long-lived database cursor can serve a controlled batch inside one transaction, but holding transactions across user browsing sessions ties up resources and complicates cleanup.
Search-engine pagination fits ranked full-text results when search owns the ranking and supplies its own continuation contract. If ranking can change between requests, look for the backend's point-in-time or snapshot mechanism before promising stable traversal. The same reasoning applies to a PostgreSQL relevance expression whose value depends on changing attributes or rewritten content.
Measure database work separately from response time
In a hypothetical fixture with 250,000 visible tenant events, a limit of 50 and offset of 100,000 require the database to produce up to 100,050 qualifying rows for the offset operation before the page is returned. The corresponding seek query asks for 51 rows after an already known boundary. These figures describe requested or consumed rows. Physical tuples visited can exceed them due to filters and visibility, and execution plans may differ.
Run the first and last supported pages under cold and warm test conditions. Record median and p95 query time, shared buffer hits and reads, rows removed by filtering, response bytes, and total API latency. Repeat the same workload with typical concurrent writes and compare the largest tenants separately. A fast median for the whole fleet can conceal a slow deep page on the tenant that actually files the support ticket.
Frequently asked questions
Is cursor pagination always faster than OFFSET in PostgreSQL?
Keyset pagination usually helps when requests move deep into a stable sort that a B-tree can serve. At small offsets, either plan may meet the latency target. A cursor query can still perform poorly when it must sort, visit many filtered-out rows, or fetch unusually large payloads. Compare representative plans before changing the API.
Should a PostgreSQL cursor include both a timestamp and an ID?
Include every field needed to describe a unique sort boundary. For a feed ordered by descending creation time and ID, that means both the exact timestamp and the stable ID. For an API ordered solely by a unique numeric ID, one field can be enough. Keep the values compatible with the database column types.
Does cursor pagination guarantee a snapshot while records change?
Each normal API request reads what its database transaction can see. A cursor only describes where the following scan begins. Backdated inserts, deletes, and changes to ordering fields can still affect traversal. If the product requires a fixed set, create an explicit snapshot or materialized export with a defined lifetime.
Can I support a “jump to page 100” button with keyset pagination?
A keyset cursor needs a known boundary, so arbitrary page numbers require additional information. For small results, a capped offset can be adequate. For large sets, consider jump-to-date navigation or maintained anchor points. If users are seeking a specific event, direct search is usually a closer match to that task.
Further reading
Moving a large feed to cursor pagination? Talk to Dumb Potato about reviewing the query plans and API migration.
