HTTP semantics, resource design, retries and idempotency, concurrent updates, pagination, versioning and rate limits, with a definition at every new term and practice questions at the end.
Explain what an API contract is, why it is more expensive to change than the code behind it, and how much of it to specify at the high-level and at the low-level design stage.
Apply HTTP method semantics and status codes to decide which operations are safe or idempotent and how each outcome should be signalled to a client.
Derive an API surface from a list of core entities, and choose between REST, gRPC, GraphQL and event-based interfaces, including when an operation should be asynchronous.
Design error responses that let a client distinguish permanent, transient and ambiguous failures, and calculate the load that retries at several layers can generate.
Apply idempotency keys and conditional requests to make retries and concurrent updates safe, and calculate the storage a deduplication window needs.
Calculate the cost of offset pagination against keyset pagination, and design an opaque cursor that stays correct while the underlying data changes.
Distinguish breaking from non-breaking changes, plan versioning and deprecation, and calculate how many requests a token-bucket rate limit admits.
§1 · Definitions
Core concepts
This section defines four terms that every later section relies on. Each definition is set out in a callout where the term is first introduced, and the prose after it explains the mechanism.
The word interface carries its engineering sense of a shared boundary between two systems, and application programming distinguishes it from a user interface: the party on the other side is a program, not a person. Between services the boundary is a network interface such as an HTTP endpoint or a gRPC method; inside one service it is a set of class or method signatures, such as ParkingLot.park(vehicle): Ticket.
A complete contract states the operations, the name and type of every input and output field, which inputs are required, the status and error codes, and the behavioural guarantees that are not visible in a single request: what happens when a request is repeated, how large result sets are split into pages, how two concurrent updates interact, how much traffic a client may send, and how the contract itself will change over time.
The mechanism that gives the contract its weight is independent deployment. The provider and its clients are built, released and run by different teams or organisations, on different schedules. Anything behind the contract, such as the database schema, the class structure or the caching strategy, can be changed in one deployment by the provider alone. Anything in the contract can only be changed by coordinating with every client that depends on it, and for a public API those clients are not known individually. A field name chosen in an afternoon can therefore stay in place for years, which is the reason to spend design effort on the contract out of proportion to the size of the code that implements it.
API design happens at two levels of design, and the remaining two terms name those levels.
At the HLD level, API design means naming the operations, deciding which component owns each one, choosing the protocol and deciding whether each call is synchronous or asynchronous. At the LLD level it means writing out the full contract. The operation is the same at both levels; what changes is how precisely its behaviour is written down.
The confusion learners most often have with the central term is to treat an API as a list of URLs. A list of endpoints is the HLD view of the API, and it is the right amount of detail in the first minutes of a design discussion, but it says nothing about the behaviour that causes failures in production: a payment request retried after a timeout, two editors saving the same record, a client paging through a list while rows are inserted, or an old mobile app meeting a renamed field. A second, related confusion is to equate API with HTTP. Method signatures between classes, gRPC services and events on a message stream are all APIs, and the contract questions apply to each of them.
§2 · RFC 9110
HTTP semantics the contract builds on
This section covers a prerequisite that the rest of the guide relies on. Most network APIs are carried over HTTP, and the later sections on retries, idempotency and conditional updates rely on properties that HTTP already defines. The current definition is RFC 9110, HTTP Semantics, published by the IETF in 2022, which consolidated material previously spread over several older RFCs.
An HTTP method is the verb of a request, the part that says what the client wants done to the target URL. HTTP classifies methods by two properties that clients, proxies and libraries are allowed to rely on. A safe method is one whose semantics are read-only: the client does not request any change of state on the server, so GET, HEAD and OPTIONS can be sent speculatively, prefetched or cached. An idempotent method is one where the intended effect on the server of several identical requests is the same as the effect of one. Every safe method is idempotent, and so are PUT, which replaces the target with the supplied representation, and DELETE, which removes it. POST and PATCH are not idempotent in general, because POST typically creates something new on each call and PATCH may express a relative change such as "add one item".
The reason these properties exist is the ambiguity of a lost response. When a connection drops after a request has been sent, the client cannot tell whether the server processed it. HTTP allows a client or proxy to resend an idempotent request automatically in that situation, because doing so cannot change the outcome; it does not allow the same for POST. The property concerns the effect on server state, not the response. A second DELETE for the same order may return 404 Not Found while the first returned 204 No Content, and the method is still idempotent, because the server's state after both calls is the same as after one. Under RFC 9110 both responses conform, so which one to return is a design choice. Returning 204 makes a retried delete look identical to a first delete, which simplifies clients that retry; returning 404 tells the truth about the current state. Either is acceptable if the contract states which one the API uses.
The following table sets out the methods an API contract normally uses against the safe and idempotent properties, and adds whether a client can retry a request with no extra mechanism. It is useful because the last column is the one that decides where the server needs a way to recognize repeated requests.
Method
Safe
Idempotent
Typical use
Retry after an ambiguous failure without extra mechanism
GET
Yes
Yes
Read a resource or collection
Yes
PUT
No
Yes
Replace a resource with a full representation
Yes
DELETE
No
Yes
Remove a resource
Yes
PATCH
No
Not in general
Change part of a resource
Only if the patch sets absolute values
POST
No
No
Create a resource or trigger an action
No; needs an idempotency key or a client-supplied identity
Read down the last column and the pattern is that the operations which create or change something relative to its current state are the ones that need help. The same split holds beyond HTTP: absolute writes are safe to repeat, while relative writes, creates, appends and external effects are not.
A status code is the three-digit number at the start of every HTTP response, and its first digit gives the class of outcome. 2xx means the request succeeded, for example 200 OK, 201 Created with a Location header naming the new resource, 202 Accepted for work that has been queued, and 204 No Content. 3xx means the client must take a further action such as following a redirect, and 304 Not Modified tells a client its cached copy is still current. 4xx means the request itself is at fault, so repeating it unchanged will normally fail again: 400 Bad Request, 401 Unauthorized for missing or invalid credentials, 403 Forbidden, 404 Not Found, 409 Conflict, 412 Precondition Failed, 422 Unprocessable Content and 429 Too Many Requests. 5xx means the server failed, so the same request may succeed later: 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable and 504 Gateway Timeout. The class is a first approximation of whether to retry; "Errors and retry safety" refines it, because 429 is a client-class code that should be retried and a 500 received after a non-idempotent request should not be blindly repeated.
§3 · Surface
Resources and the API surface
With the method vocabulary in place, the next step is deciding what the API's operations act on. For HTTP APIs the prevailing answer is REST, short for Representational State Transfer, the architectural style that Roy Fielding described in his doctoral dissertation in 2000. A REST API is organised around resources, the nouns of the domain, each identified by a URL. Clients act on a resource by transferring representations of it, usually JSON documents, using the uniform set of HTTP methods. The nouns go in the URL and the verbs come from the method, so POST /urls creates a short link, GET /urls/{code} reads one, DELETE /urls/{code} removes one and GET /users/{id}/urls lists the links a user owns. Nesting a collection under its owner, as in that last URL, expresses ownership in the address itself.
Not every operation is a create, read, update or delete. Cancelling an order, for example, is an action with its own rules. There are two established ways to express it. The first models the action as a resource of its own, POST /orders/{id}/cancellations, which gives the cancellation an identity, a timestamp and a place to record a reason. The second, used in Google's API design guidance, is a custom method written as POST /orders/{id}:cancel. Both keep the noun-based structure; what to avoid is drifting into verb-named URLs such as /cancelOrder, which reintroduce one-off conventions for every action.
The order in which the surface is designed matters because the API and the data model depend on each other in both directions, and a four-step order resolves the dependency. A short list of entity names comes first, because REST resources are those entities, and agreeing on the nouns before writing endpoints prevents the same thing being called /links in one place and /short-urls in another. The API surface comes second, because each endpoint is a read or a write the storage layer must serve. Those reads and writes, with their frequencies, are the access patterns of the system, and the data model and choice of datastore come third because they can only be justified by access patterns. The architecture comes fourth. The diagram below shows that flow for a URL shortener.
Diagram
core entities API surface access patterns data model and store architecture
User, ShortUrl, ──► POST /urls ──► lookup one record ──► key-value store, ──► cache on the read path,
Click GET /{code} by key, read-heavy partitioned on writes to the store
GET /users/{id}/urls list by owner short_code; index on
owner_id
▲ │
└────────── a missing endpoint discovered while modelling data ◄────┘
Read the diagram from left to right: each box supplies the reasons for the next one, so the key-value store is justified by the single-key lookup, which is justified by GET /{code}, which exists because of the ShortUrl entity. The return arrow records that the process is not strictly linear. Modelling the data often exposes a query no endpoint asked for, such as listing a user's links, and the right response is to add the endpoint rather than treat the API as finished.
Granularity is the remaining surface decision. Every API call across a network costs at least one round trip, so an API whose operations are too fine-grained forces clients into long sequences of calls. A mobile screen that shows an order with its items and their product names should not need one call for the order, one per item and one per product, which is the API-level form of the N+1 query problem: one call to get a list, then N further calls for its members. The usual remedies are to shape operations around what a client needs to accomplish, to let a client request related data in one call, for example with an expand=items.product parameter, or to provide a batch endpoint. The opposite error, one large operation that returns everything, wastes bandwidth and couples every client to the full response shape, which motivates an API style that lets clients select the fields they need, discussed in "Choosing an API style".
§4 · Interface style
Choosing an API style
Once the operations are known, the next decision is which style should carry them. Four styles are in common use: REST, gRPC, GraphQL and events on a message stream.
REST over HTTP with JSON bodies was introduced under "Resources and the API surface". Its strengths come from HTTP itself: every language and tool can call it, responses to GET can be cached by browsers, proxies and content delivery networks, and a request can be inspected and replayed with a command-line tool. Its contract is usually written in OpenAPI, a machine-readable description format, but nothing forces the implementation to match the description.
gRPC is a remote procedure call framework that Google open-sourced in 2015, derived from its internal system called Stubby; the leading "g" is officially left undefined. A remote procedure call presents a network request as if it were a function call, orders.GetOrder(GetOrderRequest), and gRPC carries those calls over HTTP/2. The contract is written in Protocol Buffers, Google's schema language and binary encoding, from which client and server code is generated in each language. The generated code enforces the contract at compile time, the binary encoding is smaller and faster to parse than JSON, and HTTP/2 allows streaming in either direction. The costs are that browsers cannot call gRPC directly without a translating proxy, messages are not human-readable, and long-lived HTTP/2 connections need request-level load balancing, because a load balancer that chooses a backend only when a connection opens sends every request on that connection to the same backend.
GraphQL is a query language for APIs developed at Facebook from 2012 and published in 2015. The server exposes a typed schema of objects and their relationships through a single endpoint, and each client sends a query naming exactly the fields it wants, so one request can fetch an order, its items and their product names. That removes over-fetching (receiving fields the client does not use) and under-fetching (needing several calls), which matters when many different clients, such as web, iOS and Android, need different shapes of the same data. The costs move to the server: one innocent-looking query can fan out into thousands of database reads, so the server needs query cost limits and batching, and because queries are usually sent as POST requests to one URL, ordinary HTTP caching does not apply.
Event-based interfaces invert the direction of the call. Instead of a client asking for something, a producer publishes a fact that has happened, such as OrderPlaced, and consumers react to it in their own time. Inside a system the events travel over a broker such as Kafka; across organisational boundaries the usual form is the webhook, an HTTP request that a service sends to an endpoint you expose when an event happens, so that you learn of it without polling. The contract that comes with this style is that delivery is at least once and possibly out of order, so receivers need signature checks, deduplication on the event identifier and a periodic reconciliation against the sender's API.
The following table compares the four styles across the dimensions that usually decide between them. It is useful because each style is strong where another is weak, so the choice depends on who the clients are.
Dimension
REST over HTTP
gRPC
GraphQL
Events and webhooks
Direction
Client asks, server answers
Client asks, server answers, optional streams
Client asks, server answers
Producer pushes facts to consumers
Contract definition
OpenAPI document, often optional
Protocol Buffers schema, enforced by generated code
Typed schema, enforced by the server
Event schema, often in a registry
Encoding
JSON text
Binary
JSON text
JSON or binary
HTTP caching
Works for GET
Not applicable
Does not apply to POST queries
Not applicable
Main cost
Many calls or over-fetching for varied clients
Tooling needed; no direct browser access
Query cost control on the server
At-least-once, unordered delivery to handle
Typical fit
Public and partner APIs
Internal service-to-service calls
Several client types aggregating data
Notifying other systems of changes
The table suggests a common arrangement rather than a single winner: REST for the public edge, gRPC between internal services, GraphQL as an aggregation layer in front of several services when client needs diverge, and events wherever one system must react to another without being called by it.
The second decision made at the HLD stage is whether each operation is synchronous, meaning the caller waits for the result, or asynchronous, meaning the provider accepts the request, queues the work and answers before it is done. The choice shapes the architecture, because an asynchronous operation needs a queue and a worker pool. It belongs in the contract as well, because the client needs a way to learn the outcome. The established pattern is the long-running operation: the provider answers 202 Accepted with a Location header pointing at an operation resource, and the client reads that resource until it reports success or failure, or registers a webhook to be told. Holding an HTTP request open for minutes instead would occupy a connection and a server thread for the whole time, and it would collide with the idle timeouts that load balancers and proxies impose. The exchange below is illustrative.
HTTP
POST /reports HTTP/1.1
Idempotency-Key: 3f6c2a9e-8d41-4b7a-9c1e-5a2d7f0b6e11 # the create is a POST, so a retry needs a key (see "Idempotency keys")
Content-Type: application/json
{"type": "monthly_sales", "month": "2026-10"}
HTTP/1.1 202 Accepted # the work is queued, not done
Location: /operations/op_81f2 # where the client can watch progress
Retry-After: 5 # suggested polling interval in seconds
GET /operations/op_81f2 HTTP/1.1
HTTP/1.1 200 OK
{"id": "op_81f2", "status": "succeeded", # status moves pending -> running -> succeeded or failed
"result": "/reports/rep_5521"} # the finished resource has its own URL
The diagram below shows the states the operation resource moves through, which is what the client's polling observes.
Read it as the lifecycle the contract promises: every operation starts at pending, passes through running, and ends in exactly one of the two terminal states, which never change afterwards. Because the terminal states are final, a client that loses track of an operation can always recover by reading it again.
§5 · Failure handling
Errors and retry safety
Resource design and the choice of style describe what happens when calls succeed; the contract must also say what the API returns when they fail, so that clients can tell which failures are safe to retry. A client receiving an error needs answers to two questions: did the operation take effect, and would trying again help? A retryable error is one where the answer to the second question is yes. Sorting failures by those two questions gives three groups, which the status code classes from "HTTP semantics the contract builds on" only partly separate.
Permanent failures are those where the request is wrong or not allowed, such as 400, 401, 403, 404 and 422. The operation did not take effect and repeating it unchanged will fail again, so the client should not retry. Transient failures are those where the server refused the request before doing anything, such as 429 Too Many Requests and 503 Service Unavailable. The operation did not take effect and repeating it later should work, ideally after the delay the server names in a Retry-After header. Ambiguous failures are those where the client cannot know whether the operation took effect: a timeout, a dropped connection, a 502 or 504 from a gateway, or a 500 after the server had started work. For an idempotent operation the client can simply retry. For a non-idempotent one, a retry may perform the operation twice, and the safe options are giving the server a stable identifier so it can recognize a repeated request, as explained in "Idempotency keys", or reading the state to find out what happened. The ambiguous group is the reason idempotency is part of API design rather than an implementation detail.
A status code alone is too coarse for a client to act on, so the contract also fixes the shape of the error body. The standard format is problem details, defined in RFC 9457 (2023), which replaced RFC 7807. A problem-details body has the media type application/problem+json and the members shown in the illustrative example below.
JSON
{
"type": "https://api.example.com/problems/insufficient-stock",
"title": "Not enough stock",
"status": 409,
"detail": "Only 2 units of SKU 8812 are available; 5 were requested.",
"instance": "/orders/req_7c1d",
"available": 2
}
The type URI is the stable, machine-readable identifier of the error and is the part clients branch on; title is a short human summary of that type; status repeats the HTTP status; detail explains this occurrence for a human and should not be parsed by programs; instance identifies the specific request; and extension members such as available carry data the client can use to recover. Because type is part of the contract, adding a new error type is a contract change that clients must be able to tolerate, a point taken up in "Versioning and evolution".
The client side of the contract is the retry policy. Exponential backoff lengthens the wait between attempts geometrically, for example 100, 200 and 400 ms, so that a struggling server receives less traffic the longer it struggles. Jitter randomises each wait so that thousands of clients that failed at the same moment do not retry at the same moment; with full jitter a client sleeps a random time between zero and min(cap, base × 2^attempt). Even with both, retries add load exactly when the provider is least able to absorb it, and the effect multiplies when several layers of a call chain each retry, a pattern called retry amplification.
Worked exampleretry amplification across layers
Three retrying layers making three attempts each can send 27 calls to the bottom service. To trace it, consider a request path client → gateway → order service → inventory service, in which the client, the gateway and the order service each make up to three attempts at the next hop, and suppose the inventory service is failing every call.
The order service, invoked once, calls the inventory service up to 3 times.
The gateway, invoked once, calls the order service up to 3 times, and each of those makes up to 3 inventory calls, giving 3 × 3 = 9 inventory calls.
The client calls the gateway up to 3 times, and each of those produces up to 9 inventory calls, giving 3 × 9 = 27 inventory calls for one user action.
In general, k retrying layers with n attempts each give up to n^k calls at the bottom, and 3^3 = 27 checks the figure. As an assumption for scale, take a base load of 1,000 user requests per second: a full outage of the inventory service then turns it into 1,000 × 27 = 27,000 calls per second against a service that is already failing. Two remedies follow directly from the arithmetic. Retrying at one layer only, usually the outermost layer or the one that can recognize repeated requests, brings the multiplier back to 3, or 3,000 calls per second. A retry budget that caps retries at 10% of a client's traffic bounds it further, to 1,000 + 0.10 × 1,000 = 1,100 calls per second, regardless of how many layers retry.
Retries also need time limits, and deadline propagation supplies them across a chain: each caller passes the remaining time budget down, so downstream services stop working on a request once the original caller can no longer use the answer. For example, a gateway sets an 800 ms deadline, the order service spends 200 ms and forwards the remaining 800 − 200 = 600 ms, and the inventory service abandons its query at 600 ms rather than at its own default of 2 seconds. gRPC carries deadlines in the protocol; an HTTP API has to carry them in a header of its own and say so in the contract.
§6 · Retry safety
Idempotency keys
Retrying an ambiguous failure is safe only if a repeated request has no further effect, and idempotency keys are the general mechanism that makes it so. The term idempotency comes from mathematics, where an operation is idempotent if applying it twice gives the same result as applying it once; the HTTP sense in "HTTP semantics the contract builds on" applies the same idea to the effect of a request on server state.
Four mechanisms make a repeated request harmless. They are worth considering from cheapest to strongest, because the first three need no extra infrastructure. Natural idempotency sends absolute state rather than changes, quantity = 3 rather than quantity -= 1, so a repeat writes the same value. A natural key with a unique constraint lets the database reject the duplicate, for example a chat message carrying a client-generated client_msg_id. A conditional write applies an update only if the version is still the one the client read, which is the subject of "Conditional requests and concurrent updates". Only when none of these can express the operation, for example a payment that calls an external provider or a create with no natural identity, does the API need an explicit key.
An idempotency key is a client-generated identifier, sent with a non-idempotent request, that lets the server recognise a repeat of that request and return the original result instead of performing it again. The conventional carrier is an Idempotency-Key request header; it is specified in an IETF Internet-Draft (draft-07 in October 2025) on the standards track rather than in a published RFC, and Stripe, Adyen and PayPal all use the same header name. Five rules define a correct implementation, and each follows from the ambiguous failure the key exists to resolve.
The client generates the key before the first attempt and reuses it unchanged on every retry, typically as a random version 4 UUID. A key generated per attempt deduplicates nothing, and a key generated by the server is useless because the client that timed out never received it. The key is unique within a scope of (account, operation, key) rather than globally, so that one customer's key can neither collide with nor reveal another's. The server stores the status code and body of the first attempt and replays them verbatim on a repeat, including error responses; a table that only records "seen" stops the duplicate effect but leaves the retrying client without the answer it lost. The server also stores a request fingerprint, a hash of the canonicalised request body, and treats the same key arriving with a different body as an error, 422 Unprocessable Content, because silently replaying the old response would drop a genuine request while reporting success. Finally, the server keeps keys for a dedup window, the period during which a duplicate is still recognised, and that window must be longer than the longest time a client might go on retrying. Stripe's published contract is a useful model: keys are pruned once they are at least 24 hours old, and a key reused after pruning is treated as a new request.
Concurrency is where implementations most often fail, and a three-state model handles it. The diagram below shows the states a key row moves through and the response each state produces.
Diagram
first request
(no row) ─────────────────────────────► in_flight ─────── effect completes ───────► completed
▲ │ │
│ duplicate arrives │ duplicate arrives, │ duplicate arrives,
│ ─► 409 Conflict ◄──┘ same fingerprint │ different fingerprint
│ ─► replay stored ◄───┤ ─► 422
│ status and body │
└───────────────────────────── dedup window expires ──────────────────────────────┘
Read the diagram as the server's decision for each arriving request with a given key: with no row it processes normally; while the first attempt is still running it answers 409 Conflict, or briefly waits and checks again; after completion it replays or rejects depending on the fingerprint; and once the window expires the key is forgotten. The HTTP contract adds one more case, a missing key on an endpoint that requires one, which is 400 Bad Request.
The key row must be created atomically with the check, and implementations that break this rule fail in a predictable way: if the server checks for the key and inserts it in separate, non-atomic steps, two concurrent duplicates both pass the check. A unique constraint on (account, operation, key) makes the database arbitrate. When the whole effect is a database write, the key row and the effect can be inserted in one transaction, and a concurrent duplicate's insert waits on the constraint until the first transaction commits. When the effect includes an external call, such as charging a card, a transaction cannot stay open across it, so the in_flight row is committed on its own first, the call is made, and the stored result and completed state are written afterwards. That variant adds a recovery duty: a row left in_flight by a crashed server must eventually be resolved, by checking the external provider for the outcome or by expiring the row. The illustrative Spring sketch below shows the single-transaction case.
Java
@Transactional // key row and order commit or roll back together
public StoredResponse placeOrder(String accountId, String key, OrderRequest req) {
String fingerprint = sha256(canonicalJson(req)); // detects the same key reused with a different body// Unique constraint on (account_id, operation, idem_key) makes this insert the atomic check.// DO UPDATE with a no-op assignment, rather than DO NOTHING, so RETURNING yields the row on conflict too.
IdemRow row = jdbc.queryForObject("""
INSERT INTO idempotency_keys (account_id, operation, idem_key, fingerprint, state, created_at)
VALUES (?, 'place_order', ?, ?, 'in_flight', now())
ON CONFLICT (account_id, operation, idem_key) DO UPDATE SET idem_key = EXCLUDED.idem_key
RETURNING fingerprint, state, status_code, body, (xmax = 0) AS inserted
""", IdemRow.MAPPER, accountId, key, fingerprint);
if (!row.inserted()) { // a previous attempt with this key exists
if (!row.fingerprint().equals(fingerprint)) return StoredResponse.problem(422, "idempotency-key-reused");
return StoredResponse.of(row.statusCode(), row.body()); // completed: replay the first result verbatim
}
Order order = orders.create(accountId, req); // the effect, inside the same transaction
StoredResponse response = StoredResponse.created(order); // 201 with the order body and Location header
jdbc.update("UPDATE idempotency_keys SET state = 'completed', status_code = ?, body = ? " +
"WHERE account_id = ? AND operation = 'place_order' AND idem_key = ?",
response.status(), response.json(), accountId, key); // store the response, not just a flag
return response;
}
The comment on the insert records a PostgreSQL detail: INSERT … ON CONFLICT DO NOTHING RETURNING * returns no rows on a conflict, so the code would be unable to read the stored response; the no-op DO UPDATE makes RETURNING fire in both cases. In this single-transaction form a concurrent duplicate never observes in_flight, because it waits on the constraint and then sees completed. The xmax = 0 test is a PostgreSQL-specific way of telling a fresh insert from a conflict. The sketch also respects one more rule by placing validation before this method: requests that fail validation are not recorded, so a client that sent a malformed request can correct it and retry with the same key.
Worked examplesizing the dedup window
The dedup window has a storage cost proportional to request rate and retention, and this calculation shows how to estimate it. The figures are assumptions for illustration.
Assumption: the order-creation endpoint receives an average of 200 keyed requests per second.
Assumption: the dedup window is 24 hours, matching Stripe's published contract. That is 24 × 3,600 = 86,400 seconds.
Keys held at steady state: 200 × 86,400 = 17,280,000 rows.
Assumption: each row holds the key, scope, fingerprint, state, status code and a stored response body, about 2,000 bytes in total.
Storage: 17,280,000 × 2,000 = 34,560,000,000 bytes, about 34.6 GB.
To check the figure, work from the other direction: one hour holds 200 × 3,600 = 720,000 rows, or 720,000 × 2,000 = 1.44 × 10^9 bytes, and 24 hours of that is 24 × 1.44 GB = 34.56 GB, which matches. The calculation shows which parameters to negotiate: doubling the window to 48 hours doubles the storage to about 69.1 GB, while storing a short summary instead of the full response body, say 500 bytes per row, cuts it to 17,280,000 × 500 = 8.64 GB. It also shows why the window is a stated policy: the storage is bounded only because old keys are deleted, and the contract must say what a retry after deletion does.
§7 · ETag and If-Match
Conditional requests and concurrent updates
Idempotency keys protect a client from its own repeated requests; a different failure arises when two clients change the same resource. In a lost update, two clients read version 4 of a record, each makes a change, and both write back; the second write silently overwrites the first, and neither client is told. The general remedy is optimistic concurrency control, and this section applies it to the HTTP contract.
Optimistic concurrency control lets every client proceed without locking and checks at write time that the data has not changed since it was read, usually by comparing a version number. The alternative, pessimistic control, locks the record before changing it so that other writers wait; it suits heavy contention but does not fit an API well, because a lock held between a client's read and its later write would last as long as the client takes, which the provider does not control.
HTTP expresses the optimistic check with an ETag, short for entity tag, a response header that identifies one version of a resource's representation, such as ETag: "v4". A client that wants to update the resource sends the tag back in an If-Match header, making the update a conditional request, one the server performs only if a stated precondition holds. If the current version no longer matches, the server refuses with 412 Precondition Failed, and the client re-reads the resource, reapplies its change and tries again. A provider that wants to forbid unconditional updates altogether can answer them with 428 Precondition Required. The illustrative exchange below shows the second of two concurrent editors being stopped.
HTTP
GET /documents/42 HTTP/1.1
HTTP/1.1 200 OK
ETag: "v4" # both editors read version 4
PUT /documents/42 HTTP/1.1
If-Match: "v4" # editor A: apply only if still at version 4
...
HTTP/1.1 200 OK
ETag: "v5" # A's write succeeds and creates version 5
PUT /documents/42 HTTP/1.1
If-Match: "v4" # editor B: still believes version 4 is current
...
HTTP/1.1 412 Precondition Failed # B's change is refused instead of overwriting A's
The same check is also often written with the version carried in the request body and a 409 Conflict response. Both forms are in use; 412 is the code HTTP defines for a failed precondition sent in a header, and 409 is the usual choice when the version travels in the body. On the server, the check must be part of the write itself, for example UPDATE documents SET body = ?, version = version + 1 WHERE id = ? AND version = ?, with zero rows affected meaning the precondition failed. Reading the version, comparing it in application code and then writing in a separate statement reproduces the race the check exists to prevent.
The same headers serve two other purposes. On reads, a client sends If-None-Match: "v4" and receives 304 Not Modified with no body if its cached copy is current, which saves bandwidth. On creates, PUT with If-None-Match: * means "create only if nothing exists here", which makes a create with a client-chosen URL safe to retry. A conditional PUT is also the third idempotency mechanism from "Idempotency keys", with one difference in what the client sees: a retry of an update that in fact succeeded receives 412, because the version has moved on, so the client must re-read to discover that its own change is the one that was applied.
§8 · Collections
Pagination
Idempotency keys and conditional requests act on one resource at a time; collection reads raise a different question: how clients page through large result sets. Pagination is the splitting of a large result into pages that a client fetches one request at a time, and it is part of the contract because it bounds the work of every list request and determines what a client sees when the list changes underneath it.
Offset pagination addresses a page by its position, as in ?page=3&size=50, which the server translates into LIMIT 50 OFFSET 100. It is simple and lets a user jump to any page number, but the database cannot jump to row 100: it must walk the sorted index from the start, read the skipped rows and discard them. Keyset pagination instead asks for the rows after the last key the client saw, as in WHERE id > :last ORDER BY id LIMIT 50, so every page starts with an index seek to a known key. The client does not handle the key directly; the API returns an opaque cursor, a token encoding the position, and the client sends it back to get the next page. The contract below is illustrative.
HTTP
GET /orders?limit=50 HTTP/1.1
HTTP/1.1 200 OK
{
"items": [ ... 50 orders, newest first ... ],
"next_cursor": "eyJjIjoiMjAyNi0xMS0wNFQxMDoxNTowMloiLCJpIjo5ODEyMn0" # opaque to the client
}
GET /orders?limit=50&cursor=eyJjIjoiMjAyNi0xMS0wNFQxMDoxNTowMloiLCJpIjo5ODEyMn0 HTTP/1.1
SQL
-- The cursor decodes to the sort key of the last row returned: created_at and id.-- Index required: (created_at DESC, id DESC); id breaks ties so the order is total.
SELECT id, created_at, total
FROM orders
WHERE (created_at, id) < (:last_created_at, :last_id) -- resume strictly after the last row seen
ORDER BY created_at DESC, id DESC -- must match the index and the cursor's key
LIMIT 50; -- page size; no OFFSET, so no rows are skipped over
Three details in the sketch carry the correctness of the design. The sort key must be unique, which is why id follows created_at: when paging on a non-unique column alone, rows sharing a timestamp at a page boundary are skipped or shown twice. The cursor is opaque, here base64-encoded JSON, so the provider can change what it encodes without breaking clients; it should also record the sort order and filters it was issued for, and be signed or validated, so that a client cannot combine a cursor with a different query. The end of the list is signalled by the absence of next_cursor, rather than by a total count, because counting every matching row costs as much as reading them all.
Worked examplethe cost of deep pages
Compare page 2,000 under the two schemes with a page size of 50.
Page 2,000 starts after (2,000 − 1) × 50 = 99,950 rows, so offset pagination issues LIMIT 50 OFFSET 99950.
The database reads the 99,950 skipped rows and then the 50 returned rows, 99,950 + 50 = 100,000 rows in total, to return 50.
Keyset pagination seeks directly to the last key and reads 50 rows, the same as for page 1.
The comparison grows when a client pages through the whole list, as an export job does. Under offset pagination page k reads 50k rows, so 2,000 pages read 50 × (1 + 2 + … + 2,000) = 50 × (2,000 × 2,001 ÷ 2) = 50 × 2,001,000 = 100,050,000 rows. Under keyset pagination they read 2,000 × 50 = 100,000 rows. The ratio is 100,050,000 ÷ 100,000 = 1,000.5, so the full traversal costs about a thousand times as much with offsets, and the cost grows with the square of the number of pages rather than linearly.
Worked examplea list that changes during paging
Cost is one reason to prefer cursors; the other is that cursor pagination stays correct while data changes. Take a newest-first list paged 50 at a time, and number the items by their rank when the client fetched page 1, so page 1 contained items 1 to 50.
Before the client asks for page 2, three new items are inserted at the top of the list. Every existing item moves down three ranks.
Offset pagination requests OFFSET 50, which now returns the items in current ranks 51 to 100. Those are the items originally ranked 51 − 3 = 48 to 100 − 3 = 97.
Items 48, 49 and 50 therefore appear on page 2 a second time.
If instead three items from page 1 had been deleted, every later item would move up three ranks, OFFSET 50 would return the items originally ranked 54 to 103, and items 51, 52 and 53 would never be shown.
Keyset pagination resumes after the key of item 50 in both cases, so it returns items 51 to 100 with no repeats and no gaps. The three new items are not shown in this pass; a client sees them when it starts again from the top.
That correctness has a price: with cursors a reader cannot jump to an arbitrary page number. Interfaces that need numbered pages, such as an admin table, can use offsets over small or stable result sets, while feeds, sync endpoints and exports should use cursors.
§9 · Compatibility
Versioning and evolution
The subtopics on resources, errors, idempotency and pagination design a contract at one moment; versioning decides how it can change without breaking the clients that already use it.
A breaking change is a change to the contract that makes a correctly written existing client fail or behave wrongly. Backward compatibility is the property of a new version that every client written against the old version still works. Removing or renaming a field, changing a field's type, making an optional input required, changing a default, tightening validation, changing which error a situation produces, and changing pagination semantics are all breaking. Adding an endpoint, adding an optional input, and adding a field to a response are normally not.
Whether additions are safe depends on clients following the tolerant reader pattern, a name Martin Fowler gave in 2011 to the practice of reading only the fields a client needs and ignoring everything else. It applies to APIs the robustness principle that Jon Postel wrote into early Internet protocol specifications around 1980: be conservative in what you send and liberal in what you accept. A client that rejects responses containing unknown fields, or that handles an enumeration with a switch that fails on unknown values, turns every addition into a breaking change. Adding a new value to an enumeration, such as a new order status, is the common case: it is additive for the provider and breaking for any client without a default branch, so a contract that intends to add values should say from the start that clients must handle unknown ones.
Even a disciplined contract does not capture everything clients rely on. Hyrum's law, named after Hyrum Wright at Google, states that with a sufficient number of users of an API, all observable behaviours of the system will be depended on by somebody, whatever the contract promises. Response field order, the precise wording of an error message, the default sort order of a list and the typical latency of a call all become de facto contract once enough clients exist. The practical consequences are to document what is guaranteed and what is not, to avoid exposing incidental behaviour, for example by making cursors opaque rather than readable offsets, and to treat any observable change as potentially breaking when the client base is large.
When a breaking change is unavoidable, the provider runs two versions side by side and moves clients from one to the other. The version can be placed in the URL path, /v1/orders and /v2/orders, which is visible, easy to route and cache, and coarse, since the whole API changes version at once. It can be placed in a header or media type, Accept: application/vnd.example.v2+json, which keeps URLs stable at the cost of being invisible in logs and links. A third scheme, which Stripe uses, names versions by date and pins each account to the version current when it first integrated, so the provider can make many small breaking changes while each client upgrades on its own schedule. In gRPC the contract evolves through Protocol Buffers field numbers: a field is identified on the wire by its number rather than its name, so a removed field's number is marked reserved and never reused, and a breaking change becomes a new package, orders.v2.
Retiring an old version is a process with its own signals in HTTP. The diagram below shows the lifecycle of a version.
Diagram
v1 active ──(v2 released)──► v1 deprecated ──(sunset date reached, usage near zero)──► v1 sunset
Deprecation and Sunset 410 Gone, with a link
headers on every v1 response to migration notes
Read the diagram left to right as the obligations at each stage. Deprecation means the version still works but clients are told to move; the Deprecation response header, standardised in RFC 9745 (2025), marks deprecated responses, and the Sunset header from RFC 8594 (2019) gives the date after which the version will stop working. Sunset is the point at which it stops, and requests then receive 410 Gone. The arrow between the two stages carries a condition as well as a date, because the provider should measure traffic per version and per client and contact the remaining users before switching the old version off. The same expand-and-contract sequence, adding the new form, migrating every user, and only then removing the old form, is the one zero-downtime database migrations use.
§10 · Traffic control
Rate limits and quotas
The last part of the contract states what limits apply to each client and how they are enforced. Limits belong in the contract because clients must be designed to stay within them and to recover when they exceed them.
Rate limiting caps how many requests a client may make over time. The common algorithm is the token bucket, which comes from network traffic engineering: each client has a bucket that refills at a fixed rate of r tokens per second up to a capacity of b tokens, and each request consumes one token, so a request that finds the bucket empty is rejected. The capacity b is the burst size, the number of requests a client can send at once after a period of idleness, and the rate r bounds its sustained traffic. Over any interval of t seconds a client can send at most b + r·t requests. The two parameters are kept separate because real traffic is uneven: one page load in an app may trigger a dozen calls within a few hundred milliseconds while the client's average rate stays low. A limit over a longer period, such as 10,000 requests per day, is usually called a quota; it controls total consumption rather than instantaneous load, and many APIs apply both.
On the contract side, a rejected request receives 429 Too Many Requests, defined in RFC 6585, with a Retry-After header saying when to try again. Many APIs also report the client's remaining allowance on every response; the IETF's httpapi working group has a draft standardising these as RateLimit header fields, while many providers still use their own X-RateLimit-* names. The contract should also state what a limit is keyed on, which may be an API key, a user, an IP address or an endpoint, and whether expensive operations cost more than one token.
Worked examplewhat a token bucket admits
Consider an API that allows 100 requests per second with a bucket of 200. The calculation below traces what one client can send and how a common implementation mistake changes it.
A client that has been idle has a full bucket of 200 tokens and can send 200 requests at once.
Over t seconds it can send at most 200 + 100t requests. In the first second that is 200 + 100 × 1 = 300 requests; over 10 seconds it is 200 + 100 × 10 = 1,200.
After emptying the bucket, the client must be idle for 200 ÷ 100 = 2 seconds to refill it completely.
Assumption: the API runs on 4 instances behind a load balancer, and each instance enforces the limit with its own local bucket instead of a shared one.
Each instance admits 100 requests per second with a burst of 200, so a client whose requests are spread across all four can sustain 4 × 100 = 400 requests per second, burst 4 × 200 = 800, and send 4 × 300 = 1,200 requests in its first second.
The check on step 5 is that it is step 2 multiplied by 4: 4 × (200 + 100 × 1) = 1,200. The effective limit grows with the number of instances, so scaling the service out silently loosens every client's limit. A global limit needs shared state, typically a counter in Redis updated atomically per request, which costs a network hop, or an approximation in which each instance enforces its share of the limit. The burst size also has to be chosen against the capacity behind the limiter and not only against one client's needs: if 1,000 clients with a burst of 50 reconnect together after an outage, they produce 1,000 × 50 = 50,000 requests almost at once.
Review
Common mistakes
Each mistake below is set out in the same four parts: what goes wrong, why the mistake is easy to make, what to do instead, and the section that explains the fix.
Treating the endpoint list as the whole API
What goes wrong
The list says nothing about the behaviour that fails in production: duplicate effects from retries, lists that skip or repeat items, lost updates and limits nobody stated.
Why it happens
The HLD step of an interview, and the first draft of most real designs, legitimately stops at endpoints, methods and response shapes, and that level of detail feels complete.
What to do instead
Treat the endpoint list as the first layer of the contract and answer, for each operation that matters, the behavioural questions: what a retry does, how a list is paged, how concurrent updates interact, what errors mean and what limits apply. In an interview, go into those details where they change the design, such as idempotency for payments or cursors for a feed.
A key generated per attempt deduplicates nothing, and a table that records only that a key was seen blocks the duplicate but leaves the client that timed out without the response it lost.
Why it happens
Both versions pass a simple test in which one request is sent twice with a pause in between.
What to do instead
Generate the key once on the client and reuse it on every retry, scope it to the account and operation, and store it atomically with the effect, together with the first response's status and body and a fingerprint of the request.
Deep pages read and discard every skipped row, and inserts or deletes during paging make items repeat or disappear. A cursor on a non-unique column has a similar fault: rows that share a value at a page boundary are skipped or shown twice.
Why it happens
LIMIT and OFFSET are the first pagination tool most developers learn, and the problems only appear at depth or under concurrent writes, which small test datasets do not exercise.
What to do instead
Use keyset pagination on a sort key made unique with a tiebreaker such as id, exposed through an opaque cursor, and keep offsets for small or stable collections where users need page numbers.
A new enumeration value breaks clients with exhaustive switches, tighter validation breaks clients that sent what used to be accepted, and Hyrum's law means that even undocumented behaviour has dependants.
Why it happens
Additions are harmless for tolerant readers, and providers reason about the clients they intended rather than the clients that exist.
What to do instead
State in the contract from the start that clients must ignore unknown fields and handle unknown enumeration values, classify each change against the list of breaking changes, and measure per-version usage before removing anything.
The questions that follow mix recall, calculation and application across the whole guide. Each answer is collapsed beneath its question; open it once you have worked out your own answer.
Question 1 · recall
Which HTTP methods are idempotent, and why does a second DELETE /orders/9 that returns 404 not contradict the claim that DELETE is idempotent?
Answer
GET, HEAD, OPTIONS, PUT and DELETE are idempotent; POST and PATCH are not in general. RFC 9110 defines idempotency by the intended effect on server state, not by the response. After one DELETE the order is gone, and after two it is still gone, so the effect is the same; the different status code reports the current state and does not change it. Returning 204 on the repeat is an equally conforming choice that makes retries indistinguishable from first attempts, and the contract should state which one the API uses.
Question 2 · calculation
A request passes through four services, and each of the four callers on the path makes up to 2 attempts at the next hop. The base load is 500 user requests per second. If the deepest service fails every call, how many calls per second does it receive, and what would a single retrying layer with a 10% retry budget reduce that to?
Answer
With k retrying layers making n attempts each, the deepest service receives up to n^k calls per user request. Here that is 2^4 = 16, so 500 × 16 = 8,000 calls per second against a failing service. Restricting retries to one layer gives at most 2 calls per user request, or 1,000 per second, and a 10% retry budget caps the total at 500 + 0.10 × 500 = 550 calls per second.
Question 3 · calculation
An export job pages through 50,000 rows, 100 rows per page, using offset pagination. What offset does page 500 use, how many rows does that page read, and how many rows does the whole export read compared with keyset pagination?
Answer
There are 50,000 ÷ 100 = 500 pages. Page 500 uses an offset of (500 − 1) × 100 = 49,900 and reads 49,900 + 100 = 50,000 rows to return 100. Page k reads 100k rows, so the export reads 100 × (1 + 2 + … + 500) = 100 × (500 × 501 ÷ 2) = 100 × 125,250 = 12,525,000 rows. Keyset pagination reads 500 × 100 = 50,000 rows, so offsets cost 12,525,000 ÷ 50,000 = 250.5 times as much.
Question 4 · calculation
A token bucket allows 20 requests per second with a burst of 60. How many requests can an idle client send in its first 5 seconds? If the service runs on 3 instances that each enforce the limit locally, what sustained rate and what 5-second total can a client reach?
Answer
With the bound b + r·t, the client can send 60 + 20 × 5 = 160 requests in 5 seconds. With three local buckets and requests spread across instances, the sustained rate is 3 × 20 = 60 requests per second and the burst is 3 × 60 = 180, so the 5-second total is 3 × 160 = 480, three times the intended limit.
Question 5 · application
A mobile client sends POST /payments with Idempotency-Key: K and a body charging £40. Describe the server's response in each of the following cases.
The connection drops, and the client retries with the same key and body after the first request has finished successfully.
Answer
The server finds the key row in the completed state with a matching fingerprint and replays the stored 201 status and body verbatim, so the client learns the payment exists and no second charge is made.
The retry arrives while the first request is still being processed.
Answer
The key row is in_flight, so the server answers 409 Conflict, or waits briefly and re-checks; it must not start a second charge. The client retries later and receives the replayed result.
Because of a client bug, the same key arrives with a body charging £400.
Answer
The fingerprint does not match the stored one, so the server answers 422 Unprocessable Content. Replaying the £40 result would tell the client that a £400 charge succeeded when it was never made.
The same key arrives three days later, after the server's 24-hour dedup window.
Answer
The key has been pruned, so the request is treated as new and a second charge is made, which is why the window must exceed the longest client retry horizon and why the contract must state the window and this behaviour.
Question 6 · open-ended, combining subtopics
Design the order API for an online shop that has a web client, iOS and Android apps, and an internal warehouse service. Cover the surface and style, order placement, payment confirmation, order history and one change you expect to make later.
Answer
A complete answer combines the subtopics as follows.
Surface and style: name the entities first, Customer, Order, OrderItem, Product and Payment, then expose REST over HTTP to the three customer-facing clients, with POST /orders, GET /orders/{id}, GET /customers/{id}/orders and POST /orders/{id}:cancel or a cancellations sub-resource; use gRPC between the order service and the warehouse service, where both sides are internal and generated code enforces the contract. If the three clients' screens diverge, a GraphQL layer in front of the services is an option, with query cost limits.
Order placement: POST /orders is not idempotent, so require an Idempotency-Key generated once per checkout attempt, scoped to the customer, stored with the response and a fingerprint, and kept for a stated window such as 24 hours. A client-generated order identifier could serve as a natural key with a unique constraint instead, which is the cheaper mechanism when the client can supply an identity.
Payment confirmation: the payment provider reports outcomes by webhook, so the receiving endpoint verifies signatures, deduplicates on the provider's event identifier and reconciles periodically; if placing an order triggers slow work, POST /orders can return 202 Accepted with an operation resource the apps poll.
Errors and concurrency: return problem details with stable type URIs such as insufficient-stock, mark 429 and 503 as retryable with Retry-After, and protect address or quantity edits with ETag and If-Match, answering 412 on a stale version.
Order history: GET /customers/{id}/orders uses keyset pagination on (created_at, id) with an opaque cursor, because the list grows and changes while a user scrolls.
Evolution and limits: state from the start that clients must ignore unknown fields and handle unknown order statuses, so that adding a status such as partially_shipped is not breaking; version breaking changes in the path or by date and retire old versions with Deprecation and Sunset headers; and apply a per-customer token bucket enforced with a shared counter, returning 429 with Retry-After.
Finish
Review checklist
Without consulting notes, you should be able to define an API contract and explain why it costs more to change than the code behind it; say how much of the contract to specify at the HLD and LLD stages; list the safe and idempotent HTTP methods and explain why idempotency is defined by effect rather than by response; derive an API surface from core entities and explain why it comes before the data model; compare REST, gRPC, GraphQL and events and describe the 202 Accepted long-running operation pattern; sort failures into permanent, transient and ambiguous groups and write a problem-details body; calculate retry amplification as n^k and explain how single-layer retries, retry budgets and deadline propagation bound it; state the rules for a correct idempotency key, draw its three states with the response for each, and size a dedup window; prevent lost updates with ETag, If-Match and 412; calculate the rows read by offset and keyset pagination and show how offsets repeat or skip items when the list changes; classify a change as breaking or not and describe the deprecation and sunset lifecycle; and calculate what a token bucket admits over a period, including the effect of enforcing it per instance. A reader who can do all of these has covered the material.