Skip to content
Chethan Yadav_
System Design

SD/Lesson 7 of 8/6 min read

API Design and Microservices

REST, GraphQL and gRPC, API design rules, pagination and versioning, rate limiting algorithms, monoliths vs microservices, service discovery, and observability.


On this page

API styles

REST API

REST models the system as resources identified by URLs and manipulated with standard HTTP methods. It is stateless: every request carries everything needed to process it.

GET    /users/42           read user 42
POST   /users              create a user
PATCH  /users/42           partial update
DELETE /users/42           delete
GET    /users/42/orders    a user's orders

Rules of thumb:

  • Nouns in paths, verbs from HTTP methods (POST /orders, not /createOrder).
  • Plural collection names, nested only one level deep.
  • Correct status codes: 201 created, 400 bad input, 401 not authenticated, 403 forbidden, 404 not found, 409 conflict, 429 rate limited.
  • GET, PUT and DELETE must be idempotent; accept an Idempotency-Key for POST when retries matter.
  • Consistent error bodies with a machine-readable code.

GraphQL

GraphQL exposes one endpoint and a typed schema; the client specifies exactly which fields it wants.

query {
  user(id: 42) {
    name
    orders(last: 3) { id total }
  }
}
  • Avoids over-fetching and under-fetching (one round trip instead of several REST calls). Great for varied frontends.
  • Harder to cache at the HTTP layer, and easy to write expensive queries: enforce depth and complexity limits. Watch for N+1 resolver calls (use DataLoader batching).

gRPC

gRPC uses HTTP/2 and Protocol Buffers (a compact binary format) with strongly typed contracts generated from .proto files.

  • Fast, small payloads, bidirectional streaming, code generation for many languages.
  • Not natively browser-friendly and not human-readable. Ideal for internal service-to-service calls.
RESTGraphQLgRPC
TransportHTTP/1.1 or 2, JSONHTTP, JSONHTTP/2, Protobuf
Best forPublic APIsClient-driven frontendsInternal microservices
CachingEasy (HTTP)HardCustom
StreamingLimited (SSE, WebSocket)SubscriptionsNative

Pagination

Never return unbounded lists.

  • Offset pagination: ?limit=20&offset=40. Simple and allows jumping to page N, but slow on large offsets (the DB still scans skipped rows) and items shift when rows are inserted.
  • Cursor Pagination: ?limit=20&after=eyJpZCI6MTIzfQ. The cursor encodes the last seen sort key; the query becomes WHERE id > 123 ORDER BY id LIMIT 20. Fast at any depth and stable under inserts. Used by most large APIs.

API Versioning

  • URL: /v1/users. Explicit and easy to route. Most common.
  • Header: Accept: application/vnd.api.v2+json. Cleaner URLs, harder to test in a browser.
  • Prefer additive, backward-compatible changes (new optional fields) so versions are rarely needed. Never remove or rename a field without a deprecation window.

Rate Limiting

Rate limiting caps how many requests a client can make in a time window. It protects against abuse, brute force and accidental overload, and enforces fair use and pricing tiers. Return 429 Too Many Requests with a Retry-After header.

Token Bucket

A bucket holds up to B tokens and refills at r tokens per second. Each request takes a token; an empty bucket means reject. It allows bursts up to B while enforcing average rate r. The most common algorithm (AWS, Stripe).

Leaky Bucket

Requests enter a queue that drains at a fixed rate; when the queue is full, new requests are dropped. Smooths output to a constant rate, with no bursts.

Window algorithms

AlgorithmHowTrade-off
Fixed windowCount per calendar minuteSimple; allows 2x burst at window edges
Sliding window logStore each request timestampExact; memory per request
Sliding window counterWeighted mix of current and previous window countsClose approximation, cheap

In a distributed system, keep counters in a shared store (Redis with atomic INCR or a Lua script) so all API servers see the same counts. Limit by API key or user ID, and by IP for unauthenticated traffic.

Monolith vs microservices

Monolith

One deployable application containing all features, typically with one database.

  • Simple to develop, test, deploy and debug. Function calls instead of network calls. Transactions are easy.
  • As it grows: slow builds, tangled code, every team deploying the same artifact, all-or-nothing scaling.

A modular monolith (strict module boundaries inside one deployable) gets many of the benefits of microservices without the network.

Microservices

Microservices split the system into small, independently deployable services, each owning one business capability and its own data.

  • Independent deploys and scaling, team autonomy, technology choice per service, fault isolation.
  • Costs: network latency and failures, distributed transactions, eventual consistency, much harder debugging, and heavy operational tooling (CI/CD, observability, service discovery).
Microservices solve an organizational scaling problem more than a technical one. Start with a monolith and extract services along clear boundaries when team size or scaling needs demand it.

Anti-pattern: a distributed monolith, where services share a database or must be deployed together. You pay all the costs and get none of the benefits.

Service Discovery

Service instances come and go, so callers cannot hard-code addresses.

  • Client-side: clients query a registry (Consul, Eureka) and pick an instance themselves.
  • Server-side: clients call a load balancer or DNS name that resolves to healthy instances (Kubernetes Services).

Service Mesh

A service mesh (Istio, Linkerd) puts a sidecar proxy next to every service instance to handle service-to-service concerns uniformly: mTLS, retries, timeouts, circuit breaking, traffic splitting and telemetry, without changing application code.

Observability

Observability is the ability to understand what a system is doing from its outputs. Three pillars:

  • Metrics: numeric time series (request rate, error rate, latency percentiles, saturation). Cheap, good for dashboards and alerts. The RED method (Rate, Errors, Duration) for services; USE (Utilization, Saturation, Errors) for resources.
  • Logs: structured (JSON) event records with request IDs. Good for detail after you know where to look.
  • Traces: the path of one request across services.

Distributed Tracing

Each incoming request gets a trace ID, propagated in headers (W3C traceparent) to every downstream call. Each unit of work records a span with timing and parent. Tools (Jaeger, Zipkin, OpenTelemetry) assemble spans into a waterfall that shows where the latency went.

Quick revision

  • REST for public APIs, GraphQL for flexible client queries, gRPC for fast internal calls.
  • Resource nouns, HTTP verbs, correct status codes, idempotent retries.
  • Cursor pagination beats offset at scale; version APIs and prefer additive changes.
  • Token bucket allows bursts with an average rate; store counters in Redis for distributed limits.
  • Start with a (modular) monolith; microservices trade simplicity for independent deploys and scaling.
  • Each microservice owns its data; avoid the distributed monolith.
  • Observability: metrics, logs, traces; propagate trace IDs across services.