How to implement Cursor Pagination
High-performance keyset pagination for large datasets and real-time feeds without offset drift.
For high-throughput datasets or infinite-scroll feeds, offset pagination causes query slowdowns and duplicate items (offset drift). ZCore provides CursorPagination based on encoded keysets.
1. Enable Cursor Pagination on the Router
Open your router file and set pagination_class = CursorPagination. This automatically changes the collection endpoint query signature to accept cursor, size, and runtime keyset parameters:
# routers.py
from zcore import BaseRouter
from zcore.db.pagination import CursorPagination
from .models import Task
from .schemas import TaskCreate, TaskUpdate, TaskResponse
from .services import TaskService
class TaskRouter(BaseRouter[TaskCreate, TaskUpdate]):
model = Task
create_schema = TaskCreate
update_schema = TaskUpdate
schema_out = TaskResponse
service = TaskService
# Switch from default Page-Number to Keyset Cursor pagination
pagination_class = CursorPagination
prefix = "/tasks"
tags = ["Tasks"]
router_instance = TaskRouter()2. Client Requests
The client can fetch the first page by requesting the desired size, then passing the returned cursor for subsequent pages. Runtime overrides for sort field and direction are also supported:
# Initial request (First page)
curl -X GET "http://localhost:8000/tasks/?size=20"
# Subsequent request using the received next_cursor
curl -X GET "http://localhost:8000/tasks/?size=20&cursor=eyJ2YWx1ZSI6ICI...=="
# Optional: Runtime order override (asc or desc)
curl -X GET "http://localhost:8000/tasks/?size=20&order=asc"When executed via POST /tasks/search, BaseRouter automatically synchronizes the primary sort column from SearchRequest.sort into the cursor engine.
3. Response Structure
The response is wrapped in ZCore's ResponseWrapper. The meta block contains the pagination state:
{
"success": true,
"message": "Success",
"data": [
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Complete documentation",
"is_completed": false
}
],
"meta": {
"next_cursor": "eyJ2YWx1ZSI6ICIyMDI2LTEwLTE4VDA4OjAwOjAwIiwgInBrIjogImExYjJjM2Q0Li4uIn0",
"has_more": true,
"size": 20
}
}Advanced Keyset Engine & Type Coercion:
- Dynamic PK & Column Inspection:
CursorPaginationautomatically inspects your model's primary key (supportinguuid.UUID,int, and strings) and supports per-requestcursor_fieldandorder(ascordesc). - Compound Boundary Evaluation: When sorting on non-PK columns, ZCore applies a two-tier keyset predicate to prevent record collisions across identical values:
DESC:(col < val) OR (col == val AND pk < last_pk)ASC:(col > val) OR (col == val AND pk > last_pk)
- Driver-Safe Type Coercion: Fully coerces ISO strings to SQLAlchemy
Date(viasqlalchemy.sql.sqltypes.Dateand date fragment extraction, preventing PostgreSQLasyncpgtype mismatch errors),DateTime,UUID,int,float, and serializesDecimaltypes cleanly into the Base64 token. - Composite Key Fail-Fast Guard: On models with composite primary keys, accessing the default
cursor_fieldraises an explicitAttributeErrorunless a specific coordinate field is configured on the repository or passed via search sort criteria.
How to enforce multi-tenancy & soft deletion
Automatically isolate tenant data and filter soft-deleted records across all repository queries using SoftDeleteMixin and scope_query.
How to build complex search queries
Construct nested AND/OR/NOT filters, eager-load relations, use inverted/range operators, and execute secure dynamic searches.