Use this prompt during the API design review phase, before a single line of implementation code is written. The ideal user is an API designer, backend engineer, or technical lead who has already defined the resource model and understands the collection's access patterns, typical data volumes, and expected consumer workflows. The prompt requires a concrete resource description and collection characteristics as input—it cannot design a pagination contract from a vague idea. The output is a complete, reviewable pagination contract that includes request parameters, response envelope structure, edge-case handling rules, and a documented rationale for the chosen strategy. This contract becomes the source of truth for implementation, client SDK generation, and API documentation.
Prompt
Pagination Contract Design Prompt

When to Use This Prompt
Identify the right moment in the API design lifecycle to apply the Pagination Contract Design Prompt and understand when it adds risk instead of reducing it.
Do not use this prompt when the resource model is still in flux, when you lack clarity on whether the collection is append-only or supports arbitrary insertion and deletion, or when the underlying data store imposes hard constraints that the API layer cannot abstract (for example, a legacy database that only supports offset-based queries with no cursor primitive). The prompt is also inappropriate for streaming or real-time data feeds where pagination is not the right access pattern—WebSockets, Server-Sent Events, or gRPC streaming require fundamentally different contracts. If you are retrofitting pagination onto an existing API with live consumers, use the Breaking Change Detection Prompt first to assess migration impact before designing the new contract.
Before running this prompt, gather the resource schema, expected collection size range, mutation patterns (append-only, mutable, or sorted), consumer latency requirements, and any consistency guarantees the system must provide. The prompt works best when you can describe the collection's behavior concretely: 'A time-ordered, append-only event log with millions of records per tenant, consumers polling for new events every 30 seconds' is actionable; 'a list of things' is not. After receiving the prompt output, review the recommended strategy against your operational constraints—cursor-based pagination requires a stable sort key, and page-based pagination can produce duplicate or missing results if the underlying data mutates between requests. If the prompt recommends a strategy your infrastructure cannot support, iterate with additional constraints rather than accepting the output as final. The next step is to validate the generated contract against the API Contract Consistency Review Prompt to catch parameter naming drift, envelope inconsistencies, and error format misalignment before the contract reaches implementation.
Use Case Fit
Where the Pagination Contract Design Prompt works well and where it introduces risk. Use these cards to decide if this prompt fits your current API design task.
Good Fit: Greenfield Resource Collections
Use when: designing pagination for a new REST or GraphQL resource collection with known access patterns. The prompt produces a complete contract with request parameters, response envelope, and edge-case rules. Guardrail: provide the expected query patterns, data volatility, and client types so the recommendation matches real usage.
Bad Fit: Existing Production APIs with Consumers
Avoid when: you already have paginated endpoints in production with live consumers. Changing pagination strategy is a breaking change. Guardrail: use the Breaking Change Detection Prompt instead to assess impact, and treat this prompt as input for a vNext design, not a retrofit.
Required Inputs: Resource Shape and Access Patterns
Risk: the prompt produces a generic recommendation without understanding the data model. Guardrail: always provide the resource schema, expected collection size, sort fields, filter combinations, and whether clients need stable cursors across inserts and deletes. Missing inputs produce plausible but wrong contracts.
Operational Risk: Cursor Implementation Complexity
Risk: cursor-based pagination is often recommended but requires careful implementation of opaque, stable cursors that survive data mutations. Guardrail: if your team cannot guarantee cursor stability or encode state in the cursor, prefer offset-based pagination and document the consistency trade-off explicitly.
Operational Risk: Missing Edge-Case Handling
Risk: the prompt may produce a contract that looks complete but omits empty collections, deleted items mid-page, concurrent modifications, and max page size enforcement. Guardrail: run the output through the API Contract Consistency Review Prompt and add explicit edge-case test cases before implementation.
Team Readiness: Pagination Is a Product Decision
Risk: treating pagination as a pure technical choice ignores client SDK generation, documentation, and mobile data usage. Guardrail: involve the API product owner and client SDK teams in the review. The prompt output is a starting point for a decision, not the final contract.
Copy-Ready Prompt Template
Paste this prompt into your AI workspace. Replace square-bracket placeholders with your resource details.
This prompt template is designed to produce a complete pagination contract recommendation for a specific API resource. It forces the model to reason about data volatility, client requirements, and operational constraints before selecting between offset, cursor, or page-based pagination. The output includes a full request/response contract, edge-case handling rules, and implementation guidance. Use this when you need a concrete, reviewable pagination design rather than a general discussion of pagination patterns.
codeYou are an API design architect specializing in pagination contracts for REST and GraphQL APIs. Your task is to recommend and fully specify a pagination strategy for a specific resource collection. ## INPUT - Resource Description: [RESOURCE_DESCRIPTION] - Data Characteristics: [DATA_CHARACTERISTICS] - Client Requirements: [CLIENT_REQUIREMENTS] - Existing API Standards: [EXISTING_STANDARDS] - Operational Constraints: [OPERATIONAL_CONSTRAINTS] ## OUTPUT_SCHEMA Return a JSON object with the following structure: { "recommendation": { "strategy": "cursor" | "offset" | "page", "rationale": "string explaining why this strategy fits the resource and constraints", "trade_offs": ["list of trade-offs accepted with this choice"] }, "request_contract": { "parameters": [ { "name": "string", "type": "string", "required": boolean, "description": "string", "example": "string" } ], "default_page_size": number, "max_page_size": number }, "response_envelope": { "data_field": "string", "pagination_metadata": { "fields": [ { "name": "string", "type": "string", "description": "string" } ] }, "example_response": {} }, "edge_case_rules": [ { "scenario": "string describing the edge case", "expected_behavior": "string describing the correct response", "status_code": number } ], "implementation_notes": ["list of implementation guidance for backend developers"], "client_usage_guidance": ["list of guidance for API consumers"] } ## CONSTRAINTS - Prefer cursor-based pagination when data is frequently inserted or deleted, or when real-time consistency matters. - Use offset pagination only when data is relatively static and clients need random-access page jumping. - Reserve page-based pagination for simple UIs with fixed page sizes and low data volatility. - Every edge case rule must specify the exact HTTP status code and response body behavior. - Include a Link header recommendation in implementation notes if using cursor or offset pagination. - If the resource can return zero items, specify the empty collection response explicitly. - Address what happens when a cursor becomes invalid between requests. ## RISK_LEVEL [RISK_LEVEL] If RISK_LEVEL is "high", flag any pagination design choices that could cause data loss, missed records, or infinite loops in consumers. Require explicit handling for concurrent modification scenarios.
To adapt this template, replace each square-bracket placeholder with concrete details about your resource. For [RESOURCE_DESCRIPTION], describe what the endpoint returns—such as "user-visible events ordered by creation time descending." For [DATA_CHARACTERISTICS], specify insertion patterns, deletion frequency, and whether ordering can change between requests. [CLIENT_REQUIREMENTS] should capture whether consumers need random access, infinite scroll, or export-all behavior. [EXISTING_STANDARDS] lets you reference your organization's API guidelines so the model aligns with internal conventions. Set [RISK_LEVEL] to "high" when pagination bugs could cause financial reconciliation errors, missed audit records, or data integrity issues—this triggers stricter edge-case analysis and explicit concurrency handling in the output.
After generating the contract, validate the output against your existing API style guide. Check that the recommended strategy doesn't conflict with your gateway's caching behavior or your monitoring system's assumptions about response structure. For high-risk resources, run the edge-case rules past a senior engineer before implementing—cursor invalidation and concurrent modification handling are the most common sources of pagination defects in production.
Prompt Variables
Inputs the Pagination Contract Design Prompt needs to produce a reliable, implementation-ready contract. Each placeholder must be resolved before the prompt is sent to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RESOURCE_DESCRIPTION] | Describes the API resource collection being paginated, including its data model, typical size, and mutation frequency. | A collection of user-generated orders that can be created, updated, and deleted. New orders are appended at the end. The collection can grow to millions of records. | Must be a non-empty string. Should include mutability characteristics (append-only, mutable, immutable) and approximate scale. Missing mutation info leads to incorrect cursor stability advice. |
[CONSUMER_USE_CASES] | Lists the primary ways clients will traverse the collection, including UI patterns, export jobs, and real-time sync requirements. |
| Must contain at least one concrete use case. Each use case should describe direction (forward/backward), sort order, and whether stable state during traversal is required. Vague use cases produce generic contracts. |
[CONSTRAINTS] | Specifies non-negotiable technical or business constraints that limit pagination design choices. | Must use JSON:API response envelope. Database is PostgreSQL 15. Max page size cannot exceed 100 records. Clients include mobile apps on unreliable networks. | List each constraint as a separate statement. Include protocol requirements, database limitations, network assumptions, and client capability restrictions. Missing constraints lead to unimplementable recommendations. |
[EXISTING_CONTRACT] | The current pagination approach if this is a migration or redesign. Use 'none' for greenfield designs. | Currently uses offset-based pagination with page and per_page query parameters. Response includes total_count and page_count meta fields. | If provided, must include request parameter names, response envelope structure, and any known problems (e.g., count queries timing out, duplicate rows on page drift). Use 'none' for new designs. Partial contracts cause incomplete migration guidance. |
[SORT_REQUIREMENTS] | Defines the default sort order, allowed sort fields, and whether stable tie-breaking is required. | Default sort: created_at DESC. Allowed sorts: created_at, updated_at, total_amount. Tie-breaker: id ASC. Multi-field sort must be supported. | Must specify default sort direction and at least one unique tie-breaker field. If multi-field sort is required, list all allowed combinations. Missing tie-breaker leads to duplicate or missing records across pages. |
[FILTER_REQUIREMENTS] | Describes which filter parameters the paginated endpoint must support and how they interact with pagination. | Required filters: status (enum), created_after (datetime), created_before (datetime). Filters must be stable for the duration of pagination. Changing filters resets pagination. | List each filter with its type and whether it must remain constant during traversal. Specify behavior when filters change mid-pagination. Missing filter stability rules cause inconsistent pagination semantics. |
[OUTPUT_SCHEMA] | The expected response envelope structure, including where pagination metadata, links, and records appear. | JSON:API envelope with data array, links object (self, next, prev), and meta object (page_size, has_more). Cursor value must be opaque string. No total_count required. | Define the envelope format explicitly. Specify which pagination fields are required vs optional. Include whether total_count, page_count, or has_more are needed. Ambiguous schema leads to inconsistent client parsing. |
Implementation Harness Notes
How to wire the pagination contract design prompt into an API design workflow with validation, retries, and review gates.
This prompt is designed to be called programmatically as part of an API design review pipeline, not as a one-off chat interaction. The harness should accept an OpenAPI fragment or a structured description of the resource collection as input, inject it into the [RESOURCE_SPEC] placeholder, and parse the model's JSON output for downstream consumption. Because pagination contract decisions affect every consumer of the API, the harness must treat the model's output as a draft recommendation, not a final decision. The output should be routed to a human reviewer or an architecture review board before the contract is published in the API specification.
Validation and retry logic is critical here. The harness must validate that the model's output contains all required fields: pagination_type, request_parameters (with at least page_size or limit), response_envelope (with items, next_cursor or equivalent), and edge_case_rules (covering empty results, first page, last page, and deleted items). If the output fails JSON schema validation, retry once with a repair prompt that includes the validation errors. If the retry also fails, log the failure and escalate to a human reviewer with the raw model output attached. Model choice matters: use a model with strong structured output capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent) and set response_format to json_object with the expected schema. Do not use smaller or faster models for this task—pagination contract errors are expensive to fix after implementation.
Logging and traceability should capture the input resource spec, the model's raw response, the validated output, and the reviewer's final decision. Store these artifacts alongside the API specification version so that future teams can understand why a particular pagination strategy was chosen. If the prompt is integrated into a CI/CD pipeline for API spec changes, gate the pipeline on human approval of the pagination contract before the spec change can merge. Avoid wiring this prompt directly into automated code generation without a review step—pagination design requires judgment about consumer use cases, data volatility, and infrastructure constraints that the model cannot fully assess from the spec alone.
Expected Output Contract
Fields, format, and validation rules for the generated pagination contract. Use this table to validate the model's output before accepting it into your API specification pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
pagination_strategy | enum: offset | cursor | page | Must match one of the three allowed values. Reject any other string. | |
request_parameters | object | Must contain at least one pagination parameter. Each parameter must have name, type, required, and description fields. | |
response_envelope | object | Must include a data array and a pagination metadata object. Metadata field names must match the chosen strategy. | |
edge_case_handling | array of objects | Each entry must have scenario, behavior, and rationale fields. Minimum 3 edge cases required. | |
cursor_definition | string or null | Required when pagination_strategy is cursor. Must describe encoding, opacity, and stability guarantees. Null otherwise. | |
total_count_availability | boolean | Must be true or false. If false, response_envelope.pagination must not include total_count field. | |
sort_stability_notes | string | Must describe sort behavior during pagination. Minimum 20 characters. Must mention tie-breaking if applicable. | |
backward_compatibility_notes | string | Must list any breaking changes from common patterns. Minimum 10 characters. Use 'none' only if truly additive. |
Common Failure Modes
Pagination contracts fail in predictable ways. These are the most common failure modes when an LLM designs a pagination contract, with concrete guardrails to catch them before they reach an API specification.
Cursor Leakage into Response Bodies
What to watch: The model embeds raw database keys, opaque internal pointers, or sequential IDs as cursors, exposing implementation details and creating tight coupling between the API and the storage layer. Guardrail: Add an explicit constraint requiring cursors to be base64-encoded opaque strings. Validate that no field names like row_id, offset_value, or mongo_oid appear in the response envelope.
Missing Edge-Case Handling for Empty Collections
What to watch: The contract omits behavior for empty result sets, returning null for pagination metadata, omitting next_cursor entirely, or returning a 200 with an undefined items field. Consumers break when they expect a consistent envelope. Guardrail: Require the prompt to specify a concrete example for the empty-collection case. Validate that items is always an array (even if empty) and that next_cursor is explicitly null when there are no more pages.
Inconsistent Pagination Parameter Naming Across Endpoints
What to watch: The model generates cursor for one endpoint, page_token for another, and after for a third within the same API surface. This inconsistency forces consumers to maintain divergent client logic. Guardrail: Add a style-guide constraint in the prompt that locks parameter names to a single convention. Validate the output by extracting all pagination parameter names and confirming exactly one pattern is used across all endpoints.
Offset-Based Pagination Without Stability Guarantees
What to watch: The model recommends offset pagination for collections with frequent insertions or deletions, producing duplicate or missing items across pages without documenting the consistency risk. Guardrail: Require the prompt to include a consistency_model field in the output. If offset pagination is recommended, the contract must explicitly state whether results are eventually consistent and warn about window-based duplication.
Total Count Included on Unbounded Collections
What to watch: The model adds a total_count field to the response envelope for cursor-based pagination over large or unbounded datasets, creating an expensive COUNT(*) query on every request. Guardrail: Add a constraint that total_count must only be included when the prompt explicitly requests it and the resource collection is bounded. Validate that cursor-paginated responses omit total_count unless an opt-in parameter like include_total=true is defined.
Sort Order Dependency Not Documented in Cursor Semantics
What to watch: The model defines a cursor but fails to specify the sort criteria that the cursor depends on, making cursor stability invisible to consumers. A change in default sort order silently breaks pagination continuity. Guardrail: Require the contract to include an explicit cursor_sort_fields array listing the fields and their sort direction. Validate that every cursor-paginated endpoint documents the exact sort criteria in the response metadata or API description.
Evaluation Rubric
Use this rubric to test the quality of the generated pagination contract before accepting it. Each criterion targets a specific failure mode common in pagination design. Run these checks programmatically or manually against the model's output.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Pagination method justification | Output explicitly states the chosen method (offset, cursor, or page) and provides at least one concrete reason tied to the resource characteristics from [RESOURCE_DESCRIPTION] | Method is stated without justification, or justification is generic (e.g., 'it is best practice') without linking to resource properties | LLM-as-judge check: Does the justification mention a specific property from the input resource description (e.g., 'frequently inserted items' for cursor-based)? |
Request parameter completeness | All parameters required for the chosen pagination method are defined: page_size/limit, page_token/cursor/offset, and any sort or filter parameters that interact with pagination | Missing a core parameter for the chosen method (e.g., cursor-based pagination defined without a cursor parameter) | Schema validation: Parse the output contract and verify that the request object contains the minimum required fields for the stated pagination method |
Response envelope structure | Response body includes a data/items array, pagination metadata object, and a self link. Metadata includes at least next_cursor or next_page_token for cursor-based, or total_count and page_count for offset-based | Pagination metadata is missing, or the envelope mixes pagination fields at the top level instead of nesting them under a metadata key | JSON Schema check: Validate the response envelope against a schema that requires a top-level 'data' array and a 'pagination' object with method-appropriate fields |
Edge case: empty collection | Contract specifies that an empty collection returns a 200 with an empty items array and appropriate pagination metadata (e.g., next_cursor: null, total_count: 0) | Empty collection handling is not mentioned, or the contract specifies a 404 for empty results | Test case injection: Add 'Describe behavior when the collection is empty' to the prompt constraints and verify the output addresses it |
Edge case: last page detection | Contract defines how the client knows it has reached the last page: next_cursor is null, next is omitted, or a has_more boolean is false | No mechanism for detecting the last page is defined, forcing clients to make an extra failing request | Assertion check: Search the output for a field or rule that signals end-of-collection. Fail if no such signal exists |
Stability guarantee for cursor-based pagination | If cursor-based, the contract specifies that cursors are opaque, stable for at least the session duration, and not to be constructed by clients | Cursor is described as an offset or timestamp that clients could manipulate, or cursor stability is not addressed | Pattern match: If pagination method is cursor-based, verify the output contains the string 'opaque' or a statement that clients must not construct cursors |
Parameter naming consistency | Parameter names follow a single convention (snake_case or camelCase) throughout the request and response. No mixing of 'pageSize' and 'page_size' in the same contract | Mixed naming conventions appear in the same contract | Lint check: Extract all field names from the output, convert to lowercase, and verify that only one separator style (underscore or camelCase) is present |
Error response for invalid pagination parameters | Contract defines error responses for invalid cursors, out-of-range offsets, and excessive page sizes, with appropriate HTTP status codes (400, 404, 416) | Invalid pagination inputs are not addressed, or the contract suggests a 500 for client errors | Coverage check: Verify that at least two error scenarios for invalid pagination input are described with distinct status codes |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single resource collection and lighter validation. Replace [OUTPUT_SCHEMA] with a free-text description of the desired contract shape instead of a strict JSON schema. Skip the eval harness and run the prompt interactively against 2-3 resource types to test the recommendation logic.
Watch for
- The model defaulting to offset pagination without analyzing cursor suitability
- Missing edge-case rules (empty collections, deleted items during pagination)
- Overly generic response envelopes that don't match your existing API conventions

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us