All notes

Keyset Pagination Depends on a Stable Total Order

Bind cursor boundaries to ordering, filters and the consistency promise made to readers.

English edition, edited for length. Read the complete Chinese original.

On the first page of the article list, OFFSET 0 is used. On the second page, OFFSET 20 is used. A new article is added between the two requests, and the last article on the first page is moved to the second page, resulting in the user seeing duplicate content. Even without concurrent writes, the database may need to scan and discard a large number of preceding results when the offset becomes very large.

Using cursor-based pagination, the problem is rephrased as “Give me the record after the last one.” However, this only has a clear meaning if the records are sorted in a stable, unique order. Encoding timestamps into strings does not automatically ensure correct pagination.

Even with the same time, the order must still be unique.

Assume the articles are arranged in reverse order of publication date. Since a batch of publications may have the same publication date, a second unique key, such as the article identifier, is needed. The sorting for the first page and the “next page” condition must use the same composite order:

SELECT id, published_at, title
FROM posts
WHERE status = 'published'
  AND (published_at, id) < ($1, $2)
ORDER BY published_at DESC, id DESC
LIMIT 21;

Here, we read twenty items, using the first twenty as the result. The last item is used to determine if there are more pages. The cursor saves the time and identifier of the last item that was retrieved, rather than probing the location of that specific item. Otherwise, the user might miss the item when making the next request.

The database should have indexes that correspond to the filtering and sorting operations. It’s not sufficient to assume a query is cheap just because it contains “LIMIT”. Instead, you should examine the actual execution plan and the number of rows scanned. Multiple filtering dimensions can lead to changes in index selection. Categories and full-table lists may not be suitable for sharing a single index.

Composite Comparison Example:

Assume that both the publication time and identifier fields are non-null and use the same reverse order. If the fields allow null values, it is necessary to explicitly define the null value sorting and the next page predicate, and cannot rely on the default “<” comparison to cover this. Mixing ascending and descending order cannot directly reuse the same comparison tuple. The query protocol should include the sorting direction and null value strategy, as well as testing the boundaries of the first and last records, rather than just relying on the most common records.

The unique identifier provides a stable, secondary ordering, but the type of identifier itself must have consistent comparison rules. String sorting is affected by the database’s sorting rules, and clients should not attempt to generate boundaries after comparing. The cursor preserves the actual database sorting values, and the server reads them according to the same type. Time precision should not be lost during encoding, otherwise records with different milliseconds or microseconds will be compressed into the same boundary, potentially leading to omissions.

Set a maximum page size limit. Read an additional line solely for determining the next cursor, but do not use it as the next cursor. If the result is less than one page, there should be no “next page” option, and the empty page should also have a clear status. When switching between large sizes, whether the cursor can be carried over should be determined based on the boundary semantics, but requires documentation. Changing the size does not necessarily change the sorting, but it may affect the undo experience. Clients should not treat the internal cursor structure as editable page numbers.

Cursor Binding Query Semantics

On the first page, users filter the database by tags. However, on the second page, they switch to the “Design” tab and still have the old cursor. If the server processes all requests and returns results starting from the “Design” list, users might mistakenly believe that there are no earlier articles.

The cursor should include or bind to sorting versions, filtering condition fingerprints, and boundary values. If the request parameters are inconsistent with the cursor, it should explicitly reject them and require the user to start from the first page. The cursor can be encoded as an opaque token, but “opaque” simply means that the client should not rely on the internal structure, and it does not equal security.

If the cursor contains tenant scope or internal identifiers, it should be validated for completeness, and signed if necessary. Access permissions should still be determined independently by the server-side. A signed cursor cannot be used as an authorization credential. When upgrading the cursor format, retain the version field to avoid causing confusion for users who are still browsing the list after a single deployment.

Base64 encoding is not encryption, and readers can decode the internal fields. If the fields contain tenant information, sensitive identifiers, or filtering information, they should be signed or encrypted as needed. Signing protects integrity without hiding the content. The server validates the length, format, version, and type, to avoid large tokens causing parsing costs. If expired or unsupported versions are returned, a recoverable error is returned, allowing users to start from the beginning instead of throwing an internal stack error.

The “fingerprint” of the cursor binding filter conditions is generated from validated business parameters, with default values and semantic equivalence unified. Different tenants and permission scopes are still controlled by the current request’s authorization, and should not be solely relied upon on the signed field. If user permissions change, previously saved cursors may no longer be applicable, and visibility should be re-checked. The integrity proof comes from a token from the server, and does not mean that access rights are permanently valid.

Upgrading the format requires a compatible window. Old tabs may still use the cursor from the previous version, and it may be necessary to retain the parsing or explicitly request a refresh. An invalid cursor is different from a real one without a next page, and cannot be uniformly returned as an empty list, which could mislead users into thinking they have finished reading. The logging version and error category should not save all filtering conditions or sensitive user queries.

Deletion and Updates Modify Boundaries

The previous page’s last row has been deleted, but pagination with the cursor still works because the boundary values are already present in the token. Therefore, it doesn’t need to re-find the original row. Conversely, if the sorting field is variable, the content might move from after the cursor to before the cursor, and the user might never see it. Reversing the movement could also lead to repetition.

Therefore, the release timing should be stable after the initial release, and the modification timing is not necessarily suitable for long-term pagination sorting. If a product consistently sorts by the most recent update, it should acknowledge that this is a dynamic list, not a fixed snapshot. It can provide a “New content available, reload” prompt, but cannot guarantee that it will never miss any content during a single session.

When dealing with tasks that require exporting all invoices, a simple pagination cursor is insufficient. To achieve this, you need to implement features such as:

  • A fixed data snapshot
  • Record the export range
  • Use a clear deadline and immutable sequence numbers

Unlike interactive timelines and financial exports, which require consistency, different protocols should be chosen.

Viewing the article timeline allows users to easily see new content appear at the top, and then refresh to view it again. Exporting invoices requires knowing the complete range and ensuring that amounts are not duplicated or missing. This can be achieved using fixed snapshots or immutable business IDs combined with a cutoff boundary, but managing permissions and historical modifications still needs to be addressed. A cutoff time only restricts the addition of new content and does not automatically freeze existing records for updates or deletions. Strict snapshots rely on storage capacity and cannot be faked using cursor fields.

Maintaining long-running database transactions and snapshots can increase resource and maintenance costs. Asynchronous export can also generate fixed result files, clearly defining the input version and scope. The product requirements dictate the solution, rather than all tasks sharing an unlimited scrolling API. Export status, file integrity, and retry identity are different from pagination reads. The technical interface reuse should preserve these differences.

When the sorting field is modified, the interactive list can be improved by removing duplicates, displaying new content, and reloading, but it cannot guarantee a strict single pass. Removing duplicates prevents the display of duplicate items and does not fill in items that have been moved to the front. The documentation accurately describes the dynamic behavior, allowing users to know when to refresh. For tasks that cannot tolerate omissions, choose a stronger consistency boundary.

Jumping to a specific page is not a free feature.

Offset pagination makes it easy to express page 10, while cursor pagination requires moving the cursor along the boundary step by step. If the product requires random page jumps, you can retain the offset scheme and limit the depth, pre-establish anchor points, or change the interaction to time-based jumping.

Don’t store all cursor caches to achieve pagination, then claim that the system is both simple and allows for infinite page jumps. Cache invalidation, filtering combinations, and sorting changes will all become new state management costs. Instead, first confirm why the user needs to jump to the tenth page: to find a specific date, return to a previous reading position, or export data? These goals can often be met more effectively with clearer tools.

The previous page also needs to be designed. You can reverse the comparison and sorting, and then reverse the results; or, the client can save a chain of cursors for the pages that have been accessed. Regardless of which method is used, it is important to test both the starting and ending points, rather than simply demonstrating that the second page can return.

When a user navigates away from the list and returns, what they truly need is the content and scroll position they previously saw. The client can save the valid cursor and loaded records, but when restoring, it should check the current filters and permissions. Old records may have been deleted. Page numbers are not the only solution; jumping to a specific date, using bookmarks, or explicitly using “continue from here” are more direct options. The choice should be based on the task, not on forcing a random access simulation to replicate pagination controls.

Using the browser’s “back” button preserves the current page state, while re-requesting follows the dynamic list rules. Avoid automatically scrolling to the top each time the user returns, and avoid promising that data stored on the client will always remain valid. If recovery fails, the page will reload from the beginning, and an infinite loop will not be created. Separate handling of interaction state and data correctness allows for improved user experience while maintaining a simple backend protocol.

Observing user task success and database workload, while page switching became faster, the location tracking remained incomplete and frequent. The technical acceptance check set, along with the experience acceptance check, continued to require reading and filtering resets. The two sets of evidence do not replace each other; stable sorting provides the foundation, and a clear recovery process is necessary to complete the user task.

Index and Filter Joint Validation Access Workload

When querying with sorting by status, tenant, and time, the index order, along with the actual filtering selectivity, affects efficiency. Creating separate indexes for publication time does not guarantee fast skipping of a large number of other tenant records. Using realistic, skewed data, test scanning row counts, sorting, and buffers for popular tenants, sparse filtering, and deep boundaries. The cursor algorithm reduces offset discarding, but does not guarantee that all queries have a constant cost.

If a single request returns a long body while the list only requires titles and links, reducing the number of fields and transmissions can be more effective than indexing adjustments. By reading only the additional item that doesn’t return a useless body, we avoid loading large fields. Page size limits protect both the database and the client, and the server does not accept unlimited limits. Performance and correctness protocols are defined together, preventing users from arbitrarily changing resource budgets.

Manually Calculating Boundaries and Recording Measurements for the Same Batch of Data

Prepare five records with the same publication time and sequentially increasing identifiers, returning two records per page in reverse order. The first request retrieves three records, returning only the first two, and the cursor is saved for the second record’s identifier. The second request continues to retrieve the next two records, strictly less than the composite boundary. Since the third record is not provided to the user, it cannot be used to generate the next boundary. This small sample does not require performance measurement, but it can directly reveal the implementation of skipping multiple records after retrieving one.

Re-apply the boundary row deletion, and subsequent queries will continue to use the saved values, without needing to first retrieve the row. By changing the publication time of an unread record to just before the boundary, dynamic traversal may miss some; by moving the read record to just after the boundary, it may be repeated. These clearly demonstrate the dynamic list semantics, where de-duplication reduces redundant displays but does not automatically recover missed items. Strict export requires a separate, fixed-range protocol, and cannot be achieved through the interface to mimic a snapshot.

Null values and mixed directions are also derived using small sets. If the time is in descending order and the identifier is in ascending order, the next page’s predicate needs to express the opposite identifier direction for the same time, and it is not possible to directly copy tuples with the same direction. Null value comparison does not automatically produce the expected order, so it is necessary to explicitly define the NULLS rule and construct samples located on both sides of the boundary. Since sorting, predicates, and index access have different responsibilities, correct sorting must be established first, and then the plan can be verified for efficiency.

Query Semantics Binding Includes Default Values and Permission Changes

On the first page, the user sees the data in its default state. On the second page, the same state is explicitly passed in. Whether to accept the old cursor depends on the equivalence of standard parameters, which can usually be normalized into a single object. The order of the tag sets also affects filtering, and should be unified according to business rules. The “filtering fingerprint” of the cursor comes from standard parameters, not from the original query text. This avoids conflicts caused by meaningless changes in parameter order. If the filtering criteria are truly different, the process should start from the beginning.

The signature token field has not been modified, but this does not guarantee that the user still has access. The tenant and resource scope are re-evaluated based on the current identity. Once user permissions are narrowed, the old cursor cannot access the historical range. If necessary, the visibility version can be used as a recovery limit, but the current authorization remains the standard. Base64 encoding only, without hiding content. The token avoids unnecessary private fields and large inputs. Errors in format, expiration, and lack of a next page are all indicated.

The logs only record the version and error category, not all query conditions or tokens. The key rotation must have a clear compatibility window, and whether old tokens continue to be accepted should be determined by the protocol and risk. The cursors in different environments should not cross into the production query range, and the use of tokens can include operations or environmental constraints. Query locations are not a universal capability; integrity, confidentiality, and authorization each have independent responsibilities.

Ensure Consistent Direction in Navigation

When returning to the previous page, you can reverse the boundaries and SQL sorting to retrieve a limited number of records, and then reverse the results back to the order the user sees. Additional probing of records still does not enter the display with the cursor, and the boundary conditions have separate testing. If the client saves the accessed cursor chain, it reduces the backend logic, but refreshing, permission changes, and filter resets can invalidate the chain. The choice between the two methods is based on the task, not to secretly save the infinite server state for the sake of page appearance.

Users often need to “back” to a specific reading position. Caching previously viewed pages and scroll state can improve the user experience. When restoring, it’s important to clarify that this is not a permanent snapshot; provide a mechanism to reload and avoid silently returning the user to the top. When the cursor fails, ensure a stable return to the starting point, without infinite repetition of the same request. Separate the experience state and data access protocol to ensure reliable restoration without expanding the database guarantee.

A deadline does not equal a data snapshot.

The export function only includes records created before a specific point in time, excluding those created afterward. It cannot freeze existing record amounts, status changes, or deletions. Strict billing exports require a clear and consistent source, such as a database snapshot or a fixed-result file, along with the record range and version. Maintaining long transactions across requests incurs resource costs. Asynchronous file generation and authorization lifecycles also need to be considered. Instead of simply adding a cutoff to the cursor and claiming a complete export, it’s more practical to choose a solution that you can actually afford.

The completion conditions for export include a set of records, the total amount, and file integrity. The client cannot retry and generate multiple results with different ranges while retaining the same task identity. When downloading, permission verification is still performed, and the fixed result file should not be publicly accessible due to the address containing random values. The interactive timeline and financial export can share some query tools, but the definition of success and responsibility recovery are different, and interface reuse cannot eliminate the distinction.

Sparse Filtering Requires Planned Evidence

The time boundary is very deep, and label matching is infrequent. The database may need to scan a large number of non-matching records to find a single page. Cursor reduction and discarding offsets do not automatically enforce any constant cost. Prepare for hot tenants, sparse states, and samples with no results, observing scanning, sorting, and buffering, and designing indexes based on real query families. The LIMIT clause only restricts the number of results returned, and does not guarantee a small workload.

The list projection only extracts necessary titles, dates, and addresses, and does not download the full text on each page. The page size limit protects both the database and the client. The client can set any limit without affecting the budget. After optimization, the complete sorted set and boundaries are verified, and performance improvements cannot be achieved at the expense of omissions. If there is no real database environment, the report is a pending task plan, not a fabricated count of already verified scans.

Secondary keys in strings should also be re-validated during migration sorting. Changes in database versions or sorting configurations may cause the boundary values in historical tokens to no longer correspond to the old order. Clients should not be allowed to independently correct the sorting. It is possible to reject old tokens based on the sorting policy version, or to provide a compatibility window. The test should include case sensitivity and non-ASCII identifiers, and clearly adopt the actual comparison rules. A stable primary key reduces this complexity, but the choice of type still depends on the business and storage requirements. No single ID should be declared as the universal answer for all systems.

Completing Acceptance Using Cross-Version Cursors

Preserve legacy token formats, with explicit acceptance or controlled rejection after parsing, and test that the client can restart. Expect different outcomes for signature errors, large tokens, filtering changes, and permission restrictions, all while ensuring that the internal structure remains hidden. Stable sorting, location contracts, and a recovery entry must be implemented together to ensure that “support cursor-based pagination” provides a reader-understandable guarantee.

Testing for Redundancy and Omissions

Prepare a set of records with completely identical timestamps, and continuously page through them to check if the set of identifiers is complete and unique. Insert new records and delete boundary records between pages, and then verify that the actions comply with the defined rules. When switching filter conditions, the old cursor should be rejected. Format errors and expired cursors should return recoverable errors.

Performance validation requires a thorough comparison of the execution plans, latencies, and scan counts for both deep and shallow paging, rather than simply looking at the response time under 100 test data points. For users, the primary concern is correctness, followed by query optimization.

Include a large number of records with the same time, empty results, the last page, deletion boundaries, filtering changes, and cursor version upgrades. Test set integrity and user-recoverable errors, and verify the sorting rules of a real database. Use predefined expectations for dynamic updates, and do not treat the current return result as the standard answer. Finally, separately report the guarantees for the interactive list and export tasks, to avoid the phrase “support cursor” masking completely different consistency requirements.

If data is read from a copy, and the differences in visible data between the preceding and subsequent requests are checked, the first page might hit a newer copy, while the second page hits a more outdated copy, potentially returning only a few pages. The client interprets this result as a permanent end and no longer queries subsequent records. The interactive list can accept this boundary, but the documentation should explain the refresh behavior. Strict export cannot rely solely on the copy cursor to guarantee the completeness of the collection. Use controlled copies or simulate a fixed collection to verify the endpoint handling, without fabricating the actual replication delay. The combination of routing and sorting protocols determines the actual visibility.

References