We are going to design a safe pagination and consistency policy for an API.
The main goals are:
- Avoid common pitfalls in pagination (like skipping pages, missing items, duplicates, etc.)
- Provide consistency guarantees (especially in the face of concurrent updates)
We'll consider two common pagination strategies:
a) Offset-based (using offset and limit)
b) Cursor-based (using a cursor, usually an opaque token that represents the last seen item)
However, note that offset-based pagination can be problematic for large datasets and when data changes frequently.
We'll also consider consistency models:
- Strong consistency: every read sees the latest write.
- Eventual consistency: reads might not see the latest write, but eventually will.
But note: for pagination, we often have to balance between consistency and performance.
Steps for a safe pagination:
-
Prefer cursor-based pagination over offset-based for large datasets and when data is changing.
Why?
- Offset-based: if items are inserted/deleted, then the same offset can return different items on subsequent pages.
- Cursor-based: the cursor encodes the last item's attributes (like id, timestamp) so that even if new items are inserted, they won't appear in the current pagination session (unless they are inserted before the cursor). Also, it's more efficient for large offsets.
-
For cursor-based pagination, we need to decide on the cursor encoding.
Common approach: use a base64 encoded string of the last item's unique identifier (and maybe other sort fields).
Example: cursor=base64("id:12345") for the next page after item with id 12345.
-
Sorting:
- The API should have a deterministic sort order. Typically by a unique, immutable field (like creation timestamp and id) or by the primary key.
- The cursor must be built from the same sort fields.
-
Consistency policy:
- We can offer two modes:
a) Strongly consistent: each page is a snapshot of the data at the time of the first request. This might be expensive (like using a transaction with repeatable read) and might not scale.
b) Eventually consistent: each page is independently consistent, but the entire list might not be from the same snapshot. This is easier to implement and scales better.
However, note that even with cursor-based pagination, if we are not snapshotting, then between pages the data might change (new items inserted before the current cursor might be missed, or deleted items might cause gaps).
-
To achieve a consistent view across pages (like a snapshot) without heavy transactions, we can use:
- A timestamp or version that is taken at the first request and then passed along (like a
snapshot_time parameter). Then each page uses that snapshot.
- But note: if the data is large, holding a snapshot for a long time might be expensive (in terms of storage and performance).
-
Alternatively, we can design for "read-your-writes" consistency only for the user making the request? But that's more about user session.
-
Another idea: use a cursor that includes a version or timestamp of the system at the time of the first page. Then each subsequent request uses that version. This is similar to the snapshot idea.
-
However, if we are using cursor-based and the cursor is built from the last item's attributes, then if an item is updated (and the update changes the sort field) then we might have issues. So we must ensure that the sort fields are immutable (or at least, if they change, the item might move in the list and break the pagination). Therefore, we should sort by immutable fields.
-
Policies:
a) Pagination parameters:
- Use cursor (opaque string) for next page, and maybe previous_cursor for previous page? Or just use the same cursor in reverse?
- If using forward pagination: cursor points to the last item of the current page, and the next page returns items after that cursor.
- For backward pagination, we might need a different cursor (or the same cursor but in reverse order). Alternatively, we can require clients to store the first item of the current page to go back? That's not user-friendly.
b) Consistency:
Option 1: Snapshot consistency (strong consistency across pages)
- The first page request creates a snapshot (or uses a transaction with a consistent snapshot) and returns a cursor that includes the snapshot identifier (or the timestamp/version).
- Subsequent pages use that cursor (which includes the snapshot) and therefore see the same view of the data as the first page.
- This is safe but might be heavy on the database.
Option 2: Eventual consistency per page (no snapshot)
- Each page is a consistent view of the data at the time of that request, but the entire pagination session might not be from the same point in time.
- This can lead to:
* Missing items: if an item is inserted between page1 and page2 and the insertion happens at a position that should have been in page2, then it might be missed because the cursor for page2 is based on the last item of page1 (which doesn't include the new item).
* Duplicate items: if an item is deleted between pages, then the next page might start at the same cursor and we might see the same item again? Actually, if we are using cursor-based and the cursor is based on the last item's id, then deletion of that last item might break the pagination? We must handle that.
How to handle deletion in cursor-based?
- If the item used as cursor is deleted, then we might not be able to find the next set. We can either:
* Return an error and ask the client to restart.
* Or, if we are using a unique and immutable cursor (like a global version number or a timestamp that doesn't change) then even if the item is deleted, we can still use the cursor to continue because we are looking for items with a greater cursor value.
Therefore, we must design the cursor to be based on immutable and ever-increasing fields (like an auto-increment id, or a creation timestamp with a tie-breaker id).
-
Recommended approach for a safe and scalable pagination:
a) Use cursor-based pagination with a cursor that is built from:
- The sort fields (which must be immutable). Example: `(created_at, id)` where `created_at` is the creation timestamp and `id` is the primary key.
- The cursor is then the base64 encoding of `created_at` and `id` (or just the id if we are sure it's ever-increasing and unique).
b) Provide two consistency modes (if the use case requires):
Mode 1: Snapshot (strong consistency)
- The first request returns a `snapshot_id` (or a `consistency_token`) along with the first page and a cursor that is tied to that snapshot.
- The client must send the `snapshot_id` (or the cursor that includes it) in subsequent requests.
- The server uses the snapshot to ensure all pages are from the same point in time.
Mode 2: No snapshot (eventual consistency, but safe in terms of not missing or duplicating items as long as the cursor fields are immutable)
c) However, note that even without snapshot, if we use immutable cursor fields, then:
- New items with a `created_at` after the cursor's `created_at` (or with a higher `id` if sorting by id) will not appear in the current pagination session. That's acceptable because the client is asking for items after a certain point.
- But if an item is updated and the update changes the sort field, then we have a problem. So we must not allow updates to the sort fields. Alternatively, we can use a fixed sort by `id` (which is immutable) and then the cursor is just the last `id` of the page.
d) Therefore, we can design:
Sort by: `id` (ascending) [assuming `id` is a unique, ever-increasing integer or a similar globally unique and sortable value]
Then the cursor is simply the last `id` of the page.
This way:
- Insertions: new items with higher `id` will not appear in the current pagination (which is correct, because we are going from a starting point forward).
- Deletions: if an item with an `id` that is in the middle is deleted, then we might have a gap, but that's acceptable because we are not expecting to see that item anyway? Wait, what if we are on page 1 and the last item of page1 is id=100. Then we ask for items with id>100. If the item with id=100 is deleted, then the next item is id=101. That's fine.
But what if we are using an offset and an item is deleted? Then the offset would shift and we might see duplicates or miss items. With cursor-based on id, we are safe.
However, note: if we are sorting by `created_at` and `id` (as a tie-breaker) and the `created_at` is mutable (like an update timestamp), then if an item is updated and its `created_at` changes, it might move in the list. So we must avoid mutable sort fields.
e) So the rule: sort by immutable fields only.
11. Implementation:
For a resource, we define:
- The default sort field(s): `sort_by` (must be immutable). We can let the client choose the sort? But then the cursor must be built accordingly and the client must send the same sort in subsequent requests. It's simpler to fix the sort.
Example endpoint:
GET /items?limit=20&cursor=xyz
The response:
{
"data": [...],
"next_cursor": "base64_encoded_string_for_next_page",
"previous_cursor": "base64_encoded_string_for_previous_page" (optional, for backward pagination),
"has_more": true/false
}
How to generate the cursor?
Let's say we sort by `id` (ascending). The cursor for the next page is the `id` of the last item in the current page.
Then for the next page, we query: `SELECT * FROM items WHERE id > last_id ORDER BY id ASC LIMIT 20`
For backward pagination, we might do:
We can also return a `previous_cursor` which is the `id` of the first item in the current page. Then for the previous page: `SELECT * FROM items WHERE id < first_id ORDER BY id DESC LIMIT 20` and then reverse the results? Or we can return the items in reverse order? It's common to return the same order (ascending) but then we have to reverse the query and then reverse the results? That's inefficient.
Alternatively, we can avoid backward pagination and only support forward. Then we don't need `previous_cursor`.
But if we want to support both, we can:
- The cursor is always the last item's id for forward, and for backward we can use a different parameter? Or we can have two types of cursors: forward and backward.
However, to keep it simple, let's only support forward pagination. Then we only need to encode the last item's id.
But note: if we are using multiple sort fields, then the cursor must include all of them.
Example with two fields: `created_at` and `id`. We sort by `created_at ASC, id ASC`.
Then the cursor must be the `created_at` and `id` of the last item.
Then the next page query:
`SELECT * FROM items WHERE (created_at > last_created_at) OR (created_at = last_created_at AND id > last_id) ORDER BY created_at ASC, id ASC LIMIT 20`
This is why we need to encode both in the cursor.
12. Snapshot consistency:
If we want snapshot consistency, then we need to fix the point in time. We can do:
- The first request without a cursor (or with a special `snapshot_start` parameter) creates a snapshot (or uses a transaction with a consistent snapshot) and returns a `snapshot_id` (which is a timestamp or a transaction id) and the first page.
- Then the client must send the `snapshot_id` (or a cursor that includes it) in subsequent requests.
- The server then runs the query with that snapshot (or at that point in time).
But note: if we are using a database that supports MVCC (like PostgreSQL) we can use the transaction snapshot. But holding a transaction open for multiple requests is not feasible. So we might need to store the snapshot (like the xmin or a timestamp) and then use that to filter.
Example with PostgreSQL: we can use `SET TRANSACTION SNAPSHOT` but that requires the same transaction. Alternatively, we can use a `AS OF` timestamp if we are using logical decoding or a system that supports time travel.
Alternatively, we can use a version vector or a commit timestamp. This is complex and database-specific.
Given the complexity, if we need strong consistency, we might have to use a different approach (like returning all data in one request if possible) or accept that pagination might not be strongly consistent.
13. Conclusion:
For most APIs, cursor-based pagination with immutable sort fields and without snapshot is safe and efficient.
We must document that the pagination is eventually consistent and that the list is a snapshot of the data at the time of each request (but not the same snapshot across pages). And that the client should be prepared for items to be missing (if inserted before the cursor) or duplicates (if an item is updated and moves in the list? Actually, if the sort field is immutable, then updates don't move the item. So duplicates should not happen because we are using > condition on the cursor fields.
But note: if an item is updated and the update changes a non-sort field, that's fine.
However, if we allow the client to choose the sort, then we must ensure that the sort fields are immutable for that resource. If the client sorts by a mutable field, then we cannot guarantee consistency. So we should restrict sorting to immutable fields.
14. Policy:
a) We will use cursor-based pagination.
b) The cursor is an opaque string that encodes the values of the sort fields of the last item.
c) The sort fields must be immutable and unique (or with a tie-breaker that is immutable). We will fix the sort order (or allow the client to choose from a set of allowed sort fields that are immutable).
d) We will not support backward pagination to keep it simple. If needed, we can implement it by having the client reverse the list on their side and use forward pagination on the reversed list? Or we can have a separate endpoint for reverse order.
e) We will not provide snapshot consistency by default because it's expensive. If a client needs a consistent snapshot, they should use a different endpoint that returns the entire list (if feasible) or we can provide a `snapshot_id` parameter that they can get from the first page and then use for subsequent pages (but this is complex and might not be supported by all databases).
f) We must handle the case when the cursor is invalid (tampered or expired). We can return an error.
g) We must set a maximum limit to avoid excessive data transfer.
h) We should also consider rate limiting and resource usage.
15. Example implementation:
Let's assume we have a resource `items` and we sort by `id` (ascending). The `id` is an auto-increment integer.
Endpoint: GET /items
Parameters:
- limit: integer (optional, default 20, max 100)
- cursor: string (optional, base64 encoded integer representing the last id of the current page)
Steps:
If cursor is provided:
- Decode the cursor to get the last_id (integer).
- Query: `SELECT * FROM items WHERE id > last_id ORDER BY id ASC LIMIT limit`
Else:
- Query: `SELECT * FROM items ORDER BY id ASC LIMIT limit`
Then, if we get `limit` items, then we have more, so we set `has_more=true` and the next cursor is the last item's id (encoded).
If we get less than `limit`, then `has_more=false` and next cursor is null.
But note: what if the item with `last_id` is deleted? Then we are using `id > last_id` and we won't get that item, which is fine.
However, if we are using multiple sort fields, we must decode the cursor to get all fields and then use a condition that covers all.
16. Edge cases:
- If the client provides a cursor that is not a base64 string or doesn't decode to a valid value, return 400.
- If the cursor is for an item that doesn't exist, then we just start from the next available item? That might be acceptable.
Example: cursor=base64(100) but there is no item with id=100. Then we do `WHERE id > 100` and that's fine.
But if we are using multiple fields and the cursor is for a combination that doesn't exist, then we might have to adjust? Actually, we are using `>` on the combination, so it's safe.
17. Summary of the policy:
- Use cursor-based pagination with an opaque cursor that encodes the last item's immutable sort fields.
- Sort by immutable fields (and if multiple, then all must be immutable and the combination must be unique or we use a tie-breaker that is also immutable).
- Do not support backward pagination (or if needed, use a separate endpoint with reverse sort).
- Do not guarantee snapshot consistency across pages (unless we implement a snapshot mode, which is expensive and optional).
- Set a reasonable limit and handle invalid cursors.
18. If we want to support multiple sort orders (like ascending and descending), then:
We can have a parameter `sort` that specifies the field and direction. But then the cursor must be built accordingly and the query condition changes.
For descending order:
We want items with `id < last_id` (if we are going backwards in id). But note: if we are going forward in descending order, then we are going from high id to low id.
Actually, if we are sorting by `id DESC`, then the first page is the highest ids. The cursor for the next page (which is the next set of lower ids) is the last item's id (which is the smallest in that page). Then we do `WHERE id < last_id`.
So the condition depends on the sort order.
Therefore, the cursor must encode:
- The sort fields and their order? Or we can fix the sort order and not let the client choose?
To keep it simple, we can:
Option 1: Only allow one sort order (e.g., by `id` ascending). Then the cursor is just the last id and the condition is `id > last_id`.
Option 2: Allow the client to choose the sort, but then the cursor must encode the sort fields and the values, and also the sort order? Actually, the cursor should be such that we can reconstruct the condition.
We can do:
The cursor is a base64 encoded JSON of:
{
"sort_fields": [{"field": "id", "order": "asc"}], // but we don't need to encode the sort if the endpoint uses a fixed sort?
"values": [100] // the values of the sort fields for the last item
}
But if the client can choose the sort, then we must store the sort order in the cursor? Alternatively, we can have the client send the same sort parameters with every request. Then we don't need to store the sort in the cursor, but we must validate that the sort is the same across pages.
This is getting complex.
Given the complexity, for a safe and simple policy, we:
- Fix the sort order for the endpoint (e.g., by `id` ascending).
- The cursor is just the last `id` (encoded).
If the client wants a different sort, they can use a different endpoint (like `/items?sort=created_at`) but then we must fix the sort for that endpoint and the cursor is based on that sort.
But then we have to maintain multiple endpoints? Or we can have one endpoint with a `sort` parameter, but then the cursor must be built for that sort. And we must ensure that the client uses the same sort for the entire pagination.
We can do:
The endpoint has a required `sort` parameter (or a default). The cursor is built from the sort fields. The client must send the same `sort` in every request. If they change the sort, we return an error or ignore the cursor?
We can:
- Require that if a cursor is provided, then the `sort` parameter must be the same as the one used to generate the cursor. We can store the sort fields in the cursor.
How about:
The cursor is a base64 encoded string of a JSON object that contains:
{
"v": 1, // version of the cursor format
"sort": [{"field": "id", "order": "asc"}], // optional if we fix the sort?
"values": [100]
}
Then when we decode, we check that the sort in the cursor matches the current request's sort (if provided). If not, return an error.
But if we fix the sort for the endpoint, we don't need to store the sort in the cursor.
So, to keep it simple:
We will fix the sort for each endpoint. The cursor is then only the values of the sort fields.
Example:
Endpoint: GET /items?sort=id_asc
Then the cursor is the last `id` (since we are sorting by `id` ascending).
If we have another endpoint: GET /items?sort=created_at_desc
Then the cursor is the last `created_at` (and maybe also `id` if there are ties). But note: if we sort by `created_at` descending, then the condition is `created_at < last_created_at` (or `<=` and then break ties with `id`).
Actually, for descending order:
We want items with a `created_at` less than the last one? Wait:
If we are going from latest to oldest (created_at DESC), then the first page has the latest. The last item in the first page has the oldest `created_at` in that page. Then the next page should have even older items, so condition: `created_at < last_created_at` (or `created_at <= last_created_at AND id < last_id` if we use tie-breaker).
So the condition depends on the order.
Therefore, the cursor must encode the sort fields and also the sort order? Or we can deduce the order from the endpoint's fixed sort.
Since we are fixing the sort for the endpoint, we know the order. So we don't need to store the order in the cursor.
Example:
For endpoint with `sort=created_at_desc`:
The cursor is the `created_at` and `id` of the last item.
Condition: `(created_at < last_created_at) OR (created_at = last_created_at AND id < last_id)`
But note: if we are sorting by `created_at DESC, id DESC` then the condition for the next page (which is older) is `(created_at < last_created_at) OR (created_at = last_created_at AND id < last_id)`?
Actually, if we are sorting by `created_at DESC, id DESC`, then the items with the same `created_at` are sorted by `id` descending. So the last item in the page has the smallest `id` for that `created_at`. Then the next page should have items with `created_at` less than that, or same `created_at` but `id` less than that?
Let me think:
We have:
ORDER BY created_at DESC, id DESC
So the first page (page1) has:
created_at=2024-01-02, id=200
created_at=2024-01-02, id=199
created_at=2024-01-01, id=100
Then the cursor is (2024-01-01, 100). The next page should have items with created_at < 2024-01-01, or created_at = 2024-01-01 and id < 100? But note: we are sorting by `created_at DESC` and then `id DESC`. So for the same `created_at`, we want higher `id` first. So if we are at (2024-01-01, 100), then the next item with the same `created_at` would be `id` < 100? But that would be older in terms of id? Actually, we are going from high to low in both.
Wait, the condition for the next page (which is older) is:
We want items that are after the last item in the current page in the sort order.
Since the sort order is `created_at DESC, id DESC`, then "after" means:
Either `created_at` is less than the last `created_at` (because descending, less is older and comes after in the order),
or `created_at` equal and `id` less than the last `id`.
So condition: `(created_at < last_created_at) OR (created_at = last_created_at AND id < last_id)`
But note: if we are sorting by `created_at ASC, id ASC`, then the condition for the next page (which is newer) is:
`(created_at > last_created_at) OR (created_at = last_created_at AND id > last_id)`
So the condition depends on the order of each field.
To avoid this complexity, we can:
- Only allow sorting by a single field that is immutable and ever-increasing (like `id`). Then the condition is always `id > last_id` for ascending and `id < last_id` for descending.
- If we allow multiple fields, then we must store the sort order in the cursor? Or we can have the cursor be a tuple of the sort field values and then we construct the condition based on the fixed sort order of the endpoint.
Given the complexity, for a safe and simple policy, we:
- Only allow sorting by a single immutable field that is either always increasing (like `id` or `created_at` if we never update it) or always decreasing? Actually, we can allow both ascending and descending on that field.
Example:
Allow `sort` parameter: `id` (default ascending) or `-id` for descending.
Then the cursor is the value of that field (the `id`). And the condition:
If sort is ascending (or not specified, default ascending): `id > last_id`
If sort is descending: `id < last_id`
This is simple and safe.
But what if we want to sort by `created_at`? Then we must ensure `created_at` is immutable. And we can allow `sort=created_at` and `sort=-created_at`.
Then the cursor is the `created_at` (and if there are duplicates, we need a tie-breaker?).
So we must have a unique combination. Therefore, we can:
- Always sort by two fields: the chosen field and then `id` as tie-breaker.
Then the cursor must contain both.
Example:
sort=created_at (ascending) -> sort by `created_at ASC, id ASC`
The cursor is (created_at, id).
Condition: `(created_at > last_created_at) OR (created_at = last_created_at AND id > last_id)`
For descending:
sort=-created_at -> sort by `created_at DESC, id DESC`
Condition: `(created_at < last_created_at) OR (created_at = last_created_at AND id < last_id)`
So we can do:
The endpoint allows `sort` parameter that can be a field name, and we always add `id` as the second sort field in the same order? Actually, we must decide the order of the tie-breaker.
We can:
If the sort field is ascending, then we sort by `sort_field ASC, id ASC`
If the sort field is descending, then we sort by `sort_field DESC, id DESC`
Then the cursor is the tuple (sort_field_value, id).
And the condition is built accordingly.
This is safe because `id` is immutable and unique.
19. Final policy:
a) Endpoint: GET /items
Parameters:
- limit: integer (1..100, default 20)
- sort: string (optional, default "id", allowed values: "id", "created_at", "-id", "-created_at")
- cursor: string (optional, base64 encoded JSON array of two values: [sort_field_value, id])
Steps:
Parse `sort`:
- If `sort` is "id": then order by `id ASC`
- If `sort` is "-id": then order by `id DESC`
- If `sort` is "created_at": then order by `created_at ASC, id ASC`
- If `sort` is "-created_at": then order by `created_at DESC, id DESC`
If cursor is provided:
- Decode cursor to get [last_sort_value, last_id]
- Build condition based on sort:
For `id ASC`: `id > last_id`
For `id DESC`: `id < last_id`
For `created_at ASC, id ASC`: `(created_at > last_sort_value) OR (created_at = last_sort_value AND id > last_id)`
For `created_at DESC, id DESC`: `(created_at < last_sort_value) OR (created_at = last_sort_value AND id < last_id)`
Query with the condition and order by the same sort, limit `limit`.
Then, the next cursor is the last item's sort_field_value and id (encoded as base64 of JSON array).
Note: the `sort_field_value` must be the value of the first sort field in the current page's last item.
Example for `created_at ASC`:
Last item: created_at='2024-01-01', id=100
Then cursor = base64(['2024-01-01', 100])
Then for the next page, we use that cursor and build the condition as above.
b) Consistency:
This method provides a consistent pagination in the sense that we won't miss or duplicate items as long as the sort fields are immutable and the `id` is unique and immutable.
However, if an item is inserted with a `created_at` that is between two items that we already paged through, then it won't appear in the current pagination session (because we are using a cursor that is based on the last item's `created_at` and `id`). That's acceptable because the client is asking for items after (or before) a certain point.
But note: if we are using `created_at` and an item's `created_at` is updated (which we assume we don't allow because we said `created_at` is immutable) then it might move. So we must not allow updates to the sort fields.
c) Error handling:
- If the cursor cannot be decoded, return 400.
- If the cursor values are of the wrong type, return 400.
- If the sort parameter is invalid, return 400.
d) Security:
- The cursor is opaque, so we don't expose internal data (like total counts or ids in plain). But note: we are encoding the sort field values and id. If the client can guess the id, that might be a problem? We are not exposing more than what they would get in the response anyway.
We can encrypt the cursor to hide the values? But it's not necessary because the client already sees the id in the response. However, if we don't want the client to know the exact `created_at` (maybe it's sensitive), then we can use a hash or encryption. But then we must be able to query by that? That's not possible.
Alternatively, we can use a token that maps to the values on the server side. But that requires state. We want to be stateless.
So we accept that the cursor is just base64 of the values. If the values are sensitive, then we should not use them as sort fields? Or we can use a different field that is not sensitive.
Example: if `created_at` is sensitive, then we don't use it for pagination? Or we use a different field like `public_id` that is not sensitive.
So the choice of sort fields must consider data sensitivity.
20. Example implementation in code (pseudo):
function paginate(sort, cursor, limit):
if sort == 'id':
order_by = 'id ASC'
elif sort == '-id':
order_by = 'id DESC'
elif sort == 'created_at':
order_by = 'created_at ASC, id ASC'
elif sort == '-created_at':
order_by = 'created_at DESC, id DESC'
else:
error
if cursor:
try:
decoded = base64decode(cursor)
values = json.parse(decoded) # [value, id]
last_value = values[0]
last_id = values[1]
except:
error
if sort in ['id', '-id']:
if sort == 'id':
condition = 'id > ' + last_id
else:
condition = 'id < ' + last_id
else: # created_at
if sort == 'created_at':
condition = '(created_at > ' + last_value + ') OR (created_at = ' + last_value + ' AND id > ' + last_id + ')'
else: # -created_at
condition = '(created_at < ' + last_value + ') OR (created_at = ' + last_value + ' AND id < ' + last_id + ')'
query = 'SELECT * FROM items WHERE ' + condition + ' ORDER BY ' + order_by + ' LIMIT ' + limit
else:
query = 'SELECT * FROM items ORDER BY ' + order_by + ' LIMIT ' + limit
results = db.query(query)
if len(results) == limit:
has_more = True
last_item = results[-1]
if sort in ['id', '-id']:
next_cursor_value = last_item.id
else:
next_cursor_value = [last_item.created_at, last_item.id]
next_cursor = base64encode(json.stringify(next_cursor_value))
else:
has_more = False
next_cursor = None
return {
'data': results,
'next_cursor': next_cursor,
'has_more': has_more
}
21. Note: The above code is vulnerable to SQL injection if we don't use parameterized queries. We must use parameters.
So we should use parameterized queries. The condition becomes:
For `id > last_id`: `WHERE id > :last_id`
For `created_at` case:
`WHERE (created_at > :last_value) OR (created_at = :last_value AND id > :last_id)`
And then we pass `last_value` and `last_id` as parameters.
22. Summary:
We have designed a safe pagination system using cursor-based pagination with immutable sort fields and a tie-breaker (id). We support two sort fields (id and created_at) in both ascending and descending orders. The cursor is an opaque base64 encoded JSON array of the first sort field's value and the id. We do not guarantee snapshot consistency across pages, but we guarantee that we won't miss or duplicate items as long as the sort fields are immutable.
This is a practical and safe approach for most APIs.</think>
I'll design a comprehensive safe pagination and consistency policy for APIs that addresses common pitfalls while maintaining performance and scalability. Here's the complete solution:
Safe Pagination & Consistency Policy
1. Core Principles
- Statelessness: No server-side session storage
- Predictable behavior: Same request → same results (within consistency guarantees)
- Safety first: Prevent data loss, duplication, and infinite loops
- Scalability: Works with billions of records
2. Pagination Strategy: Cursor-Based (Recommended)
Why cursor over offset?
- Offset-based:
?page=2&limit=50 → Skips first 100 records (expensive, fragile with changes)
- Cursor-based:
?cursor=eyJpZCI6MTIzfQ== → "Give me records after ID 123"
Implementation:
GET /api/v1/resources?limit=50&cursor=eyJpZCI6MTIzfQ==&sort=created_at,id
Cursor structure (opaque base64 encoded):
{
"v": 1, // version
"sort": ["created_at", "id"], // sort fields used
"values": ["2024-01-15T10:30:00Z", 12345] // last item's values
}
3. Sorting Requirements
MANDATORY:
- Always include unique tiebreaker (usually
id or created_at+id)
- Immutable sort fields only (never use mutable fields like
updated_at or status)
- Explicit sort direction for each field
Example safe sorts:
?sort=created_at,id # ASC by created_at, then ASC by id
?sort=-created_at,id # DESC by created_at, then ASC by id
?sort=priority,created_at,id # Multi-field with tiebreaker
Forbidden sorts:
?sort=updated_at # ❌ Mutable field
?sort=name # ❌ No unique tiebreaker
4. Consistency Models
Option A: Monotonic Consistency (Default)
GET /api/v1/resources?cursor=...&consistency=monotonic
- Guarantee: Never see duplicates or missing items within a pagination session
- How: Each page uses
> LAST_CURSOR_VALUES (or < for reverse)
- Trade-off: New items inserted before cursor won't appear until session restart
- Use case: Feeds, logs, activity streams
Option B: Snapshot Consistency (Strong)
GET /api/v1/resources?cursor=...&consistency=snapshot&snapshot_id=abc123
- Guarantee: All pages from same point-in-time snapshot
- Implementation:
- First request:
POST /snapshots → returns snapshot_id (timestamp/version)
- Subsequent pages: include
snapshot_id
- Backend uses MVCC or temporal queries (PostgreSQL
AS OF, DynamoDB Timestamp condition)
- Trade-off: Higher DB load, longer snapshot retention
- Use case: Financial reports, audit trails
Option C: Eventual Consistency (Fastest)
GET /api/v1/resources?cursor=...&consistency=eventual
- No guarantees - may see duplicates/gaps with concurrent writes
- Use case: Analytics, non-critical dashboards
5. Critical Safety Rules
5.1 Never Do This:
// ❌ ANTI-PATTERN: Offset-based
GET /items?offset=1000&limit=50 // Skips 1000 rows (O(n) performance)
// ❌ ANTI-PATTERN: Unbounded pagination
GET /items?limit=1000000 // Can crash DB
// ❌ ANTI-PATTERN: Mutable sort
GET /items?sort=updated_at // Items jump between pages when updated
5.2 Always Do This:
// ✓ Safe cursor request
GET /items?limit=100&cursor=eyJ2IjoxLCJzb3VyIiwiaWQiLCJ2YWx1ZXMiOlsiMjAyNC0wMS0xNSIsMTIzNDVdfX0=&sort=created_at,id
// ✓ With max limit
GET /items?limit=100 // Server enforces max_limit=1000
// ✓ With snapshot for consistency
GET /items?cursor=...&snapshot_id=2024-01-15T10:00:00Z
6. Implementation Checklist
Frontend/Client:
Backend/API:
Database:
7. Response Format
{
"data": [...],
"pagination": {
"next_cursor": "eyJ2IjoxLCJzb3VyIiwiaWQiLCJ2YWx1ZXMiOlsiMjAyNC0wMS0xNSIsMTIzNDVdfX0=",
"has_more": true,
"limit": 100,
"sort": "created_at,id",
"consistency": "monotonic",
"approximate_total": 15432 // Optional, expensive
},
"links": {
"next": "/api/v1/resources?cursor=...&limit=100",
"self": "/api/v1/resources?cursor=..."
}
}
8. Edge Case Handling
| Scenario | Safe Handling |
|---|
| Deleted items | Skip them silently (cursor points to ID, not position) |
| Updated sort field | ❌ Prevent updates to immutable sort fields |
| Cursor too old | Return 400 Bad Request with "error": "cursor_expired", "restart_from": "beginning" |
| Empty page | Return has_more: false with empty data |
| Concurrent inserts before cursor | Won't appear (by design for monotonic) |
| Clock skew | Use DB server time, not client time |
9. Rate Limiting & Security
- Cursor discovery rate limit: 100 cursors/IP/minute (prevent enumeration)
- Max depth limit: Prevent infinite loops with
?limit=1000&cursor= malformed
- Cursor TTL: 24 hours (after which force restart)
- Opaque cursors: Always base64 encode/encrypt if exposing sensitive data
10. Migration Path from Offset-Based
// Step 1: Support both during transition
GET /items?offset=100&limit=50&legacy=true // Converts to cursor internally
// Step 2: Deprecate offset with warning header
Warning: 299 - "Offset pagination deprecated, use cursor"
// Step 3: Remove offset support entirely
11. Sample Implementation (Pseudocode)
def paginate_resources(limit, cursor, sort, consistency):
# 1. Validate inputs
validate_sort(sort) # Must be in ALLOWED_SORTS
limit = min(limit, MAX_LIMIT)
# 2. Parse cursor
if cursor:
cursor_data = decode_cursor(cursor)
validate_cursor_fields(cursor_data, sort)
condition = build_condition(cursor_data, sort, consistency)
else:
condition = "TRUE"
# 3. Build query with proper indexes
query = f"""
SELECT id, field1, field2
FROM resources
WHERE {condition}
ORDER BY {sort}
LIMIT {limit + 1} -- Fetch one extra to check has_more
"""
# 4. Execute with parameterized queries
results = db.execute(query, cursor_data.get('values', []))
# 5. Build response
has_more = len(results) > limit
if has_more:
results = results[:-1] # Remove extra item
next_cursor = None
if has_more:
last_item = results[-1]
next_cursor = encode_cursor({
'v': 1,
'sort': parse_sort(sort),
'values': extract_sort_values(last_item, sort)
})
return {
'data': results,
'pagination': {
'next_cursor': next_cursor,
'has_more': has_more,
'limit': limit
}
}
12. Testing Checklist
13. Monitoring Metrics
# Pagination health
api_pagination_cursor_invalid_total
api_pagination_has_more_ratio
api_pagination_avg_page_time_seconds
api_pagination_duplicate_items_total # Should be 0
# Consistency violations
api_pagination_missing_items_total # Should be 0 for monotonic
api_pagination_snapshot_misses_total
14. When to Use Alternatives
| Use Case | Recommended |
|---|
| Large datasets (>1M) | Cursor-based |
| Real-time feeds | Cursor + WebSocket for new items |
| Admin UI with filters | Cursor + snapshot consistency |
| Small static datasets | Offset-based acceptable |
| Time-series data | Time-range cursor: ?start_time=...&end_time=... |
15. Documentation Requirements
Every paginated endpoint must document:
- Sort fields allowed (list of immutable fields)
- Default sort and direction
- Max limit and default
- Consistency model (monotonic/snapshot/eventual)
- Cursor expiration (if any)
- Index requirements for client-side filtering
Bottom line: Use cursor-based pagination with immutable sort fields + monotonic consistency by default. Only use snapshot consistency when business logic requires strict point-in-time views. Never use offset-based for large or frequently-changing datasets.
This policy prevents:
- ✅ Missing items (due to deletions between pages)
- ✅ Duplicate items (due to concurrent inserts)
- ✅ Performance degradation (with large offsets)
- ✅ Inconsistent views (across pages)
- ✅ Infinite loops (malformed cursors)