API Design, Idempotency, And Cursor Pagination
Asked of: Software Engineer
Last updated
What's being tested
This topic tests whether you can design APIs that remain correct under retries, concurrency, partial failures, and changing datasets. You should be able to distinguish idempotency from merely “retrying safely,” and explain how an idempotency key is persisted, validated, expired, and associated with the original response. For pagination, the interviewer is probing whether you understand keyset pagination, stable ordering, opaque cursors, and consistency guarantees rather than defaulting to inefficient offsets. Meta cares because high-volume APIs experience duplicate requests, timeouts, concurrent mutations, and clients that evolve independently of servers.
Core knowledge
-
Idempotency means repeating the same logical request has the same externally visible effect as executing it once.
GET,PUT, andDELETEare conventionally idempotent;POSTis not inherently idempotent, so payment, creation, and mutation APIs commonly accept anIdempotency-Key. -
An idempotency record should contain the key, authenticated principal, request fingerprint, status (
in_progress,succeeded, orfailed), response status, response body, and expiration time. Scope keys by tenant or user so one client cannot collide with another. -
Make creation of the idempotency record atomic with a uniqueness constraint, such as
(user_id, idempotency_key). InPostgres,INSERT ... ON CONFLICTor a transactional conditional write prevents two workers from executing the same operation concurrently. -
A retry with the same key and identical parameters should return the stored result; the same key with different parameters should produce a client error such as
409 Conflictor400 Bad Request. Never silently reinterpret one key as multiple operations. -
in_progresshandling requires an explicit policy: wait briefly, return409or202, or safely take over after a lease expires. A process crash after committing the business mutation but before recording completion is the difficult case; use a transaction, an outbox, or a durable operation record. -
Idempotency does not guarantee exactly-once execution across every external system. If the API writes to a database and calls an external service, use an outbox pattern, downstream idempotency key, reconciliation job, or compensating action rather than relying on an in-memory flag.
-
Offset pagination (
LIMIT 50 OFFSET 100000) is simple but becomes slower as the offset grows and can duplicate or skip rows when inserts or deletes occur. Keyset pagination seeks from the last sort key and remains efficient with an index. -
A cursor requires a total ordering. If sorting by
created_at, use a unique tie-breaker such asid:ORDER BY created_at DESC, id DESC. The next-page predicate is lexicographic, for example(created_at, id) < (:last_time, :last_id). -
Cursors should be opaque to clients, commonly a base64url-encoded serialized payload containing the sort values, direction, filters, and schema version. Sign or authenticate the cursor to prevent tampering; encrypt it if sort values reveal sensitive information.
-
Cursor validity depends on consistency requirements. A live keyset query tolerates ordinary changes but may omit newly inserted records or show boundary effects; a snapshot token, stable read timestamp, or materialized result gives stronger consistency at additional storage and retention cost.
-
Fetch
limit + 1rows to determinehas_morewithout an expensive count query. Enforce server-side bounds such as1 <= limit <= 100; reject invalid, expired, filter-mismatched, or direction-mismatched cursors clearly. -
Index for the access pattern, not merely the filter: a feed ordered by
(created_at DESC, id DESC)needs a compatible composite index. For very large datasets, avoid counting all matching rows, and use bounded reads with predictablep95andp99latency.
Worked example
No interview title was supplied, so use this representative prompt: “Design an idempotent, cursor-paginated API for creating and listing user resources.” In the first 30 seconds, clarify whether creation may be retried, whether list results need snapshot consistency, the maximum page size, authorization scope, and the expected read/write rate. I would organize the answer around the API contract, idempotency state machine, transactional storage, pagination algorithm, and failure/observability behavior. For creation, the client sends an Idempotency-Key; the server atomically inserts a request record, performs the mutation in the same transaction, stores the response, and returns the stored response on retries. For listing, I would define a stable (created_at, id) order, use a composite index and a keyset predicate, and return an opaque cursor plus has_more. The key tradeoff is live pagination versus snapshot pagination: live reads are cheaper and fresher, while snapshots provide more stable traversal but require retaining or encoding additional state. I would explicitly describe concurrent duplicate requests and the crash window between the business write and response persistence. If I had more time, I would add rate limits, cursor versioning, metrics for duplicate-key conflicts, and a reconciliation strategy for external side effects.
A second angle
A different framing is “Design a paginated feed API where new posts arrive continuously while users scroll.” Here, the main concern is not creation retries but whether newly inserted posts should appear during an existing traversal. A descending (timestamp, id) cursor prevents most duplicates and skips, but new records ahead of the cursor will not appear unless the client refreshes from the beginning. If product requirements demand a frozen feed, introduce a snapshot timestamp or feed-generation token; if freshness matters more, document live-feed semantics and provide a refresh mechanism.
Common pitfalls
Pitfall: Saying “POST is safe to retry if the server checks the key” without explaining durable storage, atomic uniqueness, parameter mismatch handling, and concurrent requests. A strong answer describes the state transitions and the crash window explicitly.
Pitfall: Using
OFFSETpagination for a high-volume mutable table because it is easier to explain. That answer ignores deep-page cost and duplicate or skipped records; propose keyset pagination with a unique tie-breaker and state the consistency tradeoff.
Pitfall: Promising exactly-once behavior across a database and an external service. Exactly-once is not obtained by a local lock; discuss transactional outbox, downstream idempotency, reconciliation, and what the client sees after an ambiguous timeout.
Connections
The interviewer may pivot to rate limiting, transaction isolation, distributed locks, outbox and saga patterns, or API versioning. Be ready to connect cursor semantics to database indexes and idempotency semantics to retries, leases, and observability.
Further reading
- Stripe: Idempotent Requests — a concrete production API treatment of keys, retries, and parameter consistency.
- Designing Data-Intensive Applications by Martin Kleppmann — useful background on transactions, consistency, replication, and reliable distributed workflows.
- RFC 8288: Web Linking — formal context for representing pagination links such as
nextandprev.
Related concepts
- API Idempotency And Concurrency ControlSystem Design
- API Design, Data Modeling, and IndexingSystem Design
- Idempotent API DesignSystem Design
- API Design, Modularization, And Error HandlingSoftware Engineering Fundamentals
- Reliable API Integration And Distributed DesignSystem Design
- API And Database Ingestion Patterns