Your Cursor Pagination Works—Until Records Change During an Export
Pagination is one of those backend features that looks simple during development.
You execute a query, apply LIMIT and OFFSET, return the requested records, and move on.
For example:
SELECT *
FROM audit_logs
ORDER BY created_at ASC
LIMIT 50 OFFSET 50;
It works. The API returns the next 50 records.
But what happens when new records are inserted while someone is navigating through the pages?
What happens when records are deleted, timestamps are identical, or a background process continuously updates the database?
Suddenly, users may see duplicate records, skip records, or receive inconsistent exports.
This is where pagination stops being just a query optimization problem and becomes a data consistency problem.
In this article, we'll explore why traditional offset pagination can become unreliable, how cursor-based pagination works, and how to implement keyset pagination using FastAPI, SQLAlchemy, and PostgreSQL.
1. The Problem With Traditional Offset Pagination
Let's consider an audit log table containing the following records.
ID | Action |
|---|
101 | User login |
102 | Password changed |
103 | Asset created |
104 | Record updated |
105 | User logout |
106 | Report generated |
Suppose our API returns two records per page.
The first request:
SELECT *
FROM audit_logs
ORDER BY id ASC
LIMIT 2 OFFSET 0;
Result:
101, 102
The second request:
SELECT *
FROM audit_logs
ORDER BY id ASC
LIMIT 2 OFFSET 2;
Result:
103, 104
So far, everything looks correct.
Now imagine another process inserts a new record before the user requests page two.
The database now contains:
100, 101, 102, 103, 104, 105, 106
The user requests page two:
SELECT *
FROM audit_logs
ORDER BY id ASC
LIMIT 2 OFFSET 2;
The result is:
102, 103
Record 102 appears again.
The user has already seen it on page one, but the second request returns it again because the position of the records has changed.
The opposite problem can happen when records are deleted: a record can move into an earlier page position and never be seen during the user's traversal.
The problem is not that OFFSET is incorrect. The problem is that OFFSET describes a position in a changing result set, not a stable position in the underlying data.
2. What Is Cursor-Based Pagination?
Instead of asking the database to skip a certain number of records, cursor pagination asks it to continue after the last record the client received.
For example, instead of saying:
"Give me records after position 50."
We say:
"Give me records after record ID 150."
A basic SQL implementation looks like this:
SELECT *
FROM audit_logs
WHERE id > 150
ORDER BY id ASC
LIMIT 50;
This is commonly called keyset pagination.
The database uses the value of the last record as the starting point for the next request.
The API response might look like:
{
"items": [
{
"id": 151,
"action": "USER_LOGIN"
},
{
"id": 152,
"action": "ASSET_CREATED"
}
],
"next_cursor": 152,
"has_next": true
}
The next request sends:
GET /audit-logs?cursor=152&limit=50
This approach avoids repeatedly scanning and skipping an increasing number of rows.
However, using only an ID is not always appropriate. Many production systems sort records by timestamps, priorities, or other business fields.
That introduces another important requirement.
3. Why Deterministic Ordering Matters
Consider this query:
SELECT *
FROM audit_logs
ORDER BY created_at ASC
LIMIT 50;
What happens when multiple records have the same timestamp?
For example:
ID | Created At |
|---|
201 | 10:30:00 |
202 | 10:30:00 |
203 | 10:30:00 |
204 | 10:31:00 |
If the cursor contains only created_at, the API cannot precisely identify where the previous page ended among records sharing the same timestamp.
This can lead to duplicate or missing records.
The solution is to introduce a unique tie-breaker.
Instead of sorting only by timestamp:
ORDER BY created_at ASC
Use:
ORDER BY created_at ASC, id ASC
Now every record has a deterministic position based on the combination of its timestamp and unique ID.
The cursor must contain both values.
For example:
{
"created_at": "2026-12-05T10:30:00+00:00",
"id": 203
}
The next query becomes:
SELECT *
FROM audit_logs
WHERE
created_at > '2026-12-05T10:30:00+00:00'
OR (
created_at = '2026-12-05T10:30:00+00:00'
AND id > 203
)
ORDER BY created_at ASC, id ASC
LIMIT 50;
This is a much more reliable pagination strategy.
The important lesson is simple:
A cursor must represent a complete and deterministic ordering position, not just an arbitrary field from the last record.
4. Implementing Keyset Pagination With FastAPI and SQLAlchemy
Let's implement a simplified endpoint for retrieving audit logs.
Assume we have a PostgreSQL table with the following model:
from sqlalchemy import Integer, String, DateTime
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from datetime import datetime
class Base(DeclarativeBase):
pass
class AuditLog(Base):
__tablename__ = "audit_logs"
id: Mapped[int] = mapped_column(
Integer,
primary_key=True
)
action: Mapped[str] = mapped_column(
String,
nullable=False
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
index=True
)
We will use both created_at and id to construct our cursor.
The pagination function
from sqlalchemy import select, and_, or_
async def get_audit_logs(
session,
cursor_created_at=None,
cursor_id=None,
limit=50
):
query = (
select(AuditLog)
.order_by(
AuditLog.created_at.asc(),
AuditLog.id.asc()
)
)
if cursor_created_at is not None and cursor_id is not None:
query = query.where(
or_(
AuditLog.created_at > cursor_created_at,
and_(
AuditLog.created_at == cursor_created_at,
AuditLog.id > cursor_id
)
)
)
result = await session.execute(
query.limit(limit + 1)
)
rows = result.scalars().all()
has_next = len(rows) > limit
items = rows[:limit]
next_cursor = None
if has_next and items:
last_item = items[-1]
next_cursor = {
"created_at": last_item.created_at.isoformat(),
"id": last_item.id
}
return {
"items": items,
"has_next": has_next,
"next_cursor": next_cursor
}
Why are we fetching limit + 1 records?
If the requested page size is 50, we fetch 51 records.
If 51 records are returned, another page exists.
If 50 or fewer are returned, there is no next page.
We return only the first 50 records and generate the next cursor from the last record actually returned.
This avoids running an additional COUNT(*) query just to determine whether another page exists.
Exposing it through FastAPI
A simplified endpoint could look like this:
from fastapi import FastAPI, Depends, Query
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
app = FastAPI()
@app.get("/audit-logs")
async def list_audit_logs(
cursor_created_at: datetime | None = None,
cursor_id: int | None = None,
limit: int = Query(default=50, ge=1, le=100),
session: AsyncSession = Depends(get_session)
):
if (cursor_created_at is None) != (cursor_id is None):
from fastapi import HTTPException
raise HTTPException(
status_code=400,
detail="Both cursor fields must be provided together."
)
return await get_audit_logs(
session=session,
cursor_created_at=cursor_created_at,
cursor_id=cursor_id,
limit=limit
)
For a production API, I would not expose the two cursor fields independently.
Instead, I would encode them into a single opaque cursor token and validate it on every request.
For example, the client receives:
{
"items": [],
"next_cursor": "eyJjcmVhdGVkX2F0Ijoi..."
}
The server decodes the token and extracts the timestamp and ID.
If the cursor contains sensitive or security-relevant information, sign it using an HMAC so clients cannot modify its contents without detection.
An encoded cursor is not automatically secure. Base64 encoding alone does not prevent tampering.
5. What Cursor Pagination Does Not Guarantee
This is where many implementations make an incorrect assumption.
Switching from OFFSET to keyset pagination does not automatically make the entire result set a consistent snapshot.
It improves traversal behavior, but there are still edge cases.
A. New records inserted before the cursor
If a new record is inserted with a sort key earlier than the current cursor, it will not appear in subsequent pages.
That is generally desirable when traversing forward, but it means the user is not necessarily seeing every record that exists by the time the traversal finishes.
B. Records deleted during pagination
If a record is deleted before the client reaches it, the next page cannot return it.
Keyset pagination does not preserve deleted records.
C. Sort fields modified during pagination
Suppose a record initially has a timestamp later than the current cursor.
Before the client reaches it, another process updates its timestamp to a value earlier than the cursor.
The record may now be skipped.
If its sort key moves forward, it may be encountered again depending on the traversal.
For this reason, cursor pagination works best with immutable ordering fields.
For audit logs, an immutable creation timestamp and stable unique ID are usually appropriate.
D. A true point-in-time export
Consider a different requirement:
A user clicks Export and expects a file containing exactly the records that existed when the export started.
Keyset pagination alone does not provide this guarantee.
For that requirement, consider:
Running the export within an appropriate database snapshot transaction.
Using a materialized export dataset.
Capturing a reliable high-water mark when the data model supports it.
Generating the export asynchronously and storing its result.
The right approach depends on database behavior, transaction duration, write volume, and how strict the export consistency requirement is.
A long-running database snapshot can have operational costs, so it should not be introduced casually.
Stable traversal and snapshot consistency are two different requirements.
Understanding that difference is more important than simply choosing one pagination technique over another.
6. When Should You Use Offset or Keyset Pagination?
Neither approach is universally better.
The decision depends on the product and the data.
Requirement | Recommended approach |
|---|
Small administrative tables | Offset pagination |
Simple page-number navigation | Offset pagination |
Large audit log tables | Keyset pagination |
High-volume event history | Keyset pagination |
Infinite scrolling | Keyset pagination |
Stable forward traversal | Keyset pagination with immutable sort keys |
Point-in-time exports | Snapshot or materialized export strategy |
Offset pagination is perfectly reasonable for small datasets where direct page-number navigation is important.
Keyset pagination is generally a stronger choice when users navigate through large datasets sequentially.
But if the business requirement is to export a consistent point-in-time dataset, neither pagination method alone solves the entire problem.
Final Thoughts
Pagination is easy to implement when the database is treated as static.
Production systems are not static.
Records are inserted, deleted, updated, and processed concurrently. A pagination strategy that works perfectly during development can produce confusing results when real workloads arrive.
The engineering decision should not simply be:
"Should I use OFFSET or a cursor?"
It should be:
"What consistency behavior does this API need, and what guarantees does my pagination strategy actually provide?"
For small tables, offset pagination may be enough.
For large datasets and sequential traversal, keyset pagination is often a better fit.
For reliable exports, you may need a snapshot-based design.
Good API design is not just about returning the next 50 records. It is about being clear about which 50 records the client is actually receiving.
What pagination strategy do you use in your production APIs: OFFSET, keyset pagination, or a snapshot-based export workflow?
#Python #FastAPI #BackendEngineering #PostgreSQL #SQLAlchemy #APIDesign #SoftwareArchitecture #DatabasePerformance #SystemDesign #CSharpCorner
Join the conversation! Your thoughts help the community grow.