Lesson 9 of 15 Communication

API Design: REST, gRPC and WebSockets

Design clean APIs for large systems: REST resources, gRPC, WebSockets and SSE, pagination, idempotency keys, versioning and API gateways.

35-45 min intermediate 0/15 lessons done
Course contents Lesson 9 of 15 · 0 done
On this page (11 sections)
  1. What you will learn
  2. Choosing a protocol
  3. REST done well
  4. Pagination
  5. Idempotency keys
  6. Versioning and evolution
  7. Real-time APIs
  8. API gateway
  9. Key takeaways
  10. Exercises
  11. Quiz

What you will learn

  • When to use REST, gRPC, WebSockets or server-sent events.
  • Resource-oriented REST design and status codes that matter.
  • Pagination, idempotency keys and versioning.
  • What an API gateway does.

Choosing a protocol

StyleTransportBest for
REST (JSON over HTTP)Request-responsePublic APIs, CRUD, browser clients
gRPC (Protobuf over HTTP/2)Request-response and streamingInternal service-to-service calls; typed, compact, fast
GraphQLRequest-responseClients that need flexible, nested reads (mobile apps)
WebSocketsPersistent two-way connectionChat, multiplayer, collaborative editing
Server-sent events (SSE)Persistent one-way (server → client)Live feeds, notifications, progress updates
Long pollingRepeated requests held openFallback when the above aren’t available

REST done well

Model resources (nouns) and use HTTP methods for actions:

POST   /v1/links               create a link           201 Created
GET    /v1/links/{code}        read one                200 / 404
GET    /v1/users/{id}/links    list a user's links     200
PATCH  /v1/links/{code}        change expiry           200
DELETE /v1/links/{code}        delete                  204

Status codes worth using precisely: 400 (bad input), 401 (not authenticated), 403 (not allowed), 404, 409 (conflict, e.g. custom alias taken), 429 (rate limited), 500/503 (server problem; 503 means “try later”).

Pagination

Never return unbounded lists.

  • Offset pagination (?offset=200&limit=50): simple, but slow on deep pages and items shift when new ones arrive.
  • Cursor pagination (?cursor=eyJpZCI6...&limit=50): the cursor encodes “after item X” (e.g. last id or timestamp). Fast at any depth and stable while data changes. Use it for feeds and large lists.

Idempotency keys

Networks fail after the server has done the work but before the client sees the response. The client retries and you charge the card twice. Fix: the client sends a unique Idempotency-Key header; the server stores the key with the result and, on a repeat, returns the stored result instead of redoing the work. GET, PUT and DELETE are idempotent by definition; POST needs keys for anything important.

Versioning and evolution

Put a version in the path (/v1/) or a header. Within a version, make only backward-compatible changes: add optional fields, never rename or remove. Clients must ignore unknown fields. Protobuf’s numbered fields make this natural for gRPC.

Real-time APIs

For chat-like features the server must push to clients. WebSockets keep one long-lived connection per client; that means connection servers are stateful (they know which users are connected to them), which shapes the chat system design. SSE is simpler when only the server pushes.

API gateway

A gateway sits in front of services and handles cross-cutting concerns: authentication, rate limiting, request routing, TLS, request/response logging, and sometimes aggregation of several backend calls into one response. It keeps those concerns out of every service, at the cost of one more hop and component to scale.

Key takeaways

  • REST for public CRUD, gRPC internally, WebSockets/SSE for push, GraphQL for flexible reads.
  • Design around resources and use status codes precisely, including 409 and 429.
  • Prefer cursor pagination for large or changing lists; use idempotency keys for retried POSTs.
  • Evolve APIs with additive changes and explicit versions; centralise auth and limits in a gateway.

Exercises

  1. Design the REST API for a to-do app with lists, items, sharing and pagination.
  2. Implement idempotency keys for a create_payment(key, amount) function in Python using a dictionary, and show that a retried call doesn’t charge twice.
  3. For a live sports score page, choose between polling, SSE and WebSockets and justify it.

Quiz

  1. Why is cursor pagination better than offset pagination for a social feed?
  2. What problem do idempotency keys solve?
  3. Which status code should a rate-limited request receive?
Show answers
  1. It stays fast at any depth and doesn’t skip or repeat items when new posts are inserted while the user scrolls.
  2. Duplicate side effects (e.g. double charges) when a client retries a request whose response it didn’t receive.
  3. 429 Too Many Requests, ideally with a Retry-After header.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).