A pagination bug can look like a customer overlooking a record. The first screen shows two events, a new event arrives, and the next screen repeats something the customer has already read. Another implementation fixes the duplicate but quietly skips every record that shares the boundary timestamp. Both can pass a happy-path test with a small, conveniently ordered fixture.

DeepSeek can help you examine these failures, turn product requirements into invariants, and challenge an implementation with specific counterexamples. The useful outcome is a pagination contract you can execute and inspect. A confident explanation from a model cannot establish whether a query returns every intended record, whether a token belongs to the current tenant, or whether a changing database still matches yesterday’s export promise.

This guide builds a small Python and SQLite lab for a descending event feed. It uses a unique compound ordering, a readable HMAC-signed continuation token, strict input checks and a one-row lookahead. You will see exactly which guarantees follow from those choices, which depend on immutable data, and which require a separate snapshot or export design. All examples are original teaching fixtures. The prompts are templates for your own review, and no DeepSeek response or live model test is presented as evidence.

The central distinction is between continuing after an ordering boundary and preserving a fixed collection. A keyset cursor answers the first question. It does not, by itself, answer the second. Keeping those responsibilities separate makes the code easier to test and the API easier to describe honestly.

1. Write the pagination contract before asking for code

Start with the interaction your product actually needs. An activity feed usually needs the next older group of events. An administrative table may require a jump to page twenty. A compliance export may need the exact records visible when an operation began. These are different products even when all three initially contain a “Next” button. The choice of pagination technique should follow the promised behavior, rather than whichever snippet a model generates first.

Our lab promises forward traversal of one tenant’s events of one kind, ordered by creation timestamp descending and then identifier descending. The timestamp is a nonnegative integer measured in microseconds for a real application, although the fixture uses tiny synthetic values for readability. The identifier is a unique positive integer. The API accepts a page size from one to one hundred and may return fewer records. It returns a continuation token only when that particular query sees an additional matching row.

For an unchanged dataset, a complete traversal must match the independent sorted collection exactly. Every matching identifier appears once, every nonmatching identifier stays out, and the concatenated pages follow the specified order. For changing data, the contract is narrower: the next query resumes strictly below the previous boundary. Existing ordering and membership fields must remain stable if you want the usual no-repeat reasoning to apply. Deletions can remove unseen records, and newly inserted records can fall on either side of the boundary.

Write these assumptions beside the contract. The authenticated server chooses the tenant; the client does not gain access by naming one. Creation time, identifier and the filter fields are immutable during an ordinary traversal. There is no exact total count in the response and no cross-request snapshot. Tokens expire after a short fixed traversal window. An expired token raises InvalidCursor in this helper. An API wrapper must turn that into a clear restart response rather than silently beginning a new collection in the middle of the user’s list.

A useful first DeepSeek task is to inspect this brief for contradictions. Ask it whether the requested page-number navigation fits a forward cursor, whether users can change the filter halfway through a traversal, and what “all records” means while writes continue. Resolve those questions with the product owner before implementation. The same discipline appears in our guide to turning requirements into traceable acceptance criteria: important promises should become observable tests.

2. Understand the failure that keyset pagination addresses

Offset pagination describes a position in the result currently being evaluated. With a page size of two, a request with an offset of two skips the first two matching rows and returns the following rows. This is easy to explain and can suit small, bounded collections or interfaces that genuinely need page numbers. It also means the position can change between requests when the underlying collection changes.

Consider a descending collection with identifiers 103, 102, 101, 104, 105 and 106. The identifiers themselves are not the primary sort key; this order comes from the timestamp and identifier pair. The first page contains 103 and 102. If a newer event 999 arrives before the second request, the new collection begins 999, 103, 102. Skipping two positions now returns 102 again. The client has received a duplicate even though each individual SQL query was valid.

A deletion can create the opposite problem. Starting from the original collection, suppose event 103 is deleted after the client reads the first page. The collection now begins 102, 101, 104. Skipping the first two rows moves past 101 even though the client has never received it. These examples do not prove that offset is always the wrong choice. They show that positional navigation and changing membership need an explicit consistency policy.

Keyset pagination describes a boundary in the ordering instead. The first page ends at the pair 900 and 102, so the next request asks for matching rows strictly below that pair. A newer arrival above the boundary does not move the boundary. Deleting a previously returned record also does not change the boundary’s values. The query can continue even if the record that originally supplied those values has been deleted, because the cursor carries the values rather than requiring a lookup of that record.

There is a performance distinction as well. SQLite’s documentation explains that large offsets involve finding and discarding the skipped rows. An appropriately indexed boundary query can avoid that growing prefix of discarded results. Actual latency still depends on the index, filters, row width, cache state and database workload. The lab demonstrates result correctness; it does not include a benchmark or claim a universal speedup. Measure your own representative queries before attaching a performance promise to the design.

3. Make the order total, consistent and deliberate

A creation timestamp alone is rarely a sufficient boundary. Three events in our fixture share the timestamp 900. If the first page ends after two of them and the next query asks only for timestamps below 900, the third event disappears from the traversal. Changing the predicate to include equal timestamps merely creates another problem: previously returned records can reappear. The cursor needs enough information to identify a precise place within the tie.

Our ordering is created_us descending followed by id descending. With a unique id, each record has a distinct ordering pair. The first page returns 103 and 102 at timestamp 900; the next page begins with 101 at that same timestamp, followed by 104 at timestamp 800. The next-page condition is a strict row-value comparison against the last returned pair. SQLite compares row values from left to right, so the identifier decides only when the timestamps tie.

Descending event order: first page contains timestamp 900 IDs 103 and 102; boundary 900,102; second page keeps tied ID 101 before timestamp 800 ID 104.
A compound boundary preserves the remaining record at a tied timestamp. The cursor points to the last returned row, not the lookahead row.

Keep the comparison and the ordering in agreement. In this all-descending example, the next older page uses a less-than comparison. If you change both columns to ascending order, the corresponding continuation comparison changes too. Mixed directions require more care: sorting one field descending and another ascending cannot be implemented by blindly reusing the same tuple comparison. Write the expanded boolean predicate, test ties in each field, and review how the target database applies collation and null ordering.

Nulls deserve a product decision instead of an accidental implementation. A null creation value can make an ordinary comparison unknown, which can exclude rows from the continuation query. Our teaching schema forbids nulls and requires the stored timestamp to have SQLite’s integer storage type. This last check matters because an INTEGER declaration alone does not make an ordinary SQLite table strictly typed. During independent review, a fractional stored timestamp exposed a cursor that the original schema could issue but could not later accept; the fixture constraint was tightened and the regression was tested.

For a production database, validate the actual stored representation rather than assuming an application type annotation controls it. Normalize time precision deliberately, avoid float conversions for large integer values, and preserve identifiers exactly in clients that have narrower integer precision. If you paginate on human names, make the collation part of the contract. If you paginate on a mutable relevance score, acknowledge that stable traversal is a different challenge. A unique secondary key resolves ties; it cannot freeze the primary key’s value.

4. Treat continuation tokens as bounded query state

A cursor can carry the last ordering pair directly, reference server-side state, or use an authenticated encrypted representation. The lab uses a small JSON payload authenticated with HMAC and encoded for convenient transport. This is intentionally readable: anyone with the token can decode the payload. The signature detects modification by a party without the signing key, provided the implementation and key handling remain sound. It does not provide confidentiality, and the example is not an implementation of Google AIP-158’s opacity requirement.

The payload contains a format version, a query-scope digest, the last timestamp and identifier pair, and an expiry time. The scope digest incorporates the tenant, event kind, query version and ordering. Reusing a token with another tenant or another kind is rejected. The digest reduces direct disclosure of those fields in the token, but it is not encryption; predictable inputs may be guessable. Do not put sensitive filter values in this format without reviewing the disclosure and choosing an appropriate alternative.

Query binding prevents accidental or malicious reinterpretation of a valid token under a different collection. It does not establish authorization. On every request, the server must resolve the caller’s current identity, derive the permitted tenant and apply the actual row access rules. If access changes while a cursor is still valid, the new request must respect the change. A token signed yesterday cannot preserve a permission that was revoked today.

The page size is deliberately not included in our query-scope digest. A caller may reduce or increase it within the allowed range while continuing from the same ordering boundary. That is a product choice, not a universal rule. Fields that change membership or ordering must be bound or rejected; fields that only change how much of the next slice is returned can sometimes vary safely. Write a test for each allowed and forbidden parameter change instead of relying on a vague rule that all parameters must always be identical.

Input limits are part of the format. This decoder rejects oversized tokens, malformed transport encoding, unexpected fields, unsupported versions, noninteger boundary values and expired tokens. It checks the signature before interpreting the JSON structure, then requires the canonical JSON and base64 representation used by the encoder. Every invalid token becomes a single public InvalidCursor error. Internal diagnostics can distinguish causes without exposing raw tokens or implementation details to users.

The now argument must come from the trusted server clock in whole seconds; it is separate from the microsecond values used to order events. The first page starts a fifteen-minute traversal window. Every continuation preserves the original expiry rather than extending it on each request. This makes the maximum token lifetime easier to reason about. A deployed service also needs a key-management and rotation policy, request-size limits before application parsing, rate limits, logging controls and tests for its actual transport layer. The public demonstration key in the download is educational data and must never be reused as a service secret.

Request flow: authorize the caller, validate cursor signature, query binding and expiry, read limit plus one rows with a parameterized query, and build a cursor from the last returned row. Tokens are readable and no cross-request snapshot is created.
Integrity and query-binding checks complement authorization. The live database can still change between requests.

5. Read the small implementation before expanding it

The complete offline lab is available in the accompanying archive. It uses only the Python standard library and creates an in-memory SQLite database. There is no network server, account setup or API credential. Running it prints three pages of identifiers: 103 and 102; 101 and 104; then 105 and 106. The fixture also contains an event owned by another tenant and an event with another kind, so ordinary traversal can demonstrate filtering rather than merely assuming it.

The function below is the page-reading portion of that module. Its helper functions, dataclasses, schema and fixture are included in the download. Read this as an excerpt with those dependencies, not as a standalone pasted file. Values are passed as SQL parameters. The table, column names and ordering are fixed by the application; accepting arbitrary client-supplied SQL identifiers would require a different, tightly allowlisted design.

def get_page(conn, *, tenant, kind, limit, key, now, cursor=None):
    """Read a page. `tenant` must come from trusted authorization context.

    Existing order/filter fields must stay immutable for no-repeat traversal.
    This function does not establish a snapshot across separate requests.
    `now` is a trusted server-clock timestamp in whole seconds.
    """
    if type(tenant) is not str or not 1 <= len(tenant) <= 100:
        raise ValueError("tenant must be 1..100 characters")
    if kind not in ("note", "alert") or type(kind) is not str:
        raise ValueError("unsupported kind")
    if not _int(limit, 1, MAX_LIMIT):
        raise ValueError("limit must be an integer from 1 to 100")
    if type(key) is not bytes or len(key) < 32:
        raise ValueError("key must contain at least 32 bytes")
    if not _int(now, 0, MAX_SQL_INT - TTL_SECONDS):
        raise ValueError("now must be an integer timestamp")
    scope = _scope(tenant, kind)
    expires = now + TTL_SECONDS
    sql = """SELECT id, created_us, title FROM events
             WHERE tenant = ? AND kind = ?"""
    params = [tenant, kind]
    if cursor is not None:
        after, expires = _decode(cursor, scope, now, key)
        sql += " AND (created_us, id) < (?, ?)"
        params.extend(after)
    sql += " ORDER BY created_us DESC, id DESC LIMIT ?"
    params.append(limit + 1)
    found = conn.execute(sql, params).fetchall()
    items = tuple(Event(*row) for row in found[:limit])
    next_cursor = None
    if len(found) > limit:
        last = items[-1]
        next_cursor = _encode(scope, (last.created_us, last.id), expires, key)
    return Page(items, next_cursor)

The lookahead requests one more row than the caller’s page size. If an extra row exists, the response returns the requested slice and creates a token from the last item in that slice. The extra row is only evidence that the current query found a continuation. Using it as the boundary would skip it on the next request because the continuation predicate is strict. This is a small off-by-one decision with a large effect on completeness.

An exactly full final page is still final when the lookahead finds nothing beyond it. An empty collection returns no items and no continuation token. A previously valid token can later produce an empty page if all older matching records have been deleted. The client should handle these outcomes without inventing another request from the last visible identifier. Treat the server’s continuation field as part of the response contract.

The result does not expose an exact total count or a page count. A separate count query would have its own cost and consistency semantics, particularly if it ran under a different snapshot. If the interface needs a count, decide whether it is exact, approximate, cached or merely the number already loaded, and label it accordingly. Avoid showing a precise-looking denominator that silently changes meaning as users navigate.

The fixture’s composite index starts with tenant and kind, followed by the two ordered fields. This matches the equality filters and the continuation order in the example. It is a reasonable index shape to investigate, not proof that an application’s actual workload is optimized. A wider projection, additional authorization predicates or a different filter can alter the plan. Our SQL analysis workflow explains why query results and plans need independent evidence.

6. Exercise changes between pages rather than hiding them

Begin with the static traversal because it gives a crisp correctness oracle. Sort all matching fixture records independently by the same declared pair and compare them with the concatenated pages. Then repeat for page sizes one, two, three and sizes larger than the collection. A test that checks only the number of returned records can miss duplicate and missing identifiers that cancel each other out. Compare the exact sequence and its uniqueness.

Next, insert a new event above the boundary after reading the first page. In this lab, continuing the old cursor will not include that newer event. Refreshing from the beginning can show it. This can be a sensible activity-feed behavior: a “new events available” affordance lets the user decide when to restart, while older-page navigation remains understandable. Describe that behavior explicitly instead of claiming the traversal contains every event that exists at the end.

A backdated insertion below the current boundary behaves differently. It can appear on a later page even though it did not exist when the first page was read. This is why a fixed upper timestamp or maximum id is not automatically a snapshot. A bound can exclude some later arrivals without preserving old row values, preventing deletions or excluding all backdated inserts. The exact guarantee depends on the data model and the fields used for the bound.

Delete the boundary record and continue again. Because the cursor contains the pair itself, the query still has a meaningful starting point. Delete an unseen older row and the future traversal will no longer include it. Both behaviors are expected under our live-collection contract. Neither demonstrates data corruption, and neither satisfies a promise to export the exact original membership.

Finally, change an existing ordering value in a disposable fixture. Moving a previously returned record below the current boundary can make it reappear. Moving an unseen record above the boundary can make it disappear from the remaining traversal. Changing a membership field can similarly move a record into or out of the result. These are useful negative demonstrations: the tests show why the immutability assumption matters, rather than pretending the algorithm enforces it.

If you need a consistent export, choose an actual consistency mechanism. Depending on the database and operational constraints, that might be one controlled snapshot, a materialized export job, a versioned dataset or a stored list of selected identifiers combined with an explicit value-version policy. In PostgreSQL, separate Read Committed queries can see different committed states. Holding a repeatable snapshot across a long workflow has resource and lifecycle consequences. Review those with the database owner instead of keeping a web transaction open indefinitely.

7. Build tests that can disagree with the implementation

Use an oracle that does not simply call the same cursor helper twice. For static fixtures, an ordinary Python list comprehension and sort can establish the expected full sequence independently of the SQL continuation predicate. Generate datasets with many timestamp ties and several tenants. Traverse them with different page sizes, then compare every identifier in order. Small randomized collections are especially useful because failures are easy to inspect and reduce.

Token tests should distinguish corruption from legitimate use. Modify a payload while preserving the old signature; the continuation must fail. Sign with another key; it must fail. Reuse a valid token with the wrong tenant or filter; it must fail. Continue at the exact expiry boundary; it must fail under this contract. Change only the allowed page size; it should continue correctly. These cases convert a security-sounding description into concrete behavior.

Malformed input is also part of the public surface. Exercise empty strings, oversized tokens, invalid characters, noncanonical base64, missing fields, wrong versions and invalid value types. Python’s boolean type deserves an explicit check because it behaves like an integer in many contexts; this lab requires actual integers for numeric inputs. At the database boundary, test that fractional values and nonnumeric text cannot be stored as timestamps in the teaching schema. That regression came from an observed review finding, not a hypothetical claim that the original code was perfect.

The archive includes the independent reviewer’s tests, the captured run log and a short explanation of what they cover. Forty independent test methods passed, including 4,800 seeded random traversals, 600 edge-dataset traversals and 1,000 malformed-token fuzz inputs. These are local deterministic and seeded checks of the shipped teaching implementation. They do not establish that a deployed endpoint is secure, that an application’s authorization policy is correct, or that DeepSeek will produce the same implementation. The downloadable evidence keeps those claims separate.

When a test fails, send DeepSeek the smallest relevant fixture, expected sequence, actual sequence and exact contract. Remove customer data and secrets first. Ask for a diagnosis tied to the observed result, followed by a minimal change and a regression test. Review the change before applying it. The approach complements property-based testing, where generated cases are valuable because they search beyond the examples an author happens to remember.

8. Use DeepSeek as a reviewer with a bounded brief

A broad request such as “make pagination production ready” leaves too many important choices unspecified. It invites an answer that mixes routing, database access, tokens and interface behavior without showing which promise each part supports. Give the model one job at a time. Start with the contract, then the query, then the token boundary, and finally the observable client behavior. Keep each answer small enough to challenge with a test.

The first prompt below asks for design review before code generation. It makes the important assumptions visible and requests counterexamples. You can use it in a chat interface without any API integration. Replace the fixture details with a sanitized description of your own schema. Do not paste real customer records, signing keys, session tokens or private connection strings merely to make the example feel realistic.

Review this pagination contract before proposing code.

Collection: authenticated tenant's events of one kind.
Order: created_us DESC, id DESC. Both fields are non-null integers;
id is unique. Existing sort and membership fields are immutable.
Page size: 1..100. Clients may change only page size mid-traversal.
Continuation: strict compound boundary from the last returned row.
Consistency: live collection, not a cross-request snapshot.
Token: readable JSON authenticated with HMAC; it is not encrypted.

Find contradictions and missing assumptions. Show a minimal fixture
for each failure you propose. Separate query correctness, token
integrity, authorization and snapshot guarantees. Do not call this
production-ready or claim tests were executed.

A good response should notice that the timestamp needs a unique tie-breaker, that mutable ordering fields can move records across the boundary, and that a signed token is not an authorization decision. It should also distinguish “more existed during this query” from “more will exist at the next request.” Those are review criteria you can check directly; they are not a transcript of an actual model answer.

Use a second pass to review code and tests together. Ask the model to identify an assumption that the tests never challenge, then require an executable counterexample. A plausible finding without a reproducible failure remains a hypothesis. Equally, a passing test written with the same mistaken logic as the implementation does not settle the question. Keep an independently derived expected sequence beside the generated test.

Review the attached sanitized pagination module and test suite.

1. State the guarantee each important test actually establishes.
2. Find one boundary the implementation or tests could mishandle.
3. Give the smallest executable reproducer with expected IDs and
   actual IDs; label anything not executed as a hypothesis.
4. Propose the smallest fix and an independent regression test.
5. Preserve the forward-only, live-collection contract.

Challenge ties, empty and final pages, changing page sizes, expired
and wrong-query tokens, tenant isolation, and writes between pages.
Never insert a real secret or treat a token as authorization.

If you automate this review through a model API, consult the current provider documentation for the model and output options you actually use. A JSON response mode can make output easier to parse, but it does not validate technical claims. Validate the response structure locally, treat any proposed patch as untrusted input and run tests in a disposable environment. This article deliberately avoids a model-name-specific SDK snippet so the pagination lesson does not depend on an unverified API configuration.

9. Give the client a response it can use safely

An API response can expose an items array and a nullable next_cursor field. The names are your choice; the semantics must be stable. The client retains the current filter and passes the continuation token only when moving forward in the same query. Changing the filter or sort order should reset traversal unless the API explicitly supports a different transition. Treating an old cursor as a universal bookmark across every view produces confusing failures.

Accessible navigation should communicate what happened after a page is loaded. Preserve a sensible focus position, avoid unexpectedly moving the reader to the top, and distinguish an empty first result from the end of an already loaded collection. Prevent duplicate simultaneous “load more” requests from appending the same page twice. The server’s correct pagination does not prevent a frontend from rendering duplicates when two responses race.

Backward navigation requires its own design. A client can keep previously loaded pages locally, or a server can implement a previous-boundary query with a reversed ordering and then restore display order. Neither approach follows automatically from a forward cursor. Decide whether returning to an earlier page should show cached content or current data, and test the consequences. Do not label a forward-only lab as a complete bidirectional navigation system.

Define errors with equal care. A malformed, wrong-query or expired cursor should produce a documented client error and a useful restart path. Database timeouts and internal faults should remain operational errors, rather than being disguised as an empty collection. Retry behavior must not append a successfully received page twice. If you publish an API contract, the contract-testing guide can help make response and error changes reviewable.

10. Review the evidence before shipping

Before release, inspect the actual query plan and test with data distributions that resemble your application. Include a tenant with many records, heavily tied timestamps, sparse filters and the largest permitted page size. Record both latency and the environment in which it was measured. Compare candidate indexes using a controlled workload. Avoid claiming that keyset pagination is constant-time in every situation simply because it avoids an offset term in this example.

Review the token lifecycle separately from query correctness. Keep signing keys out of source control and logs, document rotation, and decide what clients should do when an older token can no longer be verified. If tokens reveal values your product considers sensitive, choose a suitable confidential or server-side representation. Keep authorization checks current on every request. HMAC protects a message’s integrity under its key assumptions; it does not replace access control, operational limits or secure transport.

The final acceptance review should be understandable without reading a model conversation. Keep the contract, schema, implementation, independent oracle, test output and known limitations together. For this lab, the most important limitation is deliberate: it traverses a changing collection without freezing it. If your product requires fixed membership and fixed values, the next engineering task is a snapshot or export design, followed by tests of that design’s lifetime and failure behavior.

DeepSeek is most useful here when it helps turn an ambiguous “Next” button into a set of questions you can answer with evidence. Specify the order, bind the token to the query, validate every input, and test the changes that happen between requests. Then describe the result in terms of the guarantees you actually established. A small, explicit pagination contract is far easier to maintain than a larger implementation whose promises nobody wrote down.

Download the reproducible lab

Download the Python and SQLite pagination lab. Unzip it into a disposable folder, run python3 pagination_lab.py for the demonstration, and run python3 -m unittest -v for the included tests. The archive contains synthetic data only. Use the code as a reviewed teaching example and adapt it to your database, authorization layer and operational requirements before deployment.

Sources & References

  1. SQLite: Row Values
  2. SQLite: SELECT
  3. SQLite: Query Planning
  4. PostgreSQL 18: LIMIT and OFFSET
  5. PostgreSQL 18: Transaction Isolation
  6. SQLite: Isolation In SQLite
  7. Python 3: base64
  8. Python 3: hmac
  9. Python 3: json
  10. Python 3: sqlite3
  11. Google AIP-158: Pagination
  12. DeepSeek: JSON Output
  13. SQLite: Datatypes In SQLite
Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *