Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
API Design is a core lesson in the Networking & APIs family of the Thita system design course.
Protocols (REST, gRPC, WebSocket, SSE), API design, pagination, and idempotency.
It is part of the Interview Soon path: the HLD material that appears in a standard interview loop rather than only in a specialist one.
A system design interview usually goes wrong before storage, scaling, or queues. Vague APIs leave the design without a contract. Clear APIs define read paths, write paths, idempotency, pagination, rate limits, and data ownership. Interviewers use the API as the first concrete version of the system.
Start with: “Let me define the core entities and APIs first.”
The API tells you what the system must read, write, validate, retry, paginate, and protect.
For a marketplace order system, a first pass can look like this:
1POST /v1/orders
2GET /v1/orders/{order_id}
3GET /v1/users/{user_id}/orders?limit=50&cursor=...
4POST /v1/orders/{order_id}/cancel
5POST /v1/payments
6GET /v1/payments/{payment_id}That short list exposes the design work. POST /v1/orders needs idempotency because clients retry. GET /v1/users/{user_id}/orders needs pagination because order history grows. POST /v1/payments needs duplicate protection because retrying a payment must not charge twice.
A useful interview API definition includes four things:
user, order, payment, booking, and message.Define behavior before drawing components. The API tells the interviewer what the system does. The storage, queues, caches, and replicas follow from that behavior.
REST works well in interviews because it gives you predictable resource names and standard semantics. Name resources as nouns. Use HTTP methods for actions. Use status codes for client-visible outcomes. Avoid RPC-style endpoints unless the action does not map cleanly to a resource.
Use plural nouns for collections: /users, /orders, /payments.
Use nested paths when the relationship matches the access pattern. /users/{user_id}/orders works for order history. Avoid deep paths like /users/{id}/orders/{id}/items/{id}/discounts/{id}. Deep nesting makes authorization, caching, and ownership harder to reason about.
| API concern | Good example | Avoid | Use when | Typical status codes |
|---|---|---|---|---|
| Create resource | POST /v1/orders | POST /createOrder | Server assigns ID or validates creation | 201 Created, 400 Bad Request, 409 Conflict |
| Read one resource | GET /v1/orders/{order_id} | POST /getOrder | Fetch by stable ID | 200 OK, 404 Not Found |
| List resources | GET /v1/users/{user_id}/orders?limit=50&cursor=... | GET /allOrders | Bounded list with pagination | 200 OK, 400 Bad Request |
| Replace resource | PUT /v1/users/{user_id} | POST /updateUser | Full replacement, client knows full state | 200 OK, 404 Not Found |
| Partial update | PATCH /v1/users/{user_id} | POST /modifyUser | Update selected fields | 200 OK, 400 Bad Request, 409 Conflict |
| Delete resource | DELETE /v1/cards/{card_id} | POST /deleteCard | Remove or deactivate a resource | 204 No Content, 404 Not Found |
| Domain action | POST /v1/orders/{order_id}/cancel | GET /cancelOrder?id=... | Action changes state and has business rules | 200 OK, 409 Conflict, 422 Unprocessable Entity |
| Rate limited | Any endpoint | Silent throttling | Client exceeded allowed rate | 429 Too Many Requests |
| Auth failure | Any endpoint | 200 with error body | Missing or invalid credentials | 401 Unauthorized, 403 Forbidden |
Use 409 Conflict when the request conflicts with current state, such as canceling an already shipped order.
Use 422 Unprocessable Entity when the request is syntactically valid and violates domain rules, such as booking a checkout date before a check-in date.
Use 500 only for server faults the client cannot fix.
REST gives you semantics, not only names. After you define POST /payments as a mutation, retries need idempotency, failures need clear status codes, and rate limits need to protect the endpoint.
Define shapes early and keep them lean. Interviewers check whether you know what data crosses the API boundary. Include identifiers, state, timestamps, and fields that affect correctness.
A payment creation API should make duplicate prevention explicit:
1{
2 "amount_cents": 2599,
3 "currency": "USD",
4 "payment_method_id": "pm_123",
5 "order_id": "ord_456",
6 "idempotency_key": "client-generated-uuid"
7}A useful response gives the client a stable server-side identifier and state:
1{
2 "payment_id": "pay_789",
3 "status": "authorized",
4 "amount_cents": 2599,
5 "created_at": "2026-02-10T12:45:30Z"
6}Do not return internal database details such as shard keys, replication metadata, or raw enum values tied to implementation.
Return states clients can act on: pending, confirmed, failed, canceled.
Stable external contracts let you change storage later without breaking clients.
Pagination is required for list APIs. Any endpoint that returns a collection needs a bounded limit, even when the first version has only a few rows. Unbounded lists cause production incidents because response size, database work, and client memory grow without a hard stop.
Use offset pagination for small, stable datasets where concurrent writes do not affect correctness. Admin pages, configuration lists, and small search results can use ?limit=50&offset=100. Cost grows as the offset grows because the database often scans or skips earlier rows.
Use cursor-based pagination for feeds, histories, messages, transactions, orders, and anything that changes while users read it. The cursor encodes the last item’s stable sort position, commonly (created_at, id). New rows can be inserted between requests without causing duplicate or missing items.
| Pagination type | Example | Best fit | Failure mode | Recommendation |
|---|---|---|---|---|
| Offset | ?limit=50&offset=100 | Small admin lists, mostly static data | Duplicates or missing items under writes; slow deep pages | Use only for small datasets |
| Cursor | ?limit=50&cursor=eyJ0cyI6... | Feeds, orders, messages, transactions | Requires stable ordering and cursor encoding | Default for user-facing lists |
| Time-window | ?start=...&end=...&limit=100 | Logs, analytics, audit trails | Hot ranges can overload storage | Use with indexed time fields |
| Keyset | ?after_id=msg_123&limit=50 | Simple ordered tables | Breaks if ID order does not match sort order | Use when ID order matches sort order |
A cursor response should include the next cursor and a flag indicating whether more data exists:
1{
2 "items": [{ "order_id": "ord_1" }, { "order_id": "ord_2" }],
3 "next_cursor": "eyJjcmVhdGVkX2F0IjoiMjAyNi0wMi0xMCIsImlkIjoib3JkXzIifQ==",
4 "has_more": true
5}The database query should use the same stable sort fields encoded in the cursor:
1SELECT *
2FROM orders
3WHERE user_id = $1
4 AND (created_at, order_id) < ($2, $3)
5ORDER BY created_at DESC, order_id DESC
6LIMIT $4;Use cursor pagination for any user-facing growing list. Use offset pagination for small internal pages or static datasets.
A new order lands between page 1 and page 2. Offset paging shows order 7 twice. Cursor paging continues after the last item seen, so nothing repeats or goes missing.
Idempotency keys prevent duplicate side effects when clients retry mutations. A client-generated unique key is sent with each retryable mutation. The server stores the key with the request fingerprint and final response. Duplicate attempts return the original response.
Idempotency keys are required for payments, bookings, order creation, ride requests, ticket purchases, and inventory reservations. Network timeouts can trigger duplicates because the server may have succeeded while the client received no response.
A typical request includes the key in a header:
1POST /v1/payments
2Idempotency-Key: 7f6b5b8e-1f2a-4d8a-9d5b-1c2e3f4a5b6c
3Content-Type: application/jsonThe server logic should be explicit:
1def create_payment(req):
2 key = req.headers["Idempotency-Key"]
3 existing = idempotency_store.get(key)
4 if existing:
5 return existing.response
6
7 with transaction():
8 payment = insert_payment(req.body)
9 response = build_response(payment)
10 idempotency_store.put(key, hash(req.body), response)
11 return responseIn a real implementation, the put must be atomic with the side effect or protected by a uniqueness constraint. Store a request hash so the same key cannot be reused for a different mutation. Use a TTL based on retry windows. Use 24 hours for normal API retries. Use a longer TTL for payments when reconciliation requires it.
| Scenario | Without idempotency | With idempotency | Pick |
|---|---|---|---|
| Client times out after successful payment | Retry may charge twice | Retry returns original payment result | Idempotency required |
| User double-clicks submit | Two orders may be created | Same key returns same order | Idempotency required |
| Mobile client retries on bad network | Multiple bookings possible | One booking is created | Idempotency required |
| Pure read request | No side effect | No key needed | Do not require keys |
A POST mutation can be made safe to retry by using an idempotency key. Say that directly in the interview.
The payment succeeds but the reply is lost. The client retries with the same Idempotency-Key, and the server returns the stored response instead of charging a second time.
Rate limiting protects shared systems from abuse, bugs, and traffic spikes. Apply it at the API layer because the API knows the caller, endpoint, authentication state, and business priority. A database cannot distinguish a premium user refreshing a feed from a broken client looping on POST /payments.
Use per-user and per-endpoint limits by default. A write-heavy endpoint like POST /payments should have a lower limit than GET /products. Anonymous traffic should have stricter limits than authenticated traffic.
Use token bucket by default. Each caller has a bucket that refills at a steady rate up to a maximum burst size. A request consumes a token. If no token exists, return 429 Too Many Requests.
| Algorithm | Behavior | Best fit | Weakness | Recommendation |
|---|---|---|---|---|
| Fixed window | Allows N requests per minute | Simple internal tools | Boundary bursts can double traffic | Avoid for public APIs |
| Sliding window | Smooths fixed-window bursts | More accurate enforcement | More storage and compute | Use when fairness matters |
| Token bucket | Allows controlled bursts with steady refill | Public APIs, most interviews | Needs shared counters at scale | Default choice |
| Leaky bucket | Processes at constant rate | Queue-like traffic shaping | Adds delay instead of direct rejection | Use for background ingestion |
A simple policy might be:
1GET /v1/products: 100 req/sec/user, burst 200
2GET /v1/orders: 20 req/sec/user, burst 40
3POST /v1/orders: 5 req/sec/user, burst 10
4POST /v1/payments: 2 req/sec/user, burst 3
5Anonymous endpoints: 10 req/sec/IP, burst 20Return clear headers so clients can back off correctly:
1HTTP/1.1 429 Too Many Requests
2Retry-After: 10
3X-RateLimit-Limit: 120
4X-RateLimit-Remaining: 0
5X-RateLimit-Reset: 1760000000Use Redis or an API gateway for distributed counters. Redis can handle high-rate token operations. API gateways keep rate limiting close to ingress. For very large systems, combine local gateway counters with periodic centralized reconciliation. In an interview, start with Redis or gateway-level rate limiting unless the scale requires more.
Use the same flow every time. It keeps the interview grounded and prevents early jumps into storage.
User, Order, Payment, Booking, Message.The flow creates natural hooks for tradeoffs. If the interviewer asks about scaling reads, point to the list API. If they ask about duplicate charges, point to idempotency. If they ask about abuse, point to rate limits.
Default: Start every system design answer by defining entities and APIs. Use REST-style resource names. Use cursor pagination for growing user-facing lists. Use idempotency keys for retryable mutations. Use token-bucket rate limiting per user and per endpoint. Use offset pagination only for small internal or static datasets.
Warning: Common failure modes:
- Skipping API definition and jumping straight to databases, caches, or Kafka. The design then has no clear set of operations.
- Listing endpoints without request or response shapes. Missing shapes hide duplicate payments, invalid booking states, and missing identifiers.
- Forgetting pagination on list APIs. Any unbounded
GET /itemsendpoint can become a scalability and latency problem.- Using offset pagination for feeds, messages, or order history. Concurrent writes cause duplicates, missing rows, and slow deep pages.
- Missing idempotency keys. Payments, bookings, order creation, ride requests, and retryable mutations need them.
- Saying “HTTP retries can be handled by the client.” The client cannot know whether the server committed the side effect before the timeout.
- Applying one global rate limit to all traffic. Reads, writes, anonymous users, authenticated users, and sensitive endpoints need different limits.
- Returning
200 OKfor all errors. Clients need meaningful status codes to retry, fix input, re-authenticate, or stop.
| Category | 2026 number | API design implication |
|---|---|---|
| Same-AZ latency | < 1ms | API gateway to service calls inside one AZ are cheap. Keep APIs coarse enough to avoid chatty request paths. |
| Cross-AZ latency | 1-2ms | Synchronous multi-AZ calls are acceptable for high-value paths. Limit call count. |
| Cross-region latency, US-EU | 70-90ms | Avoid synchronous API dependencies across regions when the user-facing latency budget is tight. |
| Cross-region latency, US-India | 150-250ms | Use regional APIs or asynchronous workflows for global products. |
| Redis GET | < 1ms | Good fit for rate-limit counters, idempotency records, sessions, and hot metadata. |
| Postgres indexed query | 1-5ms | A well-indexed list API with cursor pagination can be fast without caching. |
| S3 first byte | 50-100ms | Avoid serving small API metadata from object storage on the request path. |
| CDN edge | 5-30ms | Use for static assets and cacheable public responses. Avoid it for personalized mutation flows. |
| Redis throughput | 100K-500K ops/sec per instance | A single Redis instance can handle many token-bucket checks before sharding. |
| Postgres single primary | 10K-50K TPS, tens of TB before sharding | Estimate write TPS before sharding. Millions of users do not automatically require sharding. |
| Kafka cluster | 1M+ msg/sec, single-digit ms latency | Kafka handles async processing behind APIs. API semantics still come from endpoint contracts. |
| Network within datacenter | 25-100 Gbps | Bandwidth is rarely the first bottleneck for JSON APIs. Database work and fanout usually fail earlier. |
| General-purpose machine | 512 GiB RAM, 128 vCPUs | Modern single nodes are large. Avoid premature distributed complexity. |
| Local SSD | 60 TB | Local storage is large. API correctness still depends on durable system-of-record storage. |
| QPS estimate | DAU × actions/user ÷ 86,400; peak = 2-3× average | Spend 2-3 minutes estimating API traffic, then design. |
| Bandwidth estimate | QPS × average response size | Use this to justify pagination limits and response trimming. |