Patterns

API Design Patterns

REST vs GraphQL

AspectRESTGraphQL
Data FetchingMultiple endpoints, fixed structureSingle endpoint, client specifies
Over/Under-fetchingCommon problemSolved by design
CachingHTTP caching built-inMore complex
VersioningURL or header versioningSchema evolution
Best ForSimple CRUD, public APIsComplex, nested data

🔌 REST Best Practices

HTTP Methods

  • GET /users → List users
  • GET /users/:id → Get user
  • POST /users → Create user
  • PUT /users/:id → Replace user
  • PATCH /users/:id → Update user
  • DELETE /users/:id → Delete user

Response Codes

  • 200 OK - Success with body
  • 201 Created - Resource created
  • 204 No Content - Success, no body
  • 400 Bad Request - Client error
  • 401 Unauthorized - Auth required
  • 404 Not Found - Resource missing
  • 429 Too Many Requests - Rate limited
  • 500 Server Error - Our fault

📄 Pagination Patterns

PatternExamplePros/Cons
Offset?offset=20&limit=10Simple / Slow on large offsets
Cursor?cursor=abc123&limit=10Efficient, consistent / Can't jump to page
Keyset?after_id=100&limit=10Very efficient / Needs indexed column

Rule of thumb: Use offset for small datasets, cursor/keyset for large or real-time feeds.

🚦 Rate Limiting Algorithms

Token Bucket

Tokens added at fixed rate. Request consumes token.

✓ Allows bursts up to bucket size

✓ Smooth average rate

Sliding Window

Count requests in rolling time window.

✓ More accurate than fixed window

✓ Smooth rate enforcement

Fixed Window

Count requests per time window (e.g., per minute).

✓ Simple to implement

✗ Burst at window edges

Leaky Bucket

Queue requests, process at fixed rate.

✓ Very smooth output

✗ No bursting allowed

🔐 Authentication Patterns

MethodUse CaseNotes
API KeyServer-to-server, simpleEasy to implement, no user context
JWTStateless auth, microservicesSelf-contained, can't revoke easily
OAuth 2.0Third-party access, SSOStandard for delegated auth
Session CookieWeb apps, browsersServer-side state, easy to revoke

🔁 Idempotency

Definition: Same request can be made multiple times with the same effect as making it once.

Idempotent Methods

  • ✓ GET, PUT, DELETE, HEAD, OPTIONS
  • ✓ Safe to retry on timeout/failure

Non-Idempotent

  • ✗ POST (usually creates new resource)
  • → Use idempotency keys for retries
Pattern: Client sends Idempotency-Key: uuid header. Server stores result keyed by that UUID.

🎯 Interview Template

"For this API, I'd use [REST/GraphQL] because [reason]. For pagination, I'd use [cursor-based] since we have [high volume/real-time feed]. I'd implement rate limiting with [token bucket] to allow bursts while protecting the backend."