Lesson 10 of 38Building blocks
API Design
Design clean REST APIs, know when GraphQL, gRPC, WebSockets, SSE, or webhooks fit better, and paginate correctly.
The API is the contract between your system and everyone who uses it: your own frontend, mobile apps that cannot be force-updated, and other companies' code. A good API is predictable and hard to misuse; a bad one leaks into every client and is nearly impossible to change later. In system design interviews, step three is "define the API", and how you name endpoints, paginate, and push real-time updates says a lot about your experience.
REST: resources and verbs
REST models your system as resources (nouns) with URLs, and uses HTTP methods (verbs) to act on them. The URL says what, the method says what to do.
GET /v1/users/42/posts?limit=20 list Ada's posts
POST /v1/users/42/posts create a post
GET /v1/posts/981 read one post
PATCH /v1/posts/981 change some fields
DELETE /v1/posts/981 delete itAvoid verbs in paths (/getPosts, /createUser): the method already says that.
| Method | Meaning | Safe (no side effects) | Idempotent |
|---|---|---|---|
GET | Read | Yes | Yes |
POST | Create, or run an action | No | No (needs an idempotency key) |
PUT | Replace the whole resource | No | Yes |
PATCH | Change some fields | No | Not guaranteed |
DELETE | Remove | No | Yes |
Status codes that matter
| Code | Meaning | When |
|---|---|---|
200 OK | Success with a body | Most reads and updates |
201 Created | A resource was created | POST that creates; include a Location header |
202 Accepted | Queued for later | Async jobs (see the queues lesson) |
204 No Content | Success, no body | DELETE |
400 Bad Request | The input is invalid | Validation errors |
401 Unauthorized | Not authenticated | Missing or bad token |
403 Forbidden | Authenticated, but not allowed | Editing someone else's post |
404 Not Found | No such resource | Wrong id |
409 Conflict | Clashes with current state | Duplicate username, version mismatch |
429 Too Many Requests | Rate limited | Next lesson |
500 / 503 | Server error / temporarily unavailable | Bugs, overload, maintenance |
Pagination: offset vs cursor
Never return an unbounded list. Offset pagination (?limit=20&offset=40) is simple and lets users jump to page 7, but it gets slow on deep pages (the database still reads and skips 40,000 rows for offset=40000) and it shifts when new rows arrive.
A feed is paginated with offsets, 3 per page. A new post (6) arrives between page 1 and page 2. What does page 2 show?
posts = [5, 4, 3, 2, 1] page1 = posts[0:3] posts.insert(0, 6) page2 = posts[3:6] print(page2)
Cursor pagination (keyset) returns an opaque next_cursor that encodes where you stopped, usually the last item's sort key. The next query is WHERE id < :cursor ORDER BY id DESC LIMIT 20, which uses an index and stays fast at any depth. Feeds, timelines, and most public APIs (Stripe, Slack, GitHub's GraphQL) use cursors.
Press Run (⌘ Enter) to see what happens.Versioning
Once clients depend on your API, you cannot break it. Additive changes (new optional fields, new endpoints) are safe. Breaking ones (renaming or removing a field, changing a type) need a new version: in the path (/v1/, /v2/, the most common and easiest to see), in a header (Accept: application/vnd.example.v2+json), or as a dated version (Stripe's Stripe-Version: 2024-06-20). Keep old versions running until clients migrate.
GraphQL: the client shapes the response
GraphQL exposes one endpoint (POST /graphql) and a typed schema. The client sends a query describing exactly the fields it wants, across related objects, and gets exactly that shape back.
query {
user(id: 42) {
name
posts(first: 3) {
title
comments(first: 2) { author { name } }
}
}
}One round trip replaces several REST calls, and mobile clients stop over-fetching fields they do not show. The costs: HTTP caching is harder (everything is a POST to one URL), a single query can be very expensive (you need depth and complexity limits), and the N+1 problem: a naive resolver loads 3 posts with one query, then runs one more query per post for its comments, and one per comment for its author. The standard fix is batching with a DataLoader, which collects all the ids requested in one tick and loads them in a single WHERE id IN (...) query.
gRPC: fast calls between services
gRPC is a framework for calling functions on another service. You define the service and messages in a .proto file, and code is generated for each language. Messages are encoded with Protocol Buffers, a compact binary format that is several times smaller and faster to parse than JSON, and calls run over HTTP/2, which supports streaming in either or both directions.
syntax = "proto3";
service FeedService {
rpc GetFeed (FeedRequest) returns (FeedResponse);
rpc WatchFeed (FeedRequest) returns (stream Post); // server streaming
}
message FeedRequest { int64 user_id = 1; int32 limit = 2; }
message Post { int64 id = 1; string text = 2; int64 author_id = 3; }
message FeedResponse { repeated Post posts = 1; }gRPC is the common choice for internal service-to-service traffic. Browsers cannot speak it natively (you need gRPC-Web or a gateway), and binary payloads are harder to debug with curl, so public APIs usually stay REST or GraphQL.
Real time: polling, long polling, SSE, WebSockets
HTTP is request-response: the client asks, the server answers. When the server needs to push (a new chat message, a live score), you have four options.
- Short polling: the client asks "anything new?" every few seconds. Simple, but wasteful and laggy.
- Long polling: the client asks, and the server holds the request open until there is news (or 30 s pass), then the client immediately asks again.
- Server-Sent Events (SSE): one long-lived HTTP response that the server keeps writing events to (
Content-Type: text/event-stream). One direction, server to client, with automatic reconnect built into browsers. Great for notifications, live feeds, and streaming AI responses. - WebSockets: an HTTP request is upgraded into a persistent, two-way connection. Both sides send messages at any time with tiny overhead. The choice for chat, multiplayer games, and collaborative editing.
The server has nothing new, so it holds the request instead of answering empty.
WebSocket connections are stateful: each one is pinned to one server, so you need least-connections load balancing, a way to route a message to whichever server holds the recipient's socket (usually Redis pub/sub between servers), and care during deploys.
Webhooks: the server calls you
A webhook is a reverse API: instead of you polling a provider for updates, the provider sends an HTTP POST to a URL you registered when something happens. Payment providers, GitHub, and Shopify all use them.
The provider sends payment.succeeded with a signature header. The endpoint verifies the signature with a shared secret, so a stranger cannot fake a payment.
Choosing a style
| Style | Transport | Direction | Best for | Watch out for |
|---|---|---|---|---|
| REST | HTTP + JSON | Request/response | Public APIs, CRUD, cacheable reads | Over/under-fetching, many round trips |
| GraphQL | HTTP POST + JSON | Request/response (+ subscriptions) | Many clients needing different shapes of related data | N+1, query cost limits, harder caching |
| gRPC | HTTP/2 + Protobuf | Request/response and streaming | Internal service-to-service calls | No native browser support |
| SSE | Long-lived HTTP | Server → client | Notifications, live feeds, streaming text | One direction only |
| WebSockets | Upgraded TCP connection | Both ways | Chat, games, collaboration | Stateful connections to scale |
| Webhooks | HTTP POST to you | Provider → you | Events from third parties | Signatures, retries, duplicates |
Match each feature to the API style that fits best.
- REST
- Resources as URLs, actions as HTTP methods (GET, POST, PUT, PATCH, DELETE), standard status codes.
- cursor pagination
- Return a cursor marking the last item; the next page starts after it. Fast at any depth and stable as data changes.
- GraphQL N+1
- One query for a list, then one per item for related data. Fixed by batching with a DataLoader.
- gRPC
- Typed RPC over HTTP/2 with Protocol Buffers and streaming. Common between internal services.
- WebSocket vs SSE
- WebSockets are two-way persistent connections; SSE is a one-way server-to-client event stream over HTTP.
- webhook
- A provider POSTs events to your URL. Verify the signature, respond fast, and process idempotently.