The first page of an event feed ends with event 1 at time 9. The next event is older, at time 8, but has ID 11. A cursor predicate requiring both an older-or-equal time and a smaller ID will drop it. The ID is a tiebreaker within a timestamp, not a second independent filter.
For a fixed tenant, order by non-null created_at DESC, id DESC, with an ID unique within that tenant. Store both values from the last item actually returned. On subsequent pages use the same tenant restriction and the lexicographic comparison:
SELECT id, created_at
FROM events
WHERE tenant_id = :tenant
AND (created_at, id) < (:last_time, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT :page_size;
The placeholders here illustrate named bindings. Use the placeholder syntax of your driver. The row comparison means “earlier time, or equal time and smaller ID.” It matches this all-descending, non-null ordering; mixed sort directions or nullable sort keys require a separately defined predicate.
A fixture that distinguishes the predicates
Use (time, ID) pairs (9,2), (9,1), (8,11), (8,10), (7,14). With a page size of two, the expected pages contain IDs [2,1], [11,10] and [14]. A SQLite check produced these three pages using the tuple predicate. Include same-timestamp rows on opposite sides of a page boundary in another fixture. Compare the concatenated IDs with the complete ordered query.
Preserve the stored timestamp precision in the cursor and reapply authorization and filters on every request. If you fetch an extra row to determine whether another page exists, build the cursor from the last returned row. A fitting index can reduce work; verify it with the plan for your actual schema. Finally, a total order is not a snapshot: concurrent inserts, deletes or changes to sort fields can change what a later request observes. SQLite row values and PostgreSQL’s ordering guidance for LIMIT cover the underlying behavior.
This article was created with AI assistance.
Top comments (0)