API design: the contract the boxes have to honour
The interface you write in minute ten is the contract every later box must honour, so it is worth getting the parts interviewers check right: resources and verbs with their real semantics, the case for GraphQL or gRPC, pagination that survives concurrent writes, idempotency keys, honest status codes, versioning, and where authentication and the API gateway sit.
What you'll be able to do
- Write a resource-oriented interface whose methods mean what HTTP says they mean, including which ones are idempotent
- Say when GraphQL or gRPC is a better fit than REST, in terms of who the client is and what it needs
- Show why offset pagination duplicates and skips rows under concurrent writes, and replace it with a keyset cursor
- Design idempotency keys, error responses and versioning so retries and old clients are safe
Before this: the-delivery-framework
The interface is the shortest step in the round and the one interviewers lean on most when they want to know whether you have built real services. Five endpoints on a whiteboard reveal a lot: whether identity comes from a token or from a field anyone can forge, whether a retried payment charges twice, whether the list call works for the customer with forty thousand rows.
You do not need to produce an OpenAPI spec. You need about five calls that are each right in the handful of ways that matter, and the vocabulary to defend them when asked. This lesson is that handful.
Resources and verbs, with their real semantics
REST in an interview means: nouns in the path, the HTTP method says what happens to them. Your core entities from the previous step become the nouns.
| Call | Meaning | Safe | Idempotent |
|---|---|---|---|
GET /orders/{id} | Read one order | yes | yes |
GET /orders?cursor=... | List orders, one page | yes | yes |
POST /orders | Create an order | no | no |
PUT /orders/{id}/address | Replace the address with this one | no | yes |
PATCH /orders/{id} | Change some fields | no | not by default |
DELETE /orders/{id} | Remove (or cancel) the order | no | yes |
The last two columns come from RFC 9110, and they are what an interviewer is really asking about when they say "is that endpoint safe to retry?". Safe means the client is not requesting any change. Idempotent means sending the same request twice has the same intended effect as sending it once. PUT is idempotent because "set the address to X" twice leaves the address at X. POST is not, because "create an order" twice creates two orders. That single fact is why the payment and order creation calls are the ones that need extra design.
Three conventions that read well:
- Plural nouns and nesting only for ownership.
/restaurants/{id}/tablesis fine; deep paths like/users/{u}/orders/{o}/items/{i}/notesare a sign you want a top-level resource. - Actions that are not CRUD get a sub-resource. Cancelling is
POST /orders/{id}/cancel, not aGETwith a side effect. AGETthat changes state will eventually be triggered by a link prefetcher or a crawler. - Identity from the token. The acting user is whoever the
Authorizationheader says. NeverPOST /orders {"user_id": 42}.
When REST is not the answer
REST is the default because every client, proxy and cache understands it. Two alternatives are worth naming, each with the condition that justifies it.
GraphQL wins when the client is a UI that needs differently shaped data on different screens and the backend is many services. One query fetches an order, its items and the courier's location in a single round trip, shaped exactly as the screen needs. The costs are real: HTTP caching by URL mostly stops working (queries go as POST), a single expensive query can fan out across every backend, so you need query cost limits, and authorization has to be enforced per field rather than per endpoint.
gRPC wins between services you own. It uses HTTP/2, a binary encoding from a schema (protocol buffers), generated clients in many languages, deadlines that propagate, and streaming in both directions. Payloads are smaller and parsing is cheaper than JSON. It is a poor fit for browsers without a proxy layer, and its binary payloads are harder to inspect.
The common real-world shape, and a good thing to say, is REST or GraphQL at the edge, gRPC inside. The public contract stays easy to consume; internal calls get schemas and deadlines.
Pagination that survives writes
Every list endpoint needs a page size limit and a way to ask for the next page. There are two ways to ask, and the difference is a classic probe.
Offset pagination says "skip the first N rows, give me the next 20": ?offset=40&limit=20. It is simple, it lets a UI jump to page 7, and it has two defects. The database still reads and discards the skipped rows, so page 5,000 is slow. And if rows are inserted or deleted between two requests, the window shifts underneath the reader.
Keyset (cursor) pagination says "give me 20 rows after the last one I saw": the server returns an opaque cursor encoding the last row's sort key, and the next query is WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 20. With an index on that sort key, every page costs the same, and concurrent writes cannot shift it.
1Watch offsets break, and cursors not▾
The cell builds a newest-first list of ten items, reads page one, changes the data, then reads page two. It does this twice for each method: once with a new item inserted at the top, once with an item the reader has already seen deleted.
// A newest-first list, page size 3. Between page 1 and page 2, the data changes.
const PAGE = 3;
const desc = (xs) => [...xs].sort((a, b) => b - a);
const offsetPage = (rows, offset) => desc(rows).slice(offset, offset + PAGE);
// Equivalent to: WHERE id < :before ORDER BY id DESC LIMIT 3
const keysetPage = (rows, before) =>
desc(rows.filter((r) => before === null || r < before)).slice(0, PAGE);
function run(change, paginate) {
const rows = Array.from({ length: 10 }, (_, i) => i + 1);
const p1 = paginate(rows, null);
if (change === "insert") rows.push(11); // a new item lands at the top
else rows.splice(rows.indexOf(9), 1); // an item already seen is deleted
const p2 = paginate(rows, p1);
const seen = [...p1, ...p2];
const dup = [...new Set(seen.filter((r) => seen.indexOf(r) !== seen.lastIndexOf(r)))];
const skip = rows.filter((r) => r > Math.min(...p2) && r < Math.max(...p1) && !seen.includes(r));
return [p1, p2, dup, skip];
}
const byOffset = (rows, p1) => offsetPage(rows, p1 === null ? 0 : PAGE);
const byCursor = (rows, p1) => keysetPage(rows, p1 === null ? null : p1[p1.length - 1]);
for (const [name, paginate] of [["offset", byOffset], ["cursor", byCursor]]) {
for (const change of ["insert", "delete"]) {
const [p1, p2, dup, skip] = run(change, paginate);
console.log(`${name} ${change}: [${p1}] then [${p2}] dup=[${dup}] skipped=[${skip}]`);
}
}
# A newest-first list, page size 3. Between page 1 and page 2, the data changes.
PAGE = 3
def offset_page(rows, offset):
return sorted(rows, reverse=True)[offset:offset + PAGE]
def keyset_page(rows, before=None):
# Equivalent to: WHERE id < :before ORDER BY id DESC LIMIT 3
older = sorted((r for r in rows if before is None or r < before), reverse=True)
return older[:PAGE]
def run(change, paginate):
rows = list(range(1, 11))
p1 = paginate(rows, None)
if change == "insert":
rows.append(11) # a new item lands at the top
else:
rows.remove(9) # an item the reader already saw is deleted
p2 = paginate(rows, p1)
seen = p1 + p2
duplicated = sorted({r for r in seen if seen.count(r) > 1})
skipped = [r for r in rows if min(p2) < r < max(p1) and r not in seen]
return p1, p2, duplicated, skipped
by_offset = lambda rows, p1: offset_page(rows, 0 if p1 is None else PAGE)
by_cursor = lambda rows, p1: keyset_page(rows, None if p1 is None else p1[-1])
for name, paginate in (("offset", by_offset), ("cursor", by_cursor)):
for change in ("insert", "delete"):
p1, p2, dup, skip = run(change, paginate)
print(f"{name} {change}: {p1} then {p2} dup={dup} skipped={skip}")
offset insert: [10, 9, 8] then [8, 7, 6] dup=[8] skipped=[] offset delete: [10, 9, 8] then [6, 5, 4] dup=[] skipped=[7] cursor insert: [10, 9, 8] then [7, 6, 5] dup=[] skipped=[] cursor delete: [10, 9, 8] then [7, 6, 5] dup=[] skipped=[]
One insert at the top and the offset reader sees item 8 twice. One delete of something already read and the offset reader never sees item 7 at all, with no error to tell anyone. In a feed that is a small annoyance; in an export job or a sync client it is silently lost data. The cursor reader gets the right next page in both cases, because "older than 8" does not depend on how many rows sit above it.
Two details make a cursor production-ready. Sort by a unique key, or add the id as a tiebreaker, because two rows with the same created_at will otherwise be skipped or repeated at a page boundary. And make the cursor opaque (base64 of the sort values, ideally signed), so clients cannot construct one and you can change what is inside it later. The cost to state honestly: no jumping to page 7. For infinite scroll, sync and exports, nobody needs it.
Idempotency keys for the calls that must not repeat
A mobile client sends POST /payments, the server charges the card, and the response is lost on a flaky connection. The client cannot tell whether the charge happened, so it retries. Without help, the customer pays twice.
The fix is an idempotency key: a unique value the client generates once per logical operation (a UUID made when the user taps Pay) and sends in a header on every attempt. The server keeps a table keyed by it.
- On arrival, try to insert
(key, request_hash, status='in_progress'). A unique constraint makes this atomic. - If the insert succeeded, do the work, then store the response against the key.
- If the key already exists with a stored response, return that response without doing the work again. If it exists and is still in progress, return
409so the client waits and retries. - If the key exists with a different request body, reject it: the client has a bug.
- Expire keys after a window longer than any client's retry horizon, commonly 24 hours.
The key must come from the client, not the server, because only the client knows that two attempts are the same intent. A server-generated id on each request is just a new request.
Errors, status codes and versioning
Status codes are for machines. The client's retry logic reads them, so pick them carefully:
| Code | Meaning to the client | Retry? |
|---|---|---|
| 400 | Your request is malformed | no |
| 401 | Who are you? (missing or invalid credentials) | after re-authenticating |
| 403 | I know who you are, and you may not | no |
| 404 | No such resource (or you may not know it exists) | no |
| 409 | Conflicts with current state (duplicate, version mismatch) | after re-reading |
| 422 | Well formed, but fails validation | no |
| 429 | Too many requests, see Retry-After | yes, after the delay |
| 500 | Our bug | maybe, with backoff |
| 503 | Overloaded or down, see Retry-After | yes, with backoff |
Return a consistent error body too. RFC 9457 ("problem details") defines one: a type URI, a title, the status, a human-readable detail, plus your own fields such as a request id for support. One shape for every error means one parser in every client.
Versioning exists because mobile apps you shipped two years ago are still calling you. The cheapest strategy is to never break compatibility: add fields, never remove or rename them, and make clients ignore fields they do not recognise. When a break is unavoidable, put the major version in the path (/v2/orders) so it is visible in logs and routable at the gateway, run both versions side by side, and measure traffic on the old one before turning it off.
Authentication, authorization and the gateway
These are two different questions and candidates often blur them. Authentication asks who is calling. Authorization asks whether that caller may do this to this resource.
For authentication, the two common shapes are a session (an opaque id in a cookie, looked up in a session store on each request, easy to revoke) and a signed token such as a JWT (claims plus a signature, verified without a lookup, hard to revoke before it expires). A sensible default for a product prompt: short-lived access tokens (minutes) plus a refresh token held more carefully, which bounds how long a stolen token is useful. For third parties acting on a user's behalf, OAuth 2.0 is the standard, and naming it is enough.
Authorization lives in the service that owns the data, because only it knows that order 812 belongs to user 42. A gateway can check "this token is valid and has the orders:read scope"; it cannot check ownership of a specific row without becoming a copy of every service.
That boundary is the honest description of an API gateway. It sits at the edge, in front of your services, and does the work every request needs and no service wants to repeat: TLS termination, token validation, coarse rate limiting per client, routing by path and version, request size limits, and request ids for tracing. It should not contain business logic. In an interview, draw it as one box at the edge, list two or three of those jobs, and move on; the interesting decisions are behind it.
The checklist
- Nouns from your entities in the paths, methods used for what they mean, and no
GETwith a side effect. - Identity taken from the token; ownership checked in the service that owns the data.
- Every non-idempotent create or charge accepts a client-generated idempotency key, stored durably with the result.
- Every list is cursor-paginated on a unique sort key, with a page size cap.
- Status codes chosen so the client's retry logic does the right thing, with one error shape.
- A versioning rule (additive changes only; a path version for real breaks) and a gateway doing edge concerns only.