Quick revision
The short answer
An opaque cursor lets the server change sort keys, storage or sharding without breaking clients, and stops clients from crafting cursors that skip filters or authorisation. We encode the last row's sort values plus the query context, such as {"v":1,"t":"2026-11-13T10:00:00Z","id":981,"f":"status=OPEN"}, Base64URL-encode it and sign it with an HMAC so tampering is detected; on each request we decode, verify the signature, check that filters and sort match the request (400 if not) and the version and expiry, then query WHERE (created_at, id) > (:t, :id) ORDER BY created_at, id LIMIT :size + 1, where the extra row tells us whether a next page exists.
What to remember
In this answer, we saw that an opaque cursor keeps the server free to change sorting, storage and sharding and stops clients from crafting cursors that bypass filters or authorisation. We encoded the last row's createdAt and id with the query context, a version and an expiry as JSON, Base64URL-encoded it and signed it with HMAC-SHA256, validated signature, version, expiry and filters on every request with 400 for any mismatch, and used a keyset query with LIMIT size + 1 to detect the next page.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
An opaque cursor lets the server change sort keys, storage or sharding without breaking clients, and stops clients from crafting cursors that skip filters or authorisation. We encode the last row's sort values plus the query context, such as {"v":1,"t":"2026-11-13T10:00:00Z","id":981,"f":"status=OPEN"}, Base64URL-encode it and sign it with an HMAC so tampering is detected; on each request we decode, verify the signature, check that filters and sort match the request (400 if not) and the version and expiry, then query WHERE (created_at, id) > (:t, :id) ORDER BY created_at, id LIMIT :size + 1, where the extra row tells us whether a next page exists.
Why this question is asked
Cursor pagination is the standard for large lists because it stays fast at any depth and does not skip or repeat rows when data changes between pages. But the cursor itself is part of the API contract, and if clients can read and build it, they will, and then we can never change it. Interviewers ask this to see whether we treat the cursor as a server-owned token and can implement one safely. In this answer, we will recap keyset pagination, explain why cursors should be opaque, write the encoder and validator in Java, write the query, and add versioning and expiry.
1A Quick Recap of Keyset Pagination
With offset pagination, page 3 is LIMIT 50 OFFSET 100: the database reads and discards 100 rows to return 50, which gets slower the deeper we go, and rows inserted meanwhile shift pages so clients see duplicates or miss rows. Keyset pagination instead remembers where the last page ended, the sort values of its last row, and asks for rows after that point. With an index on the sort columns, every page costs the same.
Our list is sorted by createdAt, and two rows can share the same createdAt, so we add id as a tie-breaker. The position is then the pair (createdAt, id) of the last row, which is unique and gives a total order.
2Why the Cursor Should Be Opaque
If the cursor were simply ?after=981, clients would start building it themselves, by guessing ids or combining it with other parameters. Then we could never change it. If we later sort by a different column, move the table to another store or shard it, every client that builds cursors breaks. An opaque cursor is a token the client stores and returns unchanged and cannot interpret, so its content is ours to change.
There is a security side too. A cursor that encodes position and filters could be edited to point at rows outside the client's filter, or to drop a filter the server applied for authorisation, such as a tenant restriction. Signing the cursor with a key only the server knows means any edit is detected, so clients cannot craft cursors at all.
3Encoding and Validating the Cursor in Java
The cursor carries a version, the last row's createdAt and id, the query context (the filters and sort it was created for) and an expiry. We serialise it to JSON, Base64URL-encode it so it is safe in URLs, and append an HMAC-SHA256 signature of the same bytes.
Notice a few details. MessageDigest.isEqual compares the signatures in constant time, so an attacker cannot learn the correct signature byte by byte from response times. The filter string must be built the same way every time, for example parameters sorted by name, so equivalent requests produce identical strings. Every BadCursorException maps to a 400 response with a clear error code, such as invalid_cursor, so clients know to restart from the first page. Signing makes the cursor tamper-proof but still readable after Base64 decoding; if it ever contains something the client should not see, we encrypt it instead, for example with AES-GCM, which also authenticates it.
4Writing the Next-Page Query
With the decoded cursor we fetch the next page using a row-value comparison, which PostgreSQL and MySQL both support and can serve from an index on (status, created_at, id).
- Decode Base64URL and verify HMACedited or malformed: 400
- Version, expiry and filters match the request?YesBuild the keyset queryNoReject with 400 invalid_cursor
- Query with LIMIT size + 1row-value comparison on (created_at, id)
- Return size rows and next cursorsigned cursor from the last returned row
4 steps in order. Play them, or step through them one at a time.
The extra row is a cheap trick: it tells us whether another page exists without a separate count query, so the response can omit the next cursor on the last page. The next cursor is built from the last returned row, not the extra one, so that extra row becomes the first row of the next page.
5Versions and Expiry
The version field is what makes the cursor future-proof. If we change the sort order or move the data, we bump the version, and old cursors are rejected clearly with an error, instead of being misread and silently returning wrong pages. If we can translate old cursors, the decoder can handle both versions for a transition period.
An optional expiry, for example 24 hours, limits how long a cursor can be replayed, lets us rotate the signing key without supporting old keys forever, and keeps forgotten cursors from referring to data layouts long gone. During key rotation the validator accepts signatures from both the current and the previous key.
6Follow-up questions
Should a cursor stay valid after a deployment that changes the sort order?
No, not silently. A cursor holds a position in one specific order; read in a different order, it points somewhere meaningless, so the client would skip or repeat rows without knowing. The deployment bumps the cursor version, and old cursors are rejected with a clear 400 error code telling the client to start again from the first page. If continuity matters, for example for long-running syncs, the server can keep a translation for the old version for a transition period, but it must be explicit.
Why include the filters in the cursor at all?
So a cursor created for one query cannot be used with another. Without that check, a client could take a cursor from an unfiltered admin-like query and apply it to a different filter, or change filters mid-way and get inconsistent pages. Checking that they match keeps each cursor bound to the query it came from.
Why Base64URL rather than plain Base64?
Plain Base64 uses + and /, which have special meaning in URLs and must be escaped. The URL-safe alphabet uses - and _ instead, and without padding the token can go straight into a query string.
7Conclusion
In this answer, we saw that an opaque cursor keeps the server free to change sorting, storage and sharding and stops clients from crafting cursors that bypass filters or authorisation. We encoded the last row's createdAt and id with the query context, a version and an expiry as JSON, Base64URL-encoded it and signed it with HMAC-SHA256, validated signature, version, expiry and filters on every request with 400 for any mismatch, and used a keyset query with LIMIT size + 1 to detect the next page.
Open with
A cursor should be opaque because it belongs to the server. If clients can read or build it, they will, and then we can never change the sort keys, the storage or the sharding without breaking them.
Then, if they want more
It is also a security issue: a client that can edit a cursor might skip filters or authorisation the server applied.
So I encode the last row's sort values plus the query context, for example version 1, createdAt, id 981 and the filter status=OPEN, plus an expiry, as JSON, Base64URL-encode it, and sign it with HMAC-SHA256 using a server key, so the token is the payload and the signature.
On each request I decode it, verify the signature with a constant-time comparison, check the version and expiry, and check that the filters and sort in the cursor match the request, returning 400 with a clear error if anything is wrong.
Then the query is WHERE (created_at, id) > (:t, :id) ORDER BY created_at, id LIMIT size plus one, with an index on those columns. The extra row tells me whether there is a next page, and the next cursor is built from the last row I return.
If the cursor ever held anything sensitive, I would encrypt it instead, with AES-GCM. And the version field lets me reject old cursors cleanly when the sort order changes.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Why should a cursor be opaque, and how would you encode and validate one in a Java...": https://scrivio-interview-library.netlify.app/architecture/api-design-at-scale/619b1a17fc/