System designCore concepts8 min read

API Design in a System Design Interview

This lesson is for software engineers preparing for system design rounds. Right after the requirements, most interviewers expect you to sketch the API: the handful of calls the client makes to your system. A good API takes about five minutes and makes the rest of the design easier to follow. A weak one makes the interviewer stop and ask what your boxes are actually for. By the end you will be able to write a small, defensible API quickly and answer the follow-up questions it triggers.

The HTTP basics (methods, idempotency, status codes) and the transport options (REST, gRPC, WebSockets, server-sent events) are covered in The Fundamentals First. This lesson builds on them.

Where the API fits and how it is scored

In a 45-minute round the API usually follows requirements and core entities, and comes before the high-level diagram. It counts toward the requirements and high-level design dimensions: it proves you turned the functional requirements into concrete operations. It also feeds trade-offs, because pagination, idempotency and the protocol choice are decisions the interviewer can probe.

Budget roughly five minutes. Write one endpoint per functional requirement, three to six in total, with the important fields only. You are not writing documentation; you are agreeing on the contract the diagram has to serve.

Resources first, verbs second

Start from the entities you just named and expose them as resources. For REST, that means nouns in the path and HTTP methods as verbs:

  • POST /orders creates an order.

  • GET /orders/{orderId} reads one.

  • GET /users/me/orders lists the caller's orders.

  • POST /orders/{orderId}/cancel performs an action that is not a plain update.

That last one is deliberate. Some operations are state transitions with rules ("you can cancel only before the restaurant accepts"). Forcing them into PATCH /orders/{orderId} with status: "cancelled" hides the rule. A named action sub-resource is clearer, and interviewers accept it.

Two habits make an API look senior:

  • Take identity from the auth token, never the body. GET /users/me/orders instead of GET /orders?userId=123. If the user id comes from the request, a client can ask for someone else's data.

  • Return what the client needs next. A create call returns the created resource with its id and status, so the client does not need a second read.

Pagination: offset or cursor

Any list that can grow needs pagination, and interviewers often ask which kind.

Offset pagination (?limit=20&offset=40) is simple and supports "jump to page 7". It has two problems at scale. The database still walks past every skipped row, so deep pages get slower. And if new items arrive while a user scrolls, every item shifts down by one, so the next page repeats an item the user already saw.

Cursor pagination (?limit=20&cursor=...) returns an opaque cursor with each page that encodes where the page ended, usually the sort key of the last item plus its id as a tiebreaker. The next query starts strictly after that point:

SELECT id, created_at, total_cents, status
FROM orders
WHERE user_id = $1
  AND (created_at, id) < ($2, $3)   -- values decoded from the cursor
ORDER BY created_at DESC, id DESC
LIMIT 20;

With an index on (user_id, created_at DESC, id DESC) this costs the same on page 1 and page 500, and inserts do not cause repeats. The trade-off: no jumping to an arbitrary page. For feeds, timelines, order history and chat, cursor pagination is the right default; say so and give the reason.

Idempotency on writes

Clients retry. A phone on a train sends POST /orders, the request reaches your server, the order is created, and the response is lost. The app retries, and without protection the customer gets two orders.

The fix is an idempotency key: the client generates a unique id per logical action (a UUID made when the user taps "Place order") and sends it on every attempt, typically in an Idempotency-Key header. The server stores the key with the result in the same transaction as the order; a repeated key returns the stored result instead of creating a second order. Scaling Data covers why the key and the effect must commit together.

Mention idempotency on every write that moves money or creates something a user would notice twice. It is one of the most reliable ways to earn points on failure handling.

Errors, limits and versions

Errors. Use status codes for the category and a small body for the detail, for example {"code": "restaurant_closed", "message": "..."}. A machine-readable code lets clients react without parsing English. The codes you should be able to justify:

  • 400 malformed request, 401 not authenticated, 403 authenticated but not allowed, 404 not found.

  • 409 conflict with current state, such as cancelling an order the restaurant already accepted.

  • 429 rate limited, with a Retry-After header telling the client when to try again.

  • 500 server bug; 502, 503 and 504 an upstream that failed, is overloaded or timed out. Clients retry 502 to 504, and 429 after its Retry-After, with backoff. A retried write is safe only with an idempotency key, because a 500 or a timeout does not tell the client whether the write happened.

Rate limits. For a public or abuse-prone endpoint, say it is rate limited per user or per API key and returns 429. You do not need to design the limiter unless asked.

Versioning. Adding an optional field or a new endpoint does not break clients, so it needs no new version. Removing or renaming a field does. The common approach is a version in the path (/v1/orders) for public APIs. For mobile apps, remember that old app versions stay installed for months, so the server must keep serving the old shape until those versions are gone.

Auth. At the level of a design interview, one sentence is enough: clients send a bearer token in the Authorization header, an API gateway or middleware validates it, and services trust the user id it extracts.

REST, RPC, GraphQL or a stream

Pick by the access pattern, and say why in one sentence:

  • REST for public and mobile-facing request-response APIs. It is widely understood and GET responses can be cached by browsers and CDNs. The default in most interviews.

  • RPC (gRPC) for internal service-to-service calls where you control both ends and want typed contracts and low overhead. Mention it when your design has many internal hops.

  • GraphQL when many different clients need different slices of the same data and you want to avoid several round trips per screen. The costs: caching is harder because most queries are POSTs to one endpoint, and one expensive query can be costly to serve, so you need query cost limits.

  • A streaming API (WebSocket or server-sent events) when the server must push updates without the client asking, such as order status, chat messages or live prices. It usually sits next to a REST API rather than replacing it.

Worked example: a food delivery app

Prompt: "Design the backend for a food delivery app. Users browse nearby restaurants, place an order and watch its status until delivery."

A weak API, as candidates often write it:

getRestaurants()
createOrder(userId, items)
getOrder(orderId)
updateOrder(orderId, status)

No pagination or location on the list, the user id comes from the client, nothing protects against a double order, and a generic updateOrder lets any client set any status.

A strong API, written in about five minutes:

GET  /v1/restaurants?lat=..&lng=..&radiusKm=5&cursor=..&limit=20
     -> { restaurants: [{ id, name, etaMinutes, rating }], nextCursor }

GET  /v1/restaurants/{restaurantId}/menu
     -> { sections: [{ name, items: [{ id, name, priceCents }] }] }

POST /v1/orders
     Idempotency-Key: <uuid generated on tap>
     body { restaurantId, items: [{ itemId, quantity }], addressId }
     -> 201 { orderId, status: "placed", totalCents, etaMinutes }

GET  /v1/orders/{orderId}
     -> { orderId, status, items, totalCents, courier }

POST /v1/orders/{orderId}/cancel
     -> 200, or 409 if the restaurant already accepted

GET  /v1/orders/{orderId}/events   (server-sent events)
     -> stream of { status, at } as the order moves

What to say while writing it:

  • "The user comes from the token, so there is no user id in any body."

  • "Prices come from the server's menu, not the client, so the client sends item ids and quantities only."

  • "Placing an order takes an idempotency key because mobile networks drop responses."

  • "Status updates flow one way, server to client, so server-sent events are enough; I do not need a WebSocket."

  • "The courier and restaurant apps use separate endpoints with their own permissions; I will leave them out unless you want them."

That last line shows you know the API is bigger than what you wrote, and you chose the slice that matters.

Follow-ups to expect

  • "What happens if POST /orders times out and the client retries?" The idempotency key returns the first result. Mention the window: keys are kept for, say, 24 hours, long enough to cover any retry.

  • "How does the client find out the order was accepted?" The event stream, with a fallback of polling GET /orders/{orderId} every few seconds if the stream drops.

  • "The restaurant list returns 20 items. How does the next page stay correct as restaurants open and close?" Cursor pagination over a stable sort; accept that a newly opened restaurant may not appear until the user refreshes.

  • "How would you change this for a partner API?" Versioning, per-key rate limits, stricter error contracts and webhooks so partners do not have to poll.

What changes with seniority

A mid-level candidate is expected to write clear endpoints that map to the requirements. A senior candidate adds the failure-handling details unprompted (idempotency, pagination choice, which errors are retryable) and justifies the protocol. A staff candidate also covers evolution: how the API changes without breaking old clients, and who owns which part of it.

Mistakes that cost points

  • Spending fifteen minutes on the API. List the core calls, note the key fields, move on. You can return to it during deep dives.

  • Taking the user id or the price from the client. Both are security bugs an interviewer will spot.

  • One generic update endpoint for state changes. Model transitions with rules as actions, and say which conflicts return 409.

  • Ignoring retries. Every write that creates something needs an answer to "what if the client sends it twice".

  • Choosing GraphQL or WebSockets without a reason. Name the access pattern that requires them, or use plain REST.

Practice it

Take ten minutes and write the API for a URL shortener and for a chat app, three to six calls each, with pagination and idempotency where they belong. Then say out loud which protocol each call uses and why. Run it for real in these interviews, where the API is the first thing you will be asked to define:

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Data Modeling for System Design Interviews

    Turn requirements into entities and access patterns, choose keys and indexes for the queries that matter, and denormalize for the read path with a stated update path.

    8 min read

  • Scaling Data: Replication, Partitioning and Consistency

    Pick and defend a partition key, handle hot keys, explain leader-follower, multi-leader and quorum replication, state CAP and PACELC correctly, and match a consistency guarantee to each feature.

    8 min read

  • System Design Interviews: The Quick Start

    Know which system design interview you face and how depth expectations change by level, then deliver any design with a six-step, 45-minute framework whose estimates drive real decisions.

    7 min read

  • ML System Design Interviews: The Quick Start

    Run an ML system design interview with an eight-step, 45-minute framework, from framing and labels to metrics, serving, drift and feedback loops, worked through on a harmful-comment classifier.

    9 min read