The user wants to build a "safe pagination and consistency policy across APIs."
This is a broad architectural request. I need to interpret "safe" and "consistency" in the context of distributed systems and API design.
Key Concepts:
-
Pagination:
- Why? Performance, bandwidth, usability.
- Types: Offset/Limit (traditional), Keyset/Cursor-based (efficient, consistent), Seek (similar to keyset).
- Issues: "Missing" rows, "Duplicate" rows when data changes during pagination (the "drifting window" problem).
-
Consistency:
- Strong vs. Eventual consistency.
- Read-after-write consistency.
- Consistency across pagination (seeing a stable snapshot of data).
-
Safety:
- Preventing injection attacks (SQL/NoSQL injection in sorting/filtering).
- Preventing DoS (limiting page size).
- Data integrity (not leaking soft-deleted data, handling PII).
-
Policy (Standardization):
- Defining headers, query parameters, and response structures so all APIs behave the same way.
Structuring the Guide:
I should organize this as a comprehensive design document or playbook.
- Phase 1: The Golden Rules (Principles): High-level goals (e.g., "No duplicates," "Stable order").
- Phase 2: Pagination Strategies (The "How"): Compare Offset vs. Cursor. Recommend Cursor for "safety" and "consistency."
- Phase 3: Consistency Mechanisms: How to handle data mutations while paginating (Snapshots, Cursors).
- Phase 4: API Contract Standardization: Define the exact request/response format (Headers vs. Body).
- Phase 5: Security & Safety guardrails: Rate limiting, max limits, input validation.
- Phase 6: Implementation Patterns: Code snippets or logic flows (conceptual).
Drafting the Content - Specifics:
- Offset vs. Cursor: Offset is easier but breaks consistency if rows are inserted/deleted. Cursor is safer.
- Constraint: Cursor requires a unique, sequential (or ordered) field.
- Consistency Policies:
- Flake IDs / ULIDs: Better than random UUIDs for sorting.
- Created_at: Good, but collisions happen. Use
(created_at, id) tuple.
- Stable Snapshots: For high consistency, maybe a cached result set (Redis) or a database transaction with repeatable read (expensive).
- Handling Deletions: If an item is deleted while the user is on page 1, does page 2 shift?
- Cursor approach: naturally handles shifts better than offset.
- Soft Deletes: Good for consistency, bad for performance.
- The Policy Format:
- Request:
cursor, limit, direction.
- Response:
data, next_cursor, prev_cursor, total_count (optional/expensive).
Refining the "Safe" aspect:
- Safe means predictable.
- Safe means no data leaks (enforcing scopes).
- Safe means performance protection (hard caps on limits).
Refining the "Consistency" aspect:
- What happens if I insert a row "A" after the user requests page 1?
- If ordered desc, "A" appears at top.
- If ordered asc, "A" appears at the end.
- Problem is usually row shifts. If I delete row 10, and I was using offset, row 11 becomes row 10. I miss it.
- Solution: Encrypted Cursors. Instead of exposing internal DB state (
id > 100), encrypt the pointer. This prevents tampering and hides implementation details.
Structure of the Response:
- Executive Summary: The trade-off triangle (Performance vs. Consistency vs. Simplicity).
- Policy 1: Strategy Selection (Offset vs. Cursor): When to use which. Recommendation: Cursor for anything dynamic/large.
- Policy 2: Consistency Patterns: Handling the "Moving Window."
- Policy 3: The API Contract: Standardizing query params and response bodies.
- Policy 4: Security & Safety: Encryption, limits, sorting.
- Policy 5: Sorting & Filtering: Complex pagination.
Self-Correction/Review during drafting:
- Initial thought: Suggest
START TRANSACTION for every pagination. Correction: No, that kills DB performance. Use Cursor-based pagination on immutable event logs or append-only tables where possible, or accept eventual consistency for most reads.
- Total Counts: Should the policy require
X-Total-Count? Correction: COUNT(*) is expensive on large datasets. The policy should discourage strict counts for infinite scroll and favor "HasMore" flags.
Final Polish:
Use bold headers, code blocks for JSON examples, and a checklist for the policy.
Let's assemble the detailed response based on these thoughts.
- Title: Safe Pagination & Consistency Policy.
- Section 1: Strategy: Cursor-based is king for consistency.
- Section 2: The "Moving Window" Problem: Explain it and how cursors fix it.
- Section 3: Sorting: Compound cursors (e.g., sort by date, then ID).
- Section 4: Security: Opaque cursors (Base64/Encryption).
- Section 5: Standards: Header/Body specs.
This looks like a solid plan. I will write the response following this structure.
Building a robust pagination and consistency policy requires balancing three competing factors: Performance, User Experience, and Data Integrity.
Below is a comprehensive blueprint for a safe pagination policy, moving from architectural choices to implementation standards.
1. The Core Strategy: Cursor vs. Offset
The first step in a "safe" policy is choosing the right pagination mechanism.
- Offset Pagination (
limit & offset / page & size):
- Use case: Small, static datasets (e.g., config tables, country lists).
- Risk: The Drifting Window Problem. If new items are inserted while a user moves from page 1 to 2, items from page 1 may shift to page 2, causing the user to see duplicates. If items are deleted, items may be skipped.
- Cursor/Keyset Pagination (
cursor & limit):
- Use case: Large, dynamic datasets (feeds, logs, infinite scroll).
- Benefit: It is immune to the drifting window. You ask for "10 rows after ID 105". Even if 100 rows are inserted before ID 105, your result set remains stable relative to your current position.
Policy Rule:
Default to Cursor-Based Pagination for any dataset that changes frequently or exceeds ~1,000 rows. Use Offset Pagination only when specific "Jump to Page X" UI requirements exist and data is static.
2. Consistency Patterns: Handling Mutable Data
How do you handle items that change while the user is paginating?
Scenario A: The "Live" Feed (Eventual Consistency)
If an item in the result set is modified (e.g., a status changes from "Pending" to "Done") after the user has passed that page, do not attempt to retroactively update the user's view.
- Policy: The pagination snapshot is defined by the cursor. The data within the page is fetched at execution time. This is acceptable for most APIs.
Scenario B: The "Stable" Snapshot (Strong Consistency)
For financial ledgers or audits, you cannot tolerate drifting.
- Pattern: Snapshot Pagination.
- Create a temporary view or a cached list of IDs associated with a
search_id or snapshot_token.
- Paginate against this static list of IDs.
- The API returns the live data for those IDs.
- Policy: This is expensive. Only implement this if the business logic strictly forbids data shifting during traversal.
3. API Contract Standards
To ensure safety and ease of use, standardize your request/response structure across all endpoints.
Request Parameters
Do not rely on inconsistent query params. Enforce a strict vocabulary:
limit (integer): Max items to return. (Default: 20, Max: 100).
cursor (string): An opaque token representing the position.
direction (enum): next or prev.
The "Opaque Cursor" Safety Rule
Never expose raw database IDs or timestamps in the cursor if possible.
- Unsafe:
cursor=created_at_2023-01-01T12:00:00Z
- Safe:
cursor=eyJpZCI6IDEyMywgInNvcnQiOiAiZGVzYyJ9 (Base64 encoded JSON)
Why? Encoding allows you to change the underlying pagination logic (e.g., switching from sorting by ID to sorting by Date) without breaking the client.
Standardized Response Envelope
Always wrap the data in a metadata object.
{
"data": [ ... ],
"pagination": {
"has_more": true,
"total_count": 15023, // Optional: Omit if performance is a concern
"next_cursor": "eyJ...==",
"prev_cursor": "eyJ...=="
}
}
4. The Safety Checklist (Implementation Rules)
1. Enforce Hard Limits
Prevent DoS attacks by enforcing a maximum limit server-side.
- Logic: If the client requests
limit=10000, the API overrides it to limit=100 (or your system's safe max) and ideally returns a warning header.
2. The "Unique Sort" Constraint
Pagination fails if the sort column has duplicate values (e.g., two users created at the exact same millisecond).
- Policy: All sorting MUST include a unique tie-breaker key (usually the Primary Key
id) as the final sort order.
- Bad:
ORDER BY created_at DESC
- Good:
ORDER BY created_at DESC, id DESC
3. Total Count Optimization
Counting total rows (SELECT COUNT(*) ...) is performant for small tables but freezes large datasets (Millions/Billions of rows).
- Policy:
- If
total_count is strictly required, cache the count in Redis or update it asynchronously.
- For strictly "Infinite Scroll" UIs, remove
total_count entirely and rely solely on has_more.
4. Handling Deleted Records (The 404 Gap)
If a user paginates, leaves the tab open, and the item at cursor is deleted:
- Policy: The API should look for the nearest valid neighbor or return the start of the list, rather than throwing a 404 error. The cursor should be resilient, not brittle.
5. Summary Policy Document
If you are writing documentation for your engineering team, use this summary:
The Pagination Playbook
- Mechanism: Use Keyset (Cursor) pagination by default.
- Sorting: Always append the Primary Key (ID) to the sort order to prevent duplicate entries on tie-breakers.
- Security: Obfuscate cursors (Base64) to hide implementation details.
- Performance:
- Cap
limit at 100.
- Avoid
COUNT(*) on large tables; use has_more boolean instead.
- Consistency: Accept that pages reflect the state of the database at the time of request. Do not implement locking reads for standard pagination.