Keyset (cursor) pagination
Why OFFSET slows down and shifts pages, continuing from the last row instead, tie-breakers and row comparisons, opaque cursors, the limit+1 trick, and what EXPLAIN should show.
Learning outcomes
- Explain why OFFSET gets slower with depth and returns duplicates or gaps when rows change.
- Write the keyset condition for a single key and for (created_at, id) in descending order.
- Always add a unique tie-breaker when sorting by a non-unique column.
- Encode a position as an opaque base64url cursor and reject a malformed one with 400.
- Detect the next page with limit+1 and read the list query plan with EXPLAIN.
Why pagination needs a better approach
Your restaurant database will eventually contain thousands or millions of records. Returning every restaurant in a single HTTP response is not practical.
Instead, the API returns a limited number of records at a time. The client requests the next batch when the user scrolls or navigates forward.
This is pagination.
There are two common approaches:
- OFFSET-based pagination, which skips a specified number of rows.
- Keyset pagination, which remembers the position of the last row returned and retrieves records after that position.
For a backend that serves frequently changing data, keyset pagination is generally a better fit for sequential browsing.
Your restaurant listing endpoint will use keyset pagination ordered by restaurant ID. Later, the order-history endpoint will use a timestamp and ID together.
Understanding OFFSET pagination
Consider a query that lists restaurants in ascending ID order:
SELECT id, name
FROM restaurants
ORDER BY id
LIMIT 20 OFFSET 0;The first page returns records 1 through 20.
To retrieve the second page:
SELECT id, name
FROM restaurants
ORDER BY id
LIMIT 20 OFFSET 20;This skips 20 records and returns the next 20.
The third page uses:
LIMIT 20 OFFSET 40;This approach is straightforward and supports jumping to arbitrary pages. However, it has two significant problems.
1. Increasing work for later pages
Suppose the user requests page 501 with 20 records per page.
The query becomes:
SELECT id, name
FROM restaurants
ORDER BY id
LIMIT 20 OFFSET 10000;MySQL must identify and traverse the first 10,000 qualifying rows, discard them, and then return the next 20.
Even when an index helps retrieve rows in the correct order, the database still has to process the skipped entries.
As the offset increases, more work is required before the requested page can be returned.
You can inspect this behaviour using EXPLAIN or EXPLAIN ANALYZE. The amount of work depends on the chosen access path and filtering conditions, but the fundamental problem remains: OFFSET specifies how many rows to discard, not where to begin searching.
2. Pages shift when data changes
There is another problem with OFFSET pagination: the position of a record can change between requests.
Suppose the first page contains:
1, 2, 3, 4, 5The client requests the second page using OFFSET 5.
Before the second request, a new row that sorts before them is inserted. Ids only grow, so with ORDER BY id this cannot happen, but with ORDER BY name or ORDER BY created_at DESC it happens all the time. Call the new row A.
The ordered dataset becomes:
A, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10The second page now skips the first five rows and returns:
5, 6, 7, 8, 9Restaurant 5 appears twice.
Deletions can cause the opposite problem. If a row before the current offset is removed, subsequent records shift backwards and some records may be skipped entirely.
This is undesirable for continuously changing datasets such as restaurant listings and order histories.
Keyset pagination: continue from the last row
Instead of remembering how many rows were skipped, remember the position of the last row returned.
Suppose the first page contains:
1, 2, 3, 4, 5The client remembers the final ID, 5.
The next query becomes:
SELECT id, name
FROM restaurants
WHERE id > 5
ORDER BY id
LIMIT 5;The database can use the primary-key index to find records after ID 5.
If the next page returns:
6, 7, 8, 9, 10The next cursor represents ID 10.
The query doesn't need to know how many records were previously returned.
Why this is more efficient
InnoDB maintains the primary key as an ordered index.
When MySQL receives:
WHERE id > 10000
ORDER BY id
LIMIT 20it can seek to the appropriate position in the primary index and continue scanning forward.
The database doesn't need to traverse and discard the first 10,000 rows.


With a suitable index, the amount of work is primarily related to finding the starting position and retrieving the next matching records.
This makes sequential pagination much more predictable as the dataset grows.
The importance of deterministic ordering
Keyset pagination requires a stable ordering.
Suppose you order restaurants by name:
ORDER BY nameMultiple restaurants can have the same name.
If the cursor remembers only the name, the next query cannot uniquely identify where the previous page ended.
You need a unique tie-breaker.
For example:
ORDER BY name, idNow every row has a deterministic position because id is unique.
This is a fundamental rule:
When sorting by a non-unique column, include a unique column as the final tie-breaker.
Composite sort keys and row comparisons
For your restaurant endpoint, ordering is simple:
ORDER BY idThe ID is already unique, so the cursor only needs to remember the last ID.
However, your order-history endpoint in Week 3 will use:
ORDER BY created_at DESC, id DESCHere, both columns are required to identify a unique position.
Consider these orders:
| created_at | id |
|---|---|
| 2026-10-30 10:30:00 | 105 |
| 2026-10-30 10:30:00 | 102 |
| 2026-10-30 10:25:00 | 110 |
| 2026-10-30 10:20:00 | 98 |
Notice that two orders share the same timestamp.
If the first page ends at:
created_at = 2026-10-30 10:30:00
id = 102The next page must contain rows positioned after that pair in descending order.
Row-value comparison
SQL supports comparing multiple values together using row constructors.
For descending order, the next-page condition is:
WHERE (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESCWhy < rather than >?
Because the results are ordered from newest to oldest.
Once you reach a particular timestamp and ID, subsequent records have a lexicographically smaller pair.
The same condition can be expressed explicitly:
WHERE created_at < ?
OR (
created_at = ?
AND id < ?
)
ORDER BY created_at DESC, id DESCBoth expressions describe the same logical position.
The corresponding index is:
INDEX idx_orders_user_page (user_id, created_at, id)For an individual user's history, the query also filters by:
WHERE user_id = ?The equality condition identifies the user's portion of the composite index, while the timestamp and ID provide the ordering.
MySQL can scan an appropriately ordered index backwards to satisfy descending order.
However, don't assume every row-constructor expression uses every part of an index efficiently. MySQL's optimizer has documented limitations around row-constructor comparisons and index prefixes. Compare the row-constructor and expanded forms using EXPLAIN.
The Leftmost-prefix rule rule still applies: the preceding user_id column must be constrained before the timestamp and ID parts can support the intended access pattern.
Opaque cursors
Your API shouldn't require clients to understand the internal structure of a cursor.
Instead, return an opaque cursor.
Internally, your cursor represents a position:
type Key struct {
CreatedAt time.Time
ID int64
}For the restaurant listing endpoint, only ID determines the ordering:
Key{
ID: lastID,
}CreatedAt remains zero.
For order history, both fields are required because the ordering uses timestamp and ID.
Encoding the cursor
Your implementation encodes the key as:
<unix milliseconds>:<id>For example, a conceptual key might be:
1793433000000:105This string is encoded using:
base64.RawURLEncodingBase64url uses URL-safe characters and does not include padding characters.
The resulting value can be included in a query parameter without requiring special URL escaping.
The client receives something like:
/v1/restaurants?cursor=MTc5MzQzMzAwMDAwMDoxMDUThe exact encoded value depends on the timestamp and ID.
Decoding the cursor
When the next request arrives:
- Read the cursor query parameter.
- Decode its Base64url representation.
- Split the decoded value at the colon.
- Parse the Unix milliseconds.
- Parse the ID.
- Construct the
Key.
The decoder must reject malformed input.
Your implementation uses:
var ErrInvalid = errors.New("invalid cursor")Both an empty cursor passed to Decode and malformed encoded values must return errors wrapping ErrInvalid.
The empty cursor parameter itself is different from the absence of a cursor. The service simply starts from the beginning when no cursor is supplied. An empty string passed explicitly to Decode is invalid.
A malformed cursor is a client input error. The HTTP handler must return 400, not 500.
What does opaque actually mean?
Opaque means the client treats the cursor as an uninterpreted string.
It should:
- Store the returned cursor.
- Send it back unchanged when requesting the next page.
- Never construct or modify its contents.
This gives you flexibility to change the internal encoding later without requiring changes in every client.
However, the current cursor is only Base64url-encoded.
It is not encrypted and it is not signed.
Anyone can decode it, inspect the timestamp and ID, or modify them before sending another request.
That does not directly grant access to another user's data or bypass query authorization. It simply changes the requested starting position.
The limit + 1 technique
Your API needs to know whether another page exists.
One approach would be to execute a separate COUNT(*) query.
However, this adds another database operation, and counting all matching rows can be expensive.
A simpler approach is to request one extra row.
Suppose the requested page size is 20.
Instead of querying:
LIMIT 20use:
LIMIT 21If MySQL returns at most 20 rows, there is no additional page.
If it returns 21, you know another page exists.
The extra row is used only as evidence that more data is available. It must not appear in the current response.
Your generic pagination helper has this signature:
func Page[T any](
rows []T,
limit int,
keyOf func(T) Key,
) (items []T, next string)It receives the limit+1 rows and returns:
- The first
limitrows. - An encoded cursor based on the final retained row if an extra row exists.
- An empty cursor if there is no extra row.
Consider this example:
Requested limit: 5
Rows returned by MySQL:
1, 2, 3, 4, 5, 6
Response:
1, 2, 3, 4, 5
Next cursor:
Position of row 5The cursor must represent row 5, not row 6.
Why?
Because the next query asks for records strictly after the last row actually delivered to the client.
Starting after row 6 would skip that record entirely.
The generic keyOf function
Your helper uses Go generics so that pagination logic can work with different database result structures.
The keyOf function tells it how to extract a cursor position from an individual row.
For restaurants:
func(row Restaurant) Key {
return Key{ID: row.ID}
}For order history:
func(row Order) Key {
return Key{
CreatedAt: row.CreatedAt,
ID: row.ID,
}
}The pagination helper doesn't need to know which fields belong to a restaurant or order. The caller supplies that information.
This keeps cursor encoding, page trimming, and has-more detection reusable across endpoints.
Applying pagination to the restaurant listing query
Your restaurant listing query combines geographic filtering with ID-based pagination.
-- name: ListRestaurantsNear :many
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
AND lat BETWEEN sqlc.arg(min_lat) AND sqlc.arg(max_lat)
AND lng BETWEEN sqlc.arg(min_lng) AND sqlc.arg(max_lng)
AND id > sqlc.arg(after_id)
ORDER BY id
LIMIT ?;The service performs these operations:
- Receive the decoded cursor key from the handler (the handler decodes it, so a malformed cursor becomes a 400 before the service runs).
- Take the previous restaurant ID from the key.
- Calculate the geographic bounding box.
- Request
limit + 1records from sqlc. - Pass the returned rows to
Page. - Return the retained items and next cursor.
The HTTP response is:
{
"items": [
{
"id": 7,
"name": "Restaurant 07",
"lat": 28.461234,
"lng": 77.035678
}
],
"next_cursor": "..."
}On the final page next_cursor is the empty string, and when nothing matches at all, items is an empty array:
{
"items": [],
"next_cursor": ""
}The important contract is that next_cursor is always present. An empty string means there are no more records.
Index considerations and EXPLAIN
Your restaurant query can use two relevant indexes:
PRIMARY, which supportsid > after_idand produces rows in ID order.idx_rest_geo (lat, lng), which supports geographic filtering.
Neither index perfectly satisfies every condition.
Using the primary index allows MySQL to scan forward in ID order, filtering inactive or geographically unsuitable records.
Using idx_rest_geo can narrow the latitude range, but its ordering is geographic rather than ID-based. Additional sorting may therefore be required.
Inspect the execution plan using EXPLAIN:
EXPLAIN
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
AND lat BETWEEN 28.40 AND 28.50
AND lng BETWEEN 76.95 AND 77.10
AND id > 10
ORDER BY id
LIMIT 21;With sufficiently representative data, you want to see:
keyselectingPRIMARYoridx_rest_geo.typeshowingrange.
A range scan means MySQL is using an index interval to retrieve a subset of rows.
However, a table with only 50 seeded restaurants might still produce ALL, meaning a full table scan.
That isn't automatically a problem. Scanning a tiny table may be cheaper than traversing an index and retrieving its rows separately.
Add representative data and inspect the optimizer's decision rather than forcing an index just to obtain a particular EXPLAIN output.
MySQL's EXPLAIN shows the estimated execution plan, while EXPLAIN ANALYZE actually executes the query and reports observed execution details.
Geographic filtering has another trade-off
Your query filters by a geographic bounding box but orders by ID.
When MySQL scans the primary index, it may examine many restaurants that fall outside the requested box before finding enough matching records.
This is a consequence of choosing ID ordering over geographic ordering.
For a relatively small dataset, that is acceptable.
For high-volume proximity searches, a dedicated geospatial index such as Redis GEO, which you'll encounter in Week 5, is a more appropriate way to retrieve nearby locations.
Keyset pagination trade-offs
Keyset pagination is not universally superior for every interface.
There are some limitations.
No arbitrary page jumps
You cannot efficiently jump directly to page 500 without knowing its starting cursor.
Keyset pagination is designed for sequential traversal rather than random page access.
Total counts are separate
The API does not automatically know how many matching records exist.
A separate COUNT(*) query is needed if the product genuinely requires a total count. That query may be expensive, so don't add it without a reason.
Backward pagination requires different ordering
If the client wants to move backwards, the database needs a reverse continuation condition and appropriate result ordering. This requires additional query logic.
Not a complete database snapshot
Keyset pagination avoids the positional shifts caused by OFFSET, but it doesn't create a snapshot across multiple HTTP requests.
New records inserted before the current cursor generally won't appear in subsequent pages. Records inserted after the cursor may appear.
Changes to ordering columns can also move records across the cursor position, potentially causing duplicates or omissions.
For most browsing APIs, these trade-offs are acceptable.
Knowledge assessment
Why can OFFSET pagination become increasingly expensive when a client requests later pages?
Practical applications
Exercise 2.10: GET /v1/restaurants with a cursor
You'll implement cursor encoding and decoding, generic page construction, and the restaurant listing service.
The endpoint will request limit + 1 rows, return only the requested number of restaurants, and provide an opaque cursor representing the last retained restaurant.
You'll also inspect the query plan to understand how MySQL uses the primary and geographic indexes.
Module 7: Integration testing against MySQL
The pagination integration tests will exercise the actual database query across multiple pages.
They will check that the cursor advances correctly, records aren't duplicated or skipped, and the final page returns an empty next_cursor.
Week 3: Order history
You'll reuse the same cursor implementation for order history, but this time the ordering is (created_at DESC, id DESC).
The Key structure already supports both fields, so the cursor package can remain independent of the entity being paginated.
By the end, you should understand not only how to implement cursor pagination, but also why the sort order, cursor representation, SQL predicate, and supporting index must be designed together.
References
Everything above is explained on this page; these are where it comes from (MySQL 8.4, Go 1.25).