APIs and Protocols
The API is the contract between your system and its clients, and the first thing you write after requirements. Interviewers look for sensible resources, the right protocol for each interaction, pagination that scales, and safe retries.
Learning objectives
- Choose between REST, GraphQL, gRPC, WebSockets and Server-Sent Events for a given interaction.
- Design resource-oriented endpoints with clear inputs and outputs.
- Use cursor pagination and explain why offset pagination breaks at scale.
- Make writes safe to retry with idempotency keys.
Choosing a protocol
| Protocol | Shape | Use when | Watch out |
|---|---|---|---|
| REST over HTTP | Resources and verbs, JSON | The default for public and client-facing APIs | Chatty for complex screens |
| GraphQL | One endpoint, client chooses fields | Many client types needing different shapes of related data | Caching and query cost control are harder |
| gRPC | Protobuf over HTTP/2, typed contracts, streaming | Service-to-service calls inside your system | Not natively usable from browsers |
| WebSockets | Full-duplex persistent connection | Chat, collaborative editing, multiplayer | Stateful connections complicate load balancing |
| Server-Sent Events | One-way server push over HTTP | Live scores, notifications, progress updates | Server-to-client only |
| Long polling | Request held until data arrives | Simple near-real-time without new infrastructure | Wasteful at scale |
Interview default: REST for the client API, gRPC between internal services if you mention it at all, and a push protocol only when a requirement needs real-time updates (Module 5 covers the pattern).
Designing endpoints
POST /v1/tweets { text, mediaIds[] } → 201 { tweetId }
GET /v1/tweets/{tweetId} → 200 Tweet
GET /v1/users/{userId}/feed?cursor=…&limit=20 → 200 { items[], nextCursor }
POST /v1/users/{userId}/follow → 204Habits that read well: plural nouns, verbs from HTTP methods, versioning in the path, identity from the auth token, and errors with proper status codes (400 validation, 401/403 auth, 404, 409 conflict, 429 rate limited, 5xx server).
Pagination
| Approach | How | Problem |
|---|---|---|
| Offset | ?offset=10000&limit=20 | The database still scans and discards 10,000 rows; items shift when new ones arrive, causing duplicates or gaps |
| Cursor (keyset) | ?cursor=<last seen id or timestamp> → WHERE id < :cursor ORDER BY id DESC LIMIT 20 | Uses the index directly; stable under inserts. Cannot jump to page 500 |
Use cursor pagination for feeds, timelines and any large list.
Safe retries: idempotency
Networks fail after the server has done the work. If a client retries POST /charges, it must not charge twice.
Text description
The client sends POST /charges with idempotency key abc. The API stores the key together with the charge. The response is lost to a timeout, so the client retries with the same key. The API finds key abc already stored and returns the original result, 201 with the same charge id, instead of charging twice.
GET,PUTandDELETEare idempotent by definition;POSTis not.- For non-idempotent operations, the client sends an idempotency key (a UUID per logical operation). The server stores the key with the result, unique-constrained, and returns the stored result for repeats.
- Keys expire after a window (for example 24 hours).
Any write that moves money, sends a message or creates something visible should be idempotent. Saying "the client sends an idempotency key so retries are safe" is a quick senior signal.
Self-check
Design the API for a Twitter-like service.
- Resource endpoints for posting, reading a tweet, following, and the home feed with cursor pagination; identity from the token; status codes; idempotency for posting.
Why is cursor pagination better than offset pagination for feeds?
- Index seek instead of scan-and-discard; stable when new items arrive; no duplicates or gaps.
How do you make a non-idempotent endpoint safe to retry?
- Client idempotency key per operation; server stores key + result with a unique constraint; replay stored result; expiry window.