ayushsalampuriya.xyzRevise

HLD · APIs

API Design & Rate Limiting

Expose reliable APIs and protect backends from abuse and overload.

1. REST API design basics

2. API Gateway role

Single entry point that handles:

Examples: AWS API Gateway, Kong, NGINX, Envoy.

3. Why rate limiting

Example: OpenAI API — 60 requests/min per API key. Excess returns 429 with Retry-After header.

4. Rate limiting algorithms

Token bucket

Bucket holds tokens; refills at fixed rate. Each request consumes 1 token. Allows bursts up to bucket size.

Example: 100 tokens, refill 10/sec → user can burst 100, then steady 10 RPS.

Leaky bucket

Requests enter queue; processed at constant rate. Smooths bursts; excess dropped or queued.

Fixed window

Count requests per minute. Simple but boundary spike (59 at :59 + 60 at :00 = 119 in 2 seconds).

Sliding window

Count over rolling last 60 seconds. Smoother; slightly more state (Redis sorted sets).

5. Distributed rate limiting

Multiple API servers must share counters → use Redis with atomic INCR + TTL or Lua scripts.

KEY = "rate:user:123:minute" count = INCR(key) if count == 1: EXPIRE(key, 60) if count > 100: return 429

6. Idempotency for safe retries

Client sends Idempotency-Key: uuid on POST payment. Server stores result keyed by UUID — duplicate requests return same response without double charge.

7. GraphQL vs REST (brief)

REST: multiple endpoints, fixed payloads. GraphQL: single endpoint, client picks fields — flexible but harder to cache and rate-limit per resource.

Quick revision

  • REST: Nouns, correct verbs, meaningful status codes, cursor pagination.
  • Gateway: Auth, routing, rate limit, TLS at edge.
  • Algorithms: Token bucket (bursts), sliding window (fair), leaky bucket (smooth).
  • Distributed: Redis counters with TTL.
  • 429: Include Retry-After; use idempotency keys on writes.