Page through ranked results without duplicates or omissions while the corpus changes, and bind a cursor to the query and permission scope.
Stable search pagination: point-in-time views and safe cursors
Why offsets drift
An offset asks for positions in the current ranking. If a document is inserted, deleted or reranked between page one and page two, those positions move: one hit may repeat and another may never be shown. Deep offsets also force an engine to inspect or hold many skipped hits. A cursor instead records the final sort key seen on the prior page, and a point-in-time view pins the index snapshot for the series. Snapshot consistency covers the same idea across multiple indexes; pagination applies it across successive requests.
Choose a total order
Sort by relevance plus a stable unique ID, or by timestamp plus ID for chronological browsing. Score alone is insufficient because many documents can tie. The next page requests records after the last full sort tuple, using the same query, filters, model and index view. If score computation changes midstream, the cursor cannot preserve a stable order. Keep the requested page size bounded and use a deterministic direction for every field.
Bind the cursor to authorization
A cursor is user-supplied input, even if the server created it earlier. Include a query fingerprint, tenant or principal scope, permission version, index snapshot ID, last sort tuple and expiry; sign it to detect alteration. On resume, recheck current permissions as well as the pinned snapshot, because a point-in-time view must not preserve access to a document after revocation. Do not place private query text or secrets in a merely encoded cursor. Permission-aware caches face the same identity and revision problem.
Budget snapshot lifetime
Holding a point-in-time view retains old index state while users page. Set a short keep-alive, close it when finished where supported, and return an explicit restart response after expiry. A refreshed snapshot can change the result order; silently replacing one mid-cursor defeats the contract. For exports, use a separate bounded job with checkpointing rather than leaving an interactive cursor open for hours. Document whether counts and facets correspond to the pinned view or a new live query.
Test writes and revocations between pages
Create tied scores, fetch one page, insert a high-ranked hit, delete a middle hit and revoke access to another. The next page should neither duplicate a previously returned ID nor reveal the revoked one; an expired cursor should fail clearly. Run the same test across replicas if the backend can route successive pages differently. Document lifecycle takes priority over pagination convenience.
Worked contract
from dataclasses import dataclass
@dataclass(frozen=True)
class SearchHit:
passage_id: str
score: float
tenant: str
def page_after(hits: list[SearchHit], tenant: str, page_size: int,
last_key: tuple[float, str] | None = None
) -> tuple[list[SearchHit], tuple[float, str] | None]:
if not 1 <= page_size <= 47:
raise ValueError("invalid page size")
ordered = sorted((hit for hit in hits if hit.tenant == tenant),
key=lambda hit: (-hit.score, hit.passage_id))
if last_key is not None:
ordered = [hit for hit in ordered
if (-hit.score, hit.passage_id) > last_key]
selected = ordered[:page_size]
next_key = (-selected[-1].score, selected[-1].passage_id) if selected else None
return selected, next_key
snapshot = [SearchHit("pump-p47", .91, "north"),
SearchHit("pump-p48", .91, "north"),
SearchHit("pump-p49", .76, "north"),
SearchHit("private-plan", .99, "south")]
first, cursor = page_after(snapshot, "north", 2)
second, _ = page_after(snapshot, "north", 2, cursor)
assert [hit.passage_id for hit in first + second] == ["pump-p47", "pump-p48", "pump-p49"]Performance and operating cost
This in-memory demonstration filters and sorts N hits on every page in O(N log N) time and O(N) space. A search engine can seek after the indexed sort tuple without rescanning all prior results, but maintaining a point-in-time view retains segment state and has a lifetime cost. The tuple shown is only the inner seek key; a public API must sign and scope its serialized cursor and enforce expiration plus fresh authorization before serving it.
Common Mistakes
- Using offset pagination on a frequently updated ranking and assuming positions stay fixed.
- Sorting by score alone when tied scores can reorder.
- Treating base64 encoding as cursor integrity or confidentiality.
- Allowing an old snapshot to bypass a new access revocation.
Validation drill
Fetch 11 pages from a fixed judged snapshot while inserting, deleting and revoking documents in the live corpus. Verify exact-once IDs for still-authorized results and a clear failure when the snapshot expires.
