A user opens your feed, scrolls past the first twenty items, and sees the same card twice. Another user scrolls and never sees an item that definitely exists. Neither bug reproduces in staging, because staging has no one writing to the table while you scroll. If you are weighing cursor pagination vs offset for a mobile feed, this is the failure mode that should decide it, and it is a correctness problem long before it is a performance problem.
Why offset pagination duplicates and skips rows
The typical offset endpoint looks like this:
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 40;
The client asks for page three by saying "skip 40 rows." But "40 rows" is a position in a result set that is changing under you. Offset encodes where you were, not what you last saw.
Consider a feed sorted newest first. The client has loaded pages one and two (items 1 to 40). Before it requests page three, two new rows are inserted at the top. Every existing row shifts down by two. The query now skips the first 40 rows of the new ordering, and the last two items the client already rendered are items 39 and 40 of the old ordering, which are now items 41 and 42. They come back on page three. That is your duplicate.
Deletes cause the mirror image. Remove two rows from the first 40 and everything shifts up. Rows that were at positions 41 and 42 are now at 39 and 40, inside the region the query skips. Those items are never delivered. That is your skipped content, and it is much harder to notice because nothing looks wrong.
A mobile feed makes this worse than a web page with numbered pages, for three reasons:
- Infinite scroll keeps one long session open, so the window between page fetches is long and writes are likely to land in it.
- Pull-to-refresh and background sync reset state inconsistently, so the client and server disagree about what "page 3" means.
- Flaky connections trigger retries. A retried offset request after an insert returns a different slice than the original would have.
There is also the cost side. OFFSET 100000 forces the database to walk and discard 100,000 index entries before returning 20. Deep scrolling gets slower linearly. For most feeds nobody scrolls that deep, so treat this as secondary. The correctness bug is what bites first.
The keyset query: ask for what comes after what you saw
Keyset (cursor) pagination replaces position with a boundary. The client says "give me 20 items older than this specific item." Inserts and deletes elsewhere in the table no longer move the boundary, because the boundary is a value, not an index into a shifting list.
The naive version uses the timestamp alone:
WHERE created_at < :last_created_at ORDER BY created_at DESC LIMIT 20
This is subtly broken, and it is the version we see most often in code audits. Timestamps are not unique. Bulk imports, batched writes, and low-resolution clocks produce multiple rows with the same created_at. If a page boundary falls in the middle of a group of equal timestamps, < drops the remaining members of that group. You have traded duplicates for skips.
The stable tiebreaker
The fix is a total ordering. Add a unique column, usually the primary key, as a tiebreaker, and compare the pair:
WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 20
Row-value comparison works in PostgreSQL and MySQL 8. Where it is unsupported or the planner handles it poorly, expand it by hand:
WHERE created_at < :ts OR (created_at = :ts AND id < :id)
Whichever form you use, the ORDER BY must match the comparison exactly, in both columns and direction. A mismatch here produces results that look right in testing and break only on ties.
The compound index that makes it fast
The query is only as good as the index behind it. You want a compound index in the same column order as the sort:
CREATE INDEX posts_feed_idx ON posts (created_at DESC, id DESC);
With this in place, the database seeks directly to the boundary and reads 20 entries. Cost no longer grows with scroll depth. If the feed is filtered (per user, per tenant, per category), the filter columns lead the index: (tenant_id, created_at DESC, id DESC). Check with EXPLAIN that you see an index scan with no separate sort step. If a sort node appears, your index and your ORDER BY disagree.
Designing the cursor for a Flutter client
Do not make the client assemble (created_at, id) pairs. Return an opaque cursor, a base64-encoded blob of the last row's sort keys, plus a next_cursor field that is null when the feed is exhausted. The client's only job is to hand it back unmodified.
This keeps the API contract stable when the sort changes. If you later add a ranking score as the primary key, the Flutter and native Swift or Kotlin clients do not change at all. In a REST API design this is also where you decide how to fetch limit + 1 rows: request one extra row, return only limit, and use the presence of the extra to set next_cursor. That avoids a wasted empty request at the end of the list.
Cursors are client input, so validate them like any other input. Decode, check the shape and types, and reject anything malformed with a 400. If the cursor carries a user-visible filter or scope, bind it to the authenticated user server-side rather than trusting whatever the blob says. Sign or encrypt it if it could leak internal values.
On the client, a few habits prevent a different class of duplicates:
- Key list items by stable ID and de-duplicate on merge. Keyset pagination removes most overlap, but an item edited so its sort key moves can still appear twice across a refresh.
- Treat a refresh as a new session: drop the old cursor, fetch from the top, and replace the list rather than appending.
- Keep one in-flight request per list. Two concurrent fetches with the same cursor will both append.
What keyset does not give you
The trade-offs are real. You lose random access: there is no "jump to page 50," which is fine for a feed and wrong for an admin dashboard with a numbered grid. Sorting by a mutable column, such as "last activity," lets rows move across the cursor between fetches, so you need either an immutable sort key or an explicit decision about tolerating that drift. And every new sort order wants its own compound index, which costs write throughput and storage. Choose the sort orders you actually ship, not every one a product manager might ask for.
For a numbered admin table over a modest dataset, offset is still fine. For anything infinite-scrolled on a phone, where the data is being written to while someone reads it, keyset is the default we reach for.
At orithLabs, this kind of issue tends to surface during code audits and architectural troubleshooting on existing codebases, and it is also something we design out from the start when we build mobile backends and the Flutter clients that consume them. If you are seeing phantom duplicates or missing items in a feed and want a second pair of engineers to look at the query and the index, we are happy to talk it through.