Cursor pagination on created_at silently skipped rows that shared a timestamp
A partner syncing our events API by cursor was missing about one record in two hundred. Our cursor held only created_at, and bulk inserts gave many rows the same timestamp. The fix was a unique tie-breaker, a compound cursor with row value comparison, and a matching index.
Partners sync shipment events from our API with GET /v2/events?after=<cursor>. Each page returns up to
500 events and a next_cursor. A partner running a nightly reconciliation against their own copy reported
that a small number of events were never delivered: 31 out of about 6,200 the previous day, roughly one in
two hundred.
They sent the IDs. Every missing event existed in our database. None had been deleted. Fetching each one directly by ID worked.
Looking at the cursor
Our cursor was a base64-encoded timestamp. Decoding one from the partner's logs:
next_cursor = MjAyNi0xMC0yNlQwODoxNDowMi4wMDBa
decoded = 2026-10-26T08:14:02.000Z
And the query behind each page:
SELECT id, shipment_id, type, payload, created_at
FROM events
WHERE created_at > :after
ORDER BY created_at
LIMIT 500;
We looked at the events around one of the missing IDs:
id | created_at
---------+-------------------------
9184402 | 2026-10-26 08:14:01.998
9184403 | 2026-10-26 08:14:02.000 <- last row of page 37
9184404 | 2026-10-26 08:14:02.000 <- missing
9184405 | 2026-10-26 08:14:02.000 <- missing
9184406 | 2026-10-26 08:14:02.001 <- first row of page 38
Page 37 ended on a row at 08:14:02.000. Page 38 asked for created_at > 08:14:02.000, which excludes
every other row with exactly that timestamp. Two events fell into the gap.
Why so many identical timestamps
Most events come one at a time from scanners and have distinct timestamps. But when a truck is unloaded,
the warehouse system posts a batch of events at once, and our ingestion inserts them in one statement.
In PostgreSQL, now() returns the start time of the current transaction, so every row in that insert
gets exactly the same created_at. Batches of 20 to 300 events with identical timestamps were normal.
If a page boundary fell inside a batch, the rest of the batch was skipped.
The rule for cursor pagination
Cursor (or keyset) pagination works by remembering the sort key of the last row returned and asking for
rows after it. That is much faster than OFFSET on large tables, and it is stable when rows are inserted
during paging. But it has one hard requirement: the sort order must be total. Every row must have a
unique position, so "after this row" is unambiguous.
created_at is not unique. With a non-unique sort key:
- Using
>skips rows that share the boundary value (our bug). - Using
>=repeats them, and if more than a page of rows share one value, the client loops forever on the same page.
Neither is acceptable for a sync API.
Why tests did not catch it
Our test fixtures created events one at a time in a loop. Each insert ran in its own transaction, so timestamps differed by microseconds and the sort order happened to be total. The bug needed equal timestamps exactly at a page boundary, which only real batch traffic produced.
Environment
| Item | Value |
|---|---|
| Database | PostgreSQL 16 |
| Table | events, about 900 million rows, id bigint identity primary key |
| Index | events (created_at) |
| API | page size 500, cursor = base64 of created_at |
1. Add a unique tie-breaker to the sort
The primary key id is unique, so (created_at, id) gives a total order. The cursor carries both values
of the last row, and the query uses a row value comparison:
SELECT id, shipment_id, type, payload, created_at
FROM events
WHERE (created_at, id) > (:after_created_at, :after_id)
ORDER BY created_at, id
LIMIT 500;
(a, b) > (x, y) in SQL means a > x OR (a = x AND b > y). Rows with the same timestamp as the boundary
are included if their ID is greater, and excluded if it is smaller or equal. Nothing is skipped and nothing
repeats.
The ORDER BY must list the same columns in the same order and direction as the comparison. Ordering by
created_at, id but comparing on (created_at, id) with a different direction for one column breaks the
logic; for mixed directions you have to write the expanded OR form by hand.
2. Make the index match
The old index on created_at alone could not satisfy the new order and comparison efficiently. We built a
composite index without blocking writes:
CREATE INDEX CONCURRENTLY events_created_at_id_idx ON events (created_at, id);
The plan for a page after the change:
Limit (cost=0.57..612.10 rows=500 width=212) (actual time=0.041..1.236 rows=500 loops=1)
-> Index Scan using events_created_at_id_idx on events
Index Cond: (ROW(created_at, id) > ROW('2026-10-26 08:14:02'::timestamptz, 9184403))
Planning Time: 0.120 ms
Execution Time: 1.302 ms
PostgreSQL uses the row comparison directly as an index condition. MySQL 8 also supports row
constructors, but its optimiser has historically been less reliable at using them for range scans, so on
MySQL we use the expanded form created_at > ? OR (created_at = ? AND id > ?) and check the plan.
3. Make the cursor opaque and versioned
The new cursor encodes a small JSON object, and it is signed so clients cannot construct or tamper with it:
def encode_cursor(row) -> str:
raw = json.dumps({"v": 2, "t": row.created_at.isoformat(), "id": row.id}).encode()
sig = hmac.new(CURSOR_KEY, raw, "sha256").digest()[:12]
return base64.urlsafe_b64encode(raw + sig).decode().rstrip("=")
The version field let us keep accepting old v1 cursors (timestamp only) during the transition. A v1
cursor is translated to (t, 0), which means "all rows at this timestamp", so a partner resuming from an
old cursor might receive a few duplicates but never misses anything. Our docs already told partners that
event delivery is at-least-once and to deduplicate by event ID.
4. Consider ordering by the ID alone
For this table, id is an identity column, increasing with insert order. We could have paginated on id
alone. We kept created_at first because partners filter by time range and because the identity order and
created_at can differ slightly when transactions commit out of order. That last point matters for
"catch-up" sync: a row with a smaller ID can become visible after a row with a larger one. Our API
therefore only serves events older than a few seconds (created_at < now() - interval '5 seconds') so
in-flight transactions have committed before a page boundary passes them.
1. A test with a batch straddling a page boundary. This is the case the old fixtures never built:
def test_cursor_does_not_skip_equal_timestamps(client, db):
ts = datetime(2026, 10, 26, 8, 14, 2, tzinfo=UTC)
db.insert_events([{"created_at": ts} for _ in range(7)]) # one batch, same timestamp
seen, cursor = [], None
while True:
page = client.get("/v2/events", params={"after": cursor, "limit": 3}).json()
seen += [e["id"] for e in page["data"]]
if not page["next_cursor"]:
break
cursor = page["next_cursor"]
assert len(seen) == 7 and len(set(seen)) == 7
On the old code this returned 3 events. On the new code, all 7, no duplicates.
2. A property test. Hypothesis generates random sets of timestamps with many collisions and random page
sizes, pages through them, and asserts the result equals SELECT id ORDER BY created_at, id. It ran 2,000
cases without a failure.
3. Partner reconciliation. We offered the partner a resync from the start of the affected period. Their next three nightly reconciliations matched exactly.
4. Security implications. Signing the cursor stopped clients from crafting cursors to probe arbitrary positions, which mattered less here than for APIs where the cursor can encode filters. We also confirmed the cursor does not bypass authorization: the query still applies the partner's account scope, and a cursor from one partner is rejected for another because the account ID is part of the signed payload.
Takeaways
- Cursor pagination needs a total order. Add a unique column, usually the primary key, as a tie-breaker.
- Compare with row values,
(created_at, id) > (?, ?), and order by the same columns. - Build a composite index that matches the order exactly, and check the plan.
- Test with many rows sharing the sort value across a page boundary, which is where the bug lives.
References: PostgreSQL row constructor comparison, PostgreSQL current date and time functions, CREATE INDEX CONCURRENTLY.
Add a label
Embed this post
<iframe src="https://hibug.me/cursor-pagination-skips-rows-duplicate-sort-key" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I build and maintain public and partner APIs, currently for a logistics platform with web, mobile and third-party clients all calling the same endpoints. Before that I worked on identity: login, sessions, OAuth integrations and the long tail of edge cases they create. The bugs I care about sit at the contract between client and server. A PUT that wiped fields the client never sent, a cache that served one user's page to another, a field removal that broke app versions still in the wild, a refresh flow that logged people out when two tabs raced. None of these show up in a happy-path demo. My posts walk through how each one surfaced, what the HTTP or auth spec actually says, the fix we shipped and the tests we added so the next change to the API does not repeat it.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.