ZCore LogoZCore
How to

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: CursorPagination automatically inspects your model's primary key (supporting uuid.UUID, int, and strings) and supports per-request cursor_field and order (asc or desc).
  • 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 (via sqlalchemy.sql.sqltypes.Date and date fragment extraction, preventing PostgreSQL asyncpg type mismatch errors), DateTime, UUID, int, float, and serializes Decimal types cleanly into the Base64 token.
  • Composite Key Fail-Fast Guard: On models with composite primary keys, accessing the default cursor_field raises an explicit AttributeError unless a specific coordinate field is configured on the repository or passed via search sort criteria.

On this page