API design
Read first: Networking for request paths, Idempotency and the exactly-once myth
A good API tells the client what a second attempt will do. REST resources with idempotent methods, cursor pagination, and versions that only add fields are the default. GraphQL buys one round trip and spends it on N+1 queries and a cache key that is no longer the URL, and gRPC belongs on the inside of the system.
An API is a promise about a second attempt. The caller will retry, because networks drop the response after the server has already done the work. Your job is to make that retry safe, to make a long list readable without lying, and to change the contract by addition so yesterday’s client still runs. The protocol, REST or GraphQL or gRPC, is how the promise is carried. It is not a substitute for the promise.
Core concepts
Resources and methods. REST, for interview purposes, means resources with a stable identity and a small set of methods whose retry behavior you can state. GET reads and does not change state. PUT replaces the resource with the body you sent, so sending it twice leaves the same state. DELETE removes it, so deleting it twice leaves it gone. Those three are idempotent. The effect of doing them twice is the effect of doing them once. POST appends a new action. Two identical POST requests are two actions unless you add a key that makes the second one a lookup of the first.
That key is the imposed form of idempotency. The client generates it. The server stores it with the outcome and, on a retry, returns the stored outcome. Stripe’s idempotency writeup is the pattern to steal: also store a fingerprint of the parameters, so the same key with a different body is an error, and lock concurrent retries so two workers do not both run. Natural idempotency is better when you can get it. “Set the shipment state to shipped” is safe to repeat. “Add one to the shipment count” is not, unless the key makes the second add a no-op.
Pages. Offset pagination asks for “20 rows, skipping the first 10,000.” The store still walks the skipped rows, and a live list shifts under you. An insert at the top of a time-ordered list pushes every later row down by one, so the next offset repeats a row you already showed. A delete at the top pulls rows up, so the next offset skips one. Cursor pagination asks for “20 rows after this key.” The key is the last sort value you returned, and the sort has a tie-breaker so the key is unique. New rows arrive on the side of the cursor you have not walked, or on a later refresh. They do not reshuffle the page boundary. Once the list is large or live, cursors are the page. Offsets are a convenience for a small, stable table.
Versions. Version by addition. New fields appear. Old clients ignore fields they do not know, which means you told them to, and your decoders actually do that. Removing a field, renaming it, or changing the meaning of an existing value is a break. A new required input with no default is a break for writers. A path prefix with a new major version is what you do when addition cannot express the change, and you run both until the callers you know about have moved. You do not get to call a rename a minor cleanup.
GraphQL gives the client one round trip and a shape the client chooses. The client names the fields. The server resolves them. That removes the choice between a fat resource the client did not want and three REST calls the client had to sequence. The costs are specific. Query complexity: one request can ask for a tree that is a join of the whole database, so you need a cost limit. Caching is harder than a URL. A CDN cache key is usually the URL plus selected headers, from the DNS and CDNs material. A GraphQL query is often a POST to one path, so every distinct question shares one URL and the cache cannot see the selection. N+1 resolver calls: a list of parents, and a child resolver that loads one row per parent, turns one request into one query plus one query per row.
gRPC fits internal service-to-service calls. It is HTTP/2 plus a binary protobuf contract, with deadlines and streaming RPCs. Networking covers why HTTP/2 multiplexes streams and why a lost TCP packet still stalls every stream on that connection. The part that belongs here is the contract. You generate clients. You add fields. You do not reuse a field number for a new meaning. Deadlines are how an internal call respects the caller’s budget. A public browser client is a poor fit: you would teach every external caller your protobuf pipeline for little gain over a resource URL they can curl and cache.
Errors say what the client can do. They do not say which file threw. A stable code and a sentence are the body. The status carries the action. 400 means the same bytes will fail again, so do not retry them as-is. 401 means the credential failed, so refresh it and retry once. 403 means the credential worked and the action is forbidden, so retrying will not help. 404 means the resource is not there. 409 means the state moved, so reread and decide. 429 means slow down. 503 means the call might work later, and only a caller holding an idempotent request should try again. A stack trace fails every one of those tests. The client cannot act on a file name.
A worked example
You are listing a feed. At launch it is short, people read the top, and offset pagination is a one-line explanation. Then the feed grows, scrolls get deep, and new posts land at the top while someone is still paging. Assumptions, stated as assumptions: 2 million posts in the feed, a page size of 20, a browser round trip of 30 ms in the same country, and a database query that costs 2 ms when the connection is warm. The 30 ms figure is a planning assumption in the same spirit as a continental round trip, not a measurement of one provider. A same-datacenter round trip is Dean’s 0.5 ms and is the wrong number for a phone.
The page needs a rate, and the shape still has to avoid walking thousands of rows to render twenty. One million list requests a day:
one day 86,400 seconds
interview shortcut about 100,000 seconds
1,000,000 requests in a day 1,000,000 / 86,400 = 11.6 per second
shortcut check 1,000,000 / 100,000 = 10 per second
About 12 per second average. Peak is a multiple you must state. If you assume three times average, you are near 35 per second. This API does not need a heroic cache. It does need to avoid doing 5,000 times more work than the page contains.
Offset, the expensive way. The client asks for page 5001, which someone computed as offset 100,000, limit 20.
rows the store walks 100,000 + 20 = 100,020
rows the client can render 20
work relative to a useful page 100,020 / 20 = 5,001 times
at 2 ms per small page, naive the skip dominates, and it grows as the user goes deeper
A cursor does a seek on the sort key and reads 20. Indexes are why the seek is a descent of a B-tree rather than a walk. The API returns the last key with the page. The next call sends it back. You lose “jump to page 5001” unless you are willing to scan, which is the feature that made the offset expensive. A live feed does not have a stable page 5001 anyway.
The live-feed failure, in miniature. The feed is newest first. Page one returned the current top 20. Before the next call, one new post is inserted at the top. Offset 20 now returns the old nineteenth through the old thirty-eighth, so the old twentieth appears again and the client shows a duplicate. A cursor that says “created before the last timestamp, and id less than this id on a tie” continues from where the user stopped. The new post shows up when they refresh the top. It does not splice into the walk. As the feed grows, the same client who used to stop near the top sits at a larger offset, and the walk gets more expensive without a change to the API.
Create is the idempotent-method example. POST /orders with no key, retried after a timeout, creates two orders and may charge twice. PUT /orders/client-generated-id is naturally idempotent if the body is the whole order and the second put stores the same bytes. If you stay with POST, require a client key. The second request with the same key and the same fingerprint returns the first response, including the same order id. The same key with a different total is a 409, not a second charge.
Version the order by addition. You add currency with a default of the shop’s currency. Old clients keep reading amount. A client that renames amount to amount_cents in place has broken every caller that still reads amount. Ship amount_cents beside amount for a window you name, then remove amount in a major version once you have evidence the old field is idle. Removal is the break. Addition is the compatibility strategy.
GraphQL, same screen. The client wants the order, the buyer name, and the line items. Three serial REST calls on a cold-ish phone:
browser round trip, assumption 30 ms
three serial calls 3 * 30 ms = 90 ms of round trip, plus server time
one GraphQL call 30 ms of round trip, plus whatever the resolvers do
line items, assumption 25
queries if each resolver hits SQL 1 + 25 = 26
serial database time, assumption 26 * 2 ms = 52 ms inside that single round trip
batched child query 1 + 1 = 2 queries, about 4 ms
The round trip got smaller and the server got chattier. The fix is to batch the child lookups for the request, one query for all 25 lines, not a resolver that hides a query in a loop. The cache fix is less satisfying. You can cache the REST read of one order by its URL. You cannot hand the CDN a single GraphQL path and expect it to tell two queries apart. Cache at the field or skip the CDN for that route, and say which you chose.
Errors on this API, written as actions. Not enough inventory is 409 with code inventory_short. The client refreshes the cart. A missing idempotency key on POST is 400. The client fixes the bug, and a retry of the same broken request will not start working. A downed database is 503. The client retries only if it still holds the key and the deadline. NullPointerException in a file the client does not have is none of these. It is a log line that escaped.
gRPC stays behind the resource API. The order service calls the inventory service with a protobuf request and a deadline equal to the time left in the user’s budget. If the gateway has already spent 40 ms of a 200 ms budget, the outbound deadline starts at 160 ms and shrinks at the next hop. A fresh two-second deadline at every hop lets the inside outlive the user. That deadline is the internal API’s most important field.
flowchart LR
client[Client]
orders[Orders resource]
inventory[Inventory service]
db[Orders database]
client --> orders
orders --> db
orders --> inventory
The client sees one resource. The gRPC hop is inside, and it carries a deadline. The client does not.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| REST resource, idempotent method | A cacheable read, a retry you can explain | Several round trips when the client needs a custom shape |
| Client idempotency key on POST | A safe retry for a create | Storage for the key, a lock for concurrent retries, a fingerprint check |
| Offset pagination | Page numbers that are easy to explain | A walk of every skipped row, duplicates and skips on a live list |
| Cursor pagination | A stable walk of a live or large list | No random jump to a distant page without paying for a scan |
| Version by addition | Old clients keep working | You carry old fields until you deliberately break them |
| GraphQL | One round trip, a shape the client chooses | Query cost, N+1 resolvers, a cache key that is no longer a URL |
| gRPC inside the system | Deadlines, a generated contract, small payloads | A poor public contract for browsers, and field numbers you must not reuse |
Pick REST at the edge of a design question unless the interviewer is asking about a client that composes many shapes. Pick gRPC on the hop you control. Mention GraphQL when the product is a public graph of related objects and you are ready to talk about cost limits and the N+1. Do not pick all three for one path to show range.
Pitfalls
POSTfor a create, with the client told to retry on timeout. The symptom is two orders and two charges for one click.- Treating
DELETEas failed when the second call returns “already gone.” The state is the idempotent success. The symptom is a client that retries forever. - Offset pagination on a live feed. The symptom is duplicate items as the user scrolls, or gaps when rows are deleted above the fold.
- A deep offset defended as “the index will handle it.” The symptom is latency that grows with the page number, because the store still counts past the skipped keys.
- Renaming a field and calling it backward compatible. The symptom is a client release coupled to a server release, which means you have a distributed monolith at the contract.
- A GraphQL resolver per child row. The symptom is a request that is fast at the edge and responsible for 26 serial queries.
- Caching GraphQL by the URL path alone. The symptom is one user receiving another user’s selection, or a cache that never hits because you gave up and disabled it without saying so.
- An error body that is a stack trace. The symptom is clients matching on English sentences in a file path, and a security leak of internals, and no programmatic action.
- An internal deadline that resets at every hop. The symptom is a user who gave up while the backend is still working, then a retry that doubles that work.
In the interview
In the first five minutes, name the resource, the method, and what a retry does. “Create order is a POST with a client idempotency key. The list is a cursor on a time-ordered id, page size 20. I version by adding fields.” Then one error: “409 inventory_short tells the client to refresh, and a 503 is retried only with the same key.” That is an API. A tour of status-code trivia is not.
Skip Richardson maturity levels, a lecture on hypermedia, and a claim that GraphQL replaces authorization. The question that usually follows is “the client timed out, what do you return on the retry?” Walk the key, the stored outcome, and the fingerprint mismatch. If they ask about lists, reject offset for the live case and do the 100,020-rows arithmetic so they can see you know why.
Check yourself
A client requests offset 100000 and limit 20 against a large live feed. What work does the database do, and what bug appears if a new post is inserted at the top between pages?
The store walks about 100,020 rows to return 20, which is 5,001 times the useful page. On a newest-first feed, an insert at the top shifts every following row by one, so the next offset repeats the boundary row and the user sees a duplicate. A cursor that seeks after the last key you returned does not rescan the prefix and does not shift the window. The cost also grows as the feed grows, because a deeper scroll is a larger offset.
Why is a GraphQL response harder to cache than a REST read of one order?
A CDN cache key is the URL plus selected headers. A REST read of one order has a distinct URL per order. GraphQL often posts many different queries to one path, so the URL does not identify the selection. Two clients hitting the same path can be asking different questions. You cache inside the resolver layer, or you accept that this route is a poor cache citizen, and you still have to cap query cost.
A list resolver returns 25 line items and each item's resolver runs its own query. How many queries is that, and what is the fix?
Twenty-six queries: one for the list and one per item. That is the N+1. At an assumed 2 ms each, serial, the inside of the single round trip spends about 52 ms in the database. Batch the child keys into one query for the request. The client still sees one round trip. The server stops multiplying work by the page size.
The client retries a POST that creates an order after a timeout. What must the server have stored so the retry does not charge twice?
A client-generated idempotency key, the outcome of the first attempt, and a fingerprint of the parameters. The same key and the same fingerprint return the stored outcome. The same key with a different body is an error. Concurrent retries with that key take a lock so two workers do not both run. A natural alternative is a PUT to a client-chosen order id that writes the same state twice.
The server returns a 500 whose body is a stack trace naming a source file. What should the client have received instead?
A status and a stable code that name an action. Inventory that cannot satisfy the order is a 409 the client can refresh on. A request the server will reject forever is a 400 the client should not retry unchanged. A downed dependency is a 503, retried only when the call is idempotent and the deadline still fits. A file name is not an action.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Brandur Leach's writeup of the idempotency pattern; Marc Brooker and the AWS Builders' Library.