API Design

How to design a REST API with pagination, idempotency keys, versioning and errors, when RPC, GraphQL or events fit better, and what interviewers ask.

18 minLesson 5 of 6
On this page
  1. Where the API sits
  2. REST resources and methods
  3. Idempotency keys
  4. Pagination
  5. Error responses
  6. Versioning
  7. When REST is not the best fit
  8. Concurrent updates to the same resource
  9. In the interview
  10. What to practise next

An API is the contract between a service and its clients: which requests a client may send, what each request does, and what comes back. In an interview, designing the API means choosing the resources, the request style, how long lists are paged, how failed requests are retried safely, how errors are reported and how the API changes over time. These are the parts that are expensive to change once clients depend on them.

Without these decisions, ordinary network behaviour turns into bugs. If a phone sends a booking request and loses signal before the reply arrives, the app times out and retries, and a server that treats every request as new creates a second booking. A list that is paged by position shows the same item twice when a new item is added between two page loads.

Where the API sits

Clients call the public API through a gateway; services call each other with RPC or publish events to a queue.Mobile app / browser to API gateway (REST over HTTPS); API gateway to Reservation service (RPC); Reservation service to Database; Reservation service to Event queue (publish event), asynchronous.Mobile app /browserAPI gatewayReservationserviceDatabaseEvent queueREST over HTTPSRPCpublish event

request and replyasynchronous message

Clients call the public API through a gateway; services call each other with RPC or publish events to a queue.

The examples in this lesson use a restaurant reservation service where diners search for free times, book a table and list their bookings.

REST resources and methods

In a REST API the URL names a thing, such as a reservation or a restaurant, and the HTTP method says what to do with it. Use plural nouns for collections (/reservations) and put the id after the collection (/reservations/r-5521). A verb in the URL, such as /createReservation, is a sign that the resources were not worked out, because the method already is the verb.

The methods differ in how safe they are to repeat. GET only reads, so repeating it changes nothing. PUT replaces a resource with the body you send and DELETE removes it, so doing either twice leaves the same state as doing it once. POST creates a new resource each time, so repeating it creates a second one. This difference decides which calls need the idempotency keys described below.

For updates, PUT sends the whole resource and replaces it, while PATCH sends only the fields that change. PATCH suits large resources because clients do not have to resend, and accidentally overwrite, fields they did not touch. A successful create returns 201 with the new resource or its URL, and a successful delete with nothing to return uses 204. Filters go in query parameters.

Reservation API, version 1
GET    /v1/restaurants/{id}/availability?date=2026-12-04&party_size=4
         200  { "slots": [ { "time": "19:00", "tables_free": 2 }, ... ] }
 
POST   /v1/reservations          Idempotency-Key: 6f1c...e2
         body { "restaurant_id": 42, "time": "...", "party_size": 4 }
         201  { "id": "r-5521", "status": "confirmed" }
         409  slot_taken     422  invalid_party_size     429  rate_limited
 
GET    /v1/reservations/{id}                  200 | 404
DELETE /v1/reservations/{id}                  204 | 404
GET    /v1/users/me/reservations?limit=20&cursor=...
         200  { "items": [ ... ], "next_cursor": "eyJ0IjoiMjAyNi0..." }

The client sends a time and a party size, and the server chooses which table to assign. A blind retry would therefore book a second table, which is why the booking call needs a key.

Idempotency keys

An idempotency key lets a client retry a request that changes data without the change happening twice. The client generates a unique key, usually a random UUID, once for each user action, for example when the diner taps "Book", and sends it in a header with every attempt of that action. The server stores each key together with the response it produced. When a request arrives with a key it has already seen, the server returns the stored response and does not run the action again.

A booking, a lost reply, a safe retryUse the arrows or ← → keys
  1. A booking, a lost reply, a safe retry, step 1Diner's phone to Reservation API (POST /reservations); Reservation API to Reservations DB (one transaction).Diner's phoneReservation APIReservations DBPOST /reservationsone transaction
    key
    6f1c
    bookings
    0

    1The diner taps Book. The app creates key 6f1c and sends it in the Idempotency-Key header.

  2. A booking, a lost reply, a safe retry, step 2Diner's phone to Reservation API (POST /reservations); Reservation API to Reservations DB (one transaction).Diner's phoneReservation APIReservations DB6f1c → r-5521POST /reservationsone transaction
    key
    6f1c
    bookings
    1

    2In one transaction the API inserts the key (only if it is absent), books table 7 and stores the response. A crash leaves all three or none.

  3. A booking, a lost reply, a safe retry, step 3Diner's phone to Reservation API (POST /reservations); Reservation API to Reservations DB (one transaction).Diner's phoneReservation APIReservations DBPOST /reservationsone transaction
    key
    6f1c
    bookings
    1

    3The reply is lost on the way back. After a timeout the app cannot know whether the booking happened.

  4. A booking, a lost reply, a safe retry, step 4Diner's phone to Reservation API (POST /reservations); Reservation API to Reservations DB (one transaction).Diner's phoneReservation APIReservations DBPOST /reservationsone transaction
    key
    6f1c
    bookings
    1

    4The app retries with the same key and the same body. A new key here would book a second table.

  5. A booking, a lost reply, a safe retry, step 5Diner's phone to Reservation API (POST /reservations); Reservation API to Reservations DB (one transaction).Diner's phoneReservation APIReservations DB6f1c seenPOST /reservationsone transaction
    key
    6f1c
    bookings
    1

    5The key insert finds 6f1c already stored, so nothing is booked.

  6. A booking, a lost reply, a safe retry, step 6Diner's phone to Reservation API (POST /reservations); Reservation API to Reservations DB (one transaction).Diner's phoneReservation APIReservations DBPOST /reservationsone transaction
    key
    6f1c
    bookings
    1
    status
    201

    6The API replays the stored 201 response with r-5521. The result is one booking and one table.

1 / 6

The key is stored in the same database transaction as the booking. In a separate cache, a crash between the two writes would leave a booking with no key, and the retry would book again.

Three details come up in interviews. If a retry arrives while the first attempt is still running, the second request must not run in parallel, so the first attempt claims the key row before doing any work, and the second waits or receives a "request in progress" error. If the same key arrives with a different body, the client has a bug, and the server rejects the request with a 422 instead of replaying an unrelated response. Keys are kept for longer than any client keeps retrying, typically 24 hours. Idempotency and retries covers this in more depth.

Pagination

An endpoint that returns a list must return it in pages, because the list can grow without limit and a single response with every item would be slow and large. There are two common ways to ask for the next page.

Offset pagination

The client sends ?offset=40&limit=20, and the server sorts the list, skips 40 items and returns the next 20. It is simple, and it lets a user jump straight to page 37.

It has two problems. If an item is added or removed while the user is paging, every later item shifts by one position, so the next page repeats an item the user has already seen or skips one. The second problem is cost: to return rows 100,000 to 100,019, the database still reads and discards the first 100,000 rows, so each page is slower than the one before it. Offset paging suits small, stable lists.

Cursor pagination

The response includes a next_cursor, an opaque token that encodes the sort key of the last item returned, for example its (created_at, id). The client sends the token back to get the next page, and the server asks the database for the items after that key. An index on the sort columns answers this directly, so every page costs the same no matter how deep it is, and a new item inserted elsewhere in the list does not shift the pages.

The query behind a cursor
SELECT * FROM reservations
WHERE user_id = 7
  AND (created_at, id) < ('2026-11-02 18:40:00', 'r-5521')   -- values decoded from the cursor
ORDER BY created_at DESC, id DESC
LIMIT 21;   -- one extra row tells the server whether another page exists

Two details matter. The sort must end with a unique column such as the id, because otherwise items with the same timestamp can be skipped or repeated at a page boundary. And the client cannot jump to page N. Cursor pagination is the usual answer for any list that grows.

Error responses

The HTTP status code gives the category of the failure and the response body gives the detail. A 4xx status means the client sent something that must change before the request can succeed: 400 or 422 for an invalid request, 404 for a missing resource, and 409 when the request conflicts with the current state, such as booking a slot that was just taken. A 5xx status means the server failed, and 429 means the client is sending too many requests. Both may succeed on a later retry, and 429 should carry a Retry-After header. A request with missing or invalid credentials gets 401, and a request from a caller who is known but not allowed to do this gets 403. Rate limiting covers how the server decides to send a 429.

The body should have a stable shape that programs can read, for example {"error": {"code": "slot_taken", "message": "Table 7 was just booked", "retryable": false}}. The client reacts to the code, for example by offering other times, and uses retryable to decide whether to retry.

Versioning

Adding a field to a response is safe, because clients ignore fields they do not know. Removing a field, renaming it or changing its meaning breaks existing clients, and mobile apps stay installed for years. A breaking change therefore needs a new version. The most common approach is to put the major version in the path, as in /v1/reservations, because it is easy to see and route. Run both versions side by side until the old one has little traffic left, then retire it.

The alternative is to send the version in a request header, which keeps URLs stable but is harder to see in logs and to test from a browser. Whichever you choose, announce the retirement date of an old version ahead of time.

When REST is not the best fit

REST over HTTP is the default for public APIs. The alternatives below fit specific situations,.

RPC and gRPC

In an RPC style, the client calls a named operation on a server, such as ReserveTable(request), and the request and response types are defined in a schema file. A framework such as gRPC generates typed client and server code from that schema and sends compact binary messages over a persistent HTTP/2 connection. It fits high-volume calls between your own services, because it is faster than JSON and catches contract mismatches at build time. Browsers cannot call it without a proxy, and third parties expect REST.

GraphQL

With GraphQL the server publishes one endpoint and a typed schema, and the client sends a query that lists exactly the fields it wants, including related objects. It fits an API whose many clients need different shapes of the same data. It costs more on the server: a client can write an expensive query, so you need depth and cost limits, and plain HTTP caching of GET requests no longer works because every request is a POST to one URL.

Events

Sometimes nobody needs a reply. When a booking is confirmed, the email service and the analytics pipeline need to know, but the booking request should not wait for them. The reservation service publishes a "booking confirmed" event to a queue or stream, and each consumer reads it on its own schedule. The cost is that there is no direct response, and consumers must handle receiving the same event twice.

Concurrent updates to the same resource

Two users editing the same record can silently overwrite each other if each sends a full update. The fix is optimistic concurrency: the server returns a version number or an ETag with the resource, the client sends it back in an If-Match header with the update, and the server rejects the update with 412 (or 409) if the version has changed.

In the interview

Name the two or three core calls in a sentence each, then spend your words on the one decision that changes the design. Choose REST by default, cursor pagination for any list that grows, and an idempotency key for any call that creates something and that clients retry.

Questions to expect:

  • "Who generates the idempotency key?" The client generates it, once per user action and before the first attempt. A key made by the server cannot recognise a retry, because the client never received it.
  • "Offset or cursor pagination?" Cursor for anything that grows or changes while it is read, because the pages stay correct and every page costs the same. Offset only for small, stable lists or when the user must jump to a page number.
  • "How do you change the API without breaking clients?" Make additive changes whenever possible, because clients ignore new fields. For a breaking change, add a new major version in the path, run both versions together and retire the old one when its traffic is gone.
  • "How do you retry a request that returned a 5xx or timed out?" The client retries with exponential backoff and random jitter, so that many clients do not retry at the same moment, and it sends the same idempotency key on every attempt. It stops after a few attempts. A 4xx response other than 429 is not retried, because the same request will fail again.
  • "What if the operation takes a long time, such as generating a report?" The server accepts the request, returns 202 with the URL of a status resource, and does the work in the background. The client polls that URL, or the server calls a webhook or publishes an event when the work is done.
Defending the booking endpointStrong answer
Interviewer

Why not just check for a duplicate reservation before inserting?

You

The original request and a retry can both run the check at the same time, find nothing, and both insert. An idempotency key identifies exactly which request is a retry, and I store it in the same transaction as the booking with a unique constraint, so only one of the two can succeed.

Interviewer

What does the second request return?

You

If the first one has finished, it gets the stored response, the same 201 and the same reservation id. If the first one is still running, it gets a "request in progress" error and retries after a short delay.

Quick check

A list is paged with offset, 20 per page. A diner reads page 1, a new item is added at the top, then they load page 2. What do they see?

Which request is safe for a client to retry with no extra mechanism?

Where should the idempotency key be stored?

What to practise next

Data Modeling turns these endpoints' queries into tables and keys, and Idempotency and Retries goes deeper into making repeated requests safe.