Question
Choosing Between Offset and Keyset Pagination in SQLAlchemy for Large Datasets
Neel Cedar
0 reputation · 10 Jun 2021, 08:07 UTC
17.6K views0
Context
A Python service using SQLAlchemy 2.0 must serve paginated results from a PostgreSQL table exceeding one million rows. The API currently uses limit() and offset(), but query latency grows linearly as clients request deeper pages.
Constraints
- Clients expect traditional page-number navigation (first, previous, next, last, jump to page N).
- The primary key is a UUID generated by the application, not a sequential integer.
- No officially maintained SQLAlchemy extension provides keyset pagination; third-party packages add dependency risk.
yield_per()streams rows efficiently but does not expose page boundaries or total counts.
Open Questions
- Can keyset pagination be adapted to a UUID primary key while preserving constant-time performance?
- Which strategy—offset with a reasonable page cap, hybrid offset/keyset, or a custom seek implementation—best balances API compatibility and query performance?
- Does SQLAlchemy 2.0’s
SelectAPI introduce any built-in primitives that simplify keyset pagination without external dependencies?