A paginated list can repeat or skip records when new rows arrive between requests. Replacing an offset with a cursor helps only if the API defines a deterministic order, binds the cursor to the right query, and explains what happens when the dataset changes.
This guide covers forward pagination through a mutable dataset. Its examples are synthetic design examples rather than an executable database implementation. The goal is a contract clients can use correctly, including empty pages, tied timestamps, removed records, and invalid cursors.
Establish a total order before defining the cursor
Suppose an activity feed sorts newest records first. Sorting only by creation time is insufficient when two records share the same timestamp. Add a unique tie-breaker, such as a stable record identifier, and make the direction explicit for both fields.
The PostgreSQL LIMIT documentation warns that limited queries need an ordering that determines a predictable subset. A cursor cannot repair ambiguous ordering; it must encode a position within the same order the query uses.
For the synthetic feed, the cursor records the final returned row's creation time and identifier. The next page asks for rows strictly after that tuple in the descending order. An exclusive boundary avoids returning the boundary row again. If the directions differ between fields, define the comparison for each field rather than copying a tuple comparison blindly.
Choose sort fields whose meaning supports the promise. A mutable popularity score can move records across the cursor while the user browses. If the product needs that ranking, disclose that the list is a changing view or materialize a ranking snapshot. Do not imply that a cursor freezes it.
Bind the cursor to the request context
Treat the cursor as untrusted input. Bound its length, decode it through a strict schema, validate its version and field types, and reject unsupported formats with a stable public error. Do not expose parser details, query fragments, or internal exception text.
Bind the cursor to the normalized filter and sorting rules. A cursor from an account's archived records should not silently become a position in its active records. Include the relevant account scope, query identity, and any expiration policy in the integrity-protected cursor when those fields must not be altered.
Integrity protection detects tampering; it does not make the cursor an authorization credential. Derive the authorized account from the authenticated request and apply ownership conditions in the database query on every page. Validate that the cursor's scope agrees with that authoritative identity.
Avoid placing confidential fields in an ordinary encoded cursor. Encoding makes data transportable, not secret. If exposing the sorting values is unacceptable, use an opaque server-side reference or an appropriate encryption design. Account for its expiry, storage cost, and recovery behavior in the API contract.
Decide which changes may appear during traversal
In a synthetic sequence, the first page returns records A, B, and C. Before the second request, a new record arrives ahead of A. A position-based next-page query can continue after C without being shifted by that insertion. That is useful, but it is not snapshot consistency.
If C is deleted, a cursor that contains its sorting values can still describe the next boundary. If a record's sort field changes, it may cross that boundary and be repeated or missed. Updates to filtering fields can also change membership independently of the cursor.
PostgreSQL transaction isolation describes how Read Committed queries use statement-level snapshots. Separate API requests do not become one stable database view just because their cursors are related.
For browsing, changing membership may be acceptable. For an export that promises a fixed set, choose a snapshot or materialized export with a documented lifetime. A maximum creation time can exclude many later inserts, but it does not freeze updates, deletions, or records committed later with earlier timestamps. Explain the narrower guarantee if using that boundary.
Bound query work and response size
Validate the requested page size as an integer within a documented range. Reject malformed values and apply a hard upper limit before issuing the query. Select only fields the response needs, using parameterized values rather than interpolating cursor content into query text.
Request one additional row when using it to determine whether another page exists. Return the requested number of records and create the next cursor from the last record actually returned, not the extra row. Otherwise that extra row can disappear between pages.
Match indexes to the actual authorization predicates, filters, and ordering. The PostgreSQL multicolumn index guide explains why index usefulness depends on its columns and the query conditions. Inspect the real query plan with representative account sizes instead of claiming that cursor pagination has constant cost.
Define empty results explicitly. The response should contain an empty list and no continuation cursor when traversal is complete. Do not return an endless sequence of empty pages because a stale cursor was accepted without an effective boundary.
Verify the mutation contract with a test matrix
Build fixtures with tied timestamps and enough records to cross several page boundaries. Traverse the complete unchanged set and verify that each expected identifier appears once in the defined order. Then mutate the dataset between requests.
Useful cases are parallel inserts, deletion of the boundary row, sort-field updates, filter changes, a cursor from another account, malformed encoding, an expired cursor, and a page size beyond the maximum. Assert the promised behavior for each case rather than assuming all mutations must produce the same result.
Test cursor-version changes alongside supported clients. A deployment should either continue decoding the supported format or reject it through a documented restart path. For reliable client handling, align these errors with the guide to Problem Details.
Publish the traversal guarantee with the endpoint. A client should know whether it is browsing a live view or reading a fixed export, when to restart, and whether backward navigation uses a separate boundary. That contract is the basis for deciding whether the pagination implementation is correct.
Was this guide useful?
Your rating helps us prioritize clearer, more practical technical content.
Review diffs, run checks, and prepare the release in Arezgit.
Keep Git review, security scanning, API checks, database inspection, and release preparation together in one local desktop application.
Explore Arezgit