sagelearnai

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

ProtocolShapeUse whenWatch out
REST over HTTPResources and verbs, JSONThe default for public and client-facing APIsChatty for complex screens
GraphQLOne endpoint, client chooses fieldsMany client types needing different shapes of related dataCaching and query cost control are harder
gRPCProtobuf over HTTP/2, typed contracts, streamingService-to-service calls inside your systemNot natively usable from browsers
WebSocketsFull-duplex persistent connectionChat, collaborative editing, multiplayerStateful connections complicate load balancing
Server-Sent EventsOne-way server push over HTTPLive scores, notifications, progress updatesServer-to-client only
Long pollingRequest held until data arrivesSimple near-real-time without new infrastructureWasteful 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

text
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                              → 204

Habits 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

ApproachHowProblem
Offset?offset=10000&limit=20The 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 20Uses 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.

Client Payments API Database POST /charges · key=abc insert key abc + charge (response lost: timeout) retry POST · key=abc key abc exists → read result 201 same charge id
Client / userService / computeData store
Idempotent retries with an Idempotency-Key. The client retries after a timeout; the server recognises the key and returns the first result instead of charging 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, PUT and DELETE are idempotent by definition; POST is 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).
Mention it unprompted

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.

Last reviewed 2026-11-05.