Guide / System design Fundamentals
1.3 REST API design
Resources, methods, status codes, error format, validation, idempotency, pagination, versioning and conditional requests, with the exact answers interviewers look for.
An API is a contract that outlives the code behind it. Interviewers use API design to test whether you think about clients you cannot control: they retry, send garbage, hold old versions and read page 5,000 of your list.
Fundamentals#
1.3.1 API styles: which one to choose#
| Style | Use when | Watch out for |
|---|---|---|
| REST over HTTP/JSON | Public and partner APIs, CRUD, anything cacheable; the default | Over/under-fetching, chatty clients, inconsistent conventions |
| gRPC | Internal service-to-service, low latency, streaming, strict schema | Not browser-native, needs load balancers that understand HTTP/2 |
| GraphQL | Many client types needing different shapes (web, mobile) | N+1 resolvers, HTTP caching is harder, need query cost limits and depth limits |
| Async events / webhooks | Fire-and-forget, fan-out, decoupling | Eventual consistency, ordering, harder debugging |
In an interview, say: “REST for the public API, gRPC between internal services, events for anything that does not need an immediate answer.”
1.3.2 Resource design and naming#
- Nouns, plural, hierarchical:
/orders,/orders/{id},/orders/{id}/items. Verbs belong in the method, not the URL. - Keep nesting shallow (two levels).
/users/{u}/orders/{o}/items/{i}is a smell;/orders/{o}/items/{i}is enough because order IDs are globally unique. - Actions that are not CRUD become sub-resources or custom verbs:
POST /orders/{id}/cancel,POST /payments/{id}/refunds(a refund is a thing with its own lifecycle and ID). - Use opaque, non-sequential IDs (UUIDv7, ULID, Snowflake) externally so clients cannot enumerate records and ordering by ID still works.
- Collections support
?filter,?sort,?fields,?limitand?cursor. Be consistent: copy one style and use it everywhere. - Use ISO 8601 UTC timestamps (
2026-11-29T10:15:30Z), money as integer minor units plus currency ({"amount": 1999, "currency": "INR"}), never floats.
1.3.3 Methods: safe, idempotent, cacheable#
| Method | Meaning | Safe (no state change) | Idempotent (same effect if repeated) | Cacheable | Typical success code |
|---|---|---|---|---|---|
| GET | Read | Yes | Yes | Yes | 200 |
| HEAD | Read headers only | Yes | Yes | Yes | 200 |
| POST | Create / run an action | No | No | Rarely | 201 (with Location), 202, 200 |
| PUT | Replace the whole resource | No | Yes | No | 200, 204 |
| PATCH | Partial update | No | Not guaranteed (depends on the patch format: “set x=5” is idempotent, “increment x” is not) | No | 200, 204 |
| DELETE | Remove | No | Yes (second call returns 404 or 204, but the end state is the same) | No | 204 |
Why it matters: idempotent methods may be retried automatically by clients, proxies and load balancers after a timeout. A non-idempotent POST must be made idempotent explicitly (1.3.7).
1.3.4 Status codes: what to return and what clients should do#
Group first, then the specific codes.
| Class | Meaning | Client reaction |
|---|---|---|
| 2xx | Success | Done |
| 3xx | Redirect or “not modified” | Follow or use cache |
| 4xx | Client error: the request is wrong | Fix the request. Do not retry (except 408, 409 in some flows, 425, 429) |
| 5xx | Server error | May retry (idempotent calls, with backoff) |
| Code | Name | Use it when | Retry? |
|---|---|---|---|
| 200 | OK | GET/PUT/PATCH success with a body | n/a |
| 201 | Created | POST created something; return Location: /orders/123 and the resource | n/a |
| 202 | Accepted | Work was queued, not done; return a status URL (1.3.11) | n/a |
| 204 | No Content | Success with no body (DELETE, PUT) | n/a |
| 301 / 308 | Moved permanently | Resource has a new permanent URL (308 keeps the method) | follow |
| 304 | Not Modified | Conditional GET matched the ETag (1.3.10) | use cache |
| 400 | Bad Request | Malformed JSON, wrong type, missing required field | No |
| 401 | Unauthorized | Not authenticated (missing/expired/invalid credentials). Send WWW-Authenticate | After refreshing the token |
| 403 | Forbidden | Authenticated but not allowed | No |
| 404 | Not Found | No such resource (also used to hide existence from unauthorised users) | No |
| 405 | Method Not Allowed | Wrong method on that URL; send Allow header | No |
| 406 / 415 | Not Acceptable / Unsupported Media Type | Unsupported Accept / Content-Type | No |
| 408 | Request Timeout | Server gave up waiting for the client | Yes |
| 409 | Conflict | State conflict: duplicate unique value, version mismatch, invalid state transition, idempotency key reused with a different body | Depends: fix the conflict, then retry |
| 410 | Gone | Existed once and was deleted permanently | No |
| 412 | Precondition Failed | If-Match ETag did not match (optimistic locking) | Re-read, merge, retry |
| 413 | Payload Too Large | Body over the limit | No |
| 422 | Unprocessable Content | Syntactically valid JSON but fails semantic/business validation | No |
| 428 | Precondition Required | Server requires If-Match for this write | Add header |
| 429 | Too Many Requests | Rate limit or quota exceeded; send Retry-After | Yes, after the delay |
| 500 | Internal Server Error | Unhandled bug. Never leak stack traces | Maybe, with backoff |
| 502 | Bad Gateway | The proxy got an invalid response from upstream | Yes |
| 503 | Service Unavailable | Overloaded, deploying, or dependency down; send Retry-After | Yes |
| 504 | Gateway Timeout | Upstream did not answer in time. Outcome unknown for writes | Only if idempotent |
Details interviewers probe:
- 401 vs 403: 401 means “I do not know who you are”; 403 means “I know who you are and the answer is no”.
- 400 vs 422: many teams use 400 for any validation failure; stricter APIs use 400 for syntax and 422 for semantic errors. Pick one convention and document it.
- 404 vs 403 for other people’s data: return 404 so attackers cannot probe which IDs exist (and hide the existence of resources you cannot access).
- 409 vs 412: 409 is a generic state conflict; 412 is specifically a failed conditional header.
- 503 vs 429: 429 says you are sending too much; 503 says we cannot serve right now. Both carry
Retry-After. - Never return 200 with an error body. It breaks monitoring, caches, retries and client libraries.
- 504 on a write means “unknown”, not “failed”: the server may have processed it. That is exactly why POSTs need idempotency keys.
1.3.5 Error response format#
Use one error shape across the whole API. The standard is RFC 9457 Problem Details (application/problem+json):
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/validation-failed",
"title": "Validation failed",
"status": 422,
"detail": "2 fields are invalid.",
"instance": "/orders",
"request_id": "req_8f3a1c",
"errors": [
{ "field": "items[0].quantity", "code": "min_value", "message": "Must be at least 1" },
{ "field": "shipping.pincode", "code": "invalid_format", "message": "Must be 6 digits" }
]
}
Rules:
- A stable machine-readable
code(clients branch on it) plus a humanmessage(clients may show it). Never make clients parse message text. - Include a request ID and log it so support can find the failure. Return it in a response header too.
- Report all validation errors at once, not one per round trip.
- Never leak internals (SQL, stack traces, hostnames). Log them server-side.
- Mark errors
retryableimplicitly via status code (429/503) andRetry-After.
1.3.6 Input validation#
Validate in layers, cheapest first, and never trust the client:
| Layer | Checks | Failure |
|---|---|---|
| 1. Transport | Content-Type, body size limit (e.g. 1 MB), JSON parses, request timeout | 400 / 413 / 415 |
| 2. Schema | Required fields, types, enums, string length, number range, regex, array size, unknown fields | 400 or 422 |
| 3. Semantic | Cross-field rules (end_date > start_date), formats (email, currency code), referenced IDs exist | 422 |
| 4. Authorization | Can this caller act on this resource? Check ownership on every request (prevents IDOR) | 403 / 404 |
| 5. Business rules | Stock available, balance sufficient, state allows the action | 409 / 422 |
| 6. Database constraints | NOT NULL, UNIQUE, foreign keys, CHECK: the last line of defence, and the only one that is race-free | 409 |
Practical rules:
- Define the schema once (OpenAPI/JSON Schema/protobuf) and generate validation, docs and client SDKs from it, so they cannot drift.
- Allowlist, not denylist: accept only known fields and values. Reject unknown fields or ignore them deliberately. Binding a request body straight onto a database model enables mass assignment (a client sets
is_admin: true). - Normalise before validating (trim, Unicode normalise, lowercase emails) and validate again on the server even if the UI did.
- Set limits everywhere: body size, string length, array length, nesting depth, page size (
limitmax 100), file size and type (check magic bytes, not the extension). - Parameterised queries only. Validation does not replace escaping or prepared statements for SQL injection; output encoding handles XSS.
- Validate IDs and enums before using them in lookups to avoid wasted queries (and cache penetration, see Caching).
- Check uniqueness with a constraint, not a SELECT. “Check then insert” is a race; insert and catch the unique violation, then return 409.
- Validate on the way out for AI-produced or third-party data too (LLM outputs, webhooks): treat as untrusted input.
1.3.7 Idempotency#
An operation is idempotent if running it once or many times leaves the system in the same state. Networks lose responses, so clients retry; retrying a non-idempotent call double-charges, double-orders, double-sends.
Method behaviour was in 1.3.3. For POST the standard solution is an idempotency key, popularised by Stripe:
- Client generates a unique key per logical operation (a UUID created when the user clicks “Pay”, reused on every retry).
- Client sends
Idempotency-Key: 7f9c...with the POST. - Server stores
(key, request fingerprint, status, response)using a unique constraint on the key, atomically with the work. - First request: process, save the response against the key.
- Retry with the same key and same body: return the saved response (same status and body), do not process again.
- Same key with a different body: reject with 409 or 422 (client bug).
- Retry while the first is still running: return 409 “in progress” (or wait). Keys expire after 24 hours or so.
-- the race-free core: insert the key first; the unique constraint decides who wins
INSERT INTO idempotency_keys (key, request_hash, status)
VALUES ($1, $2, 'in_progress')
ON CONFLICT (key) DO NOTHING;
-- 1 row inserted → we own it, do the work, then UPDATE status='done', response=...
-- 0 rows inserted → read the existing row: replay the response, or 409 if in progress
Idempotent does not mean “returns the same body forever”: it means the side effects happen once. Other forms of natural idempotency are better when available: PUT /orders/{client_generated_id} is idempotent without any key, and deterministic IDs plus unique constraints make duplicate inserts harmless. Full treatment including the payment gateway and webhook cases: Idempotency.
1.3.8 Pagination#
Never return an unbounded list. Three approaches:
| Approach | Request | How it works | Pros | Cons |
|---|---|---|---|---|
| Offset / page | ?page=3&limit=20 → LIMIT 20 OFFSET 40 | Skip N rows | Simple, supports “jump to page 50” | Cost grows with offset (the DB reads and discards all skipped rows; page 100,000 is slow); rows shift when data is inserted or deleted, so users see duplicates or miss items |
| Cursor / keyset | ?limit=20&cursor=eyJpZCI6MTAwfQ | Remember the last item seen and ask for “after” it | Constant time with an index; stable under inserts; the right choice for feeds and large tables | No random access to page N; need a deterministic sort |
| Time/ID-based range | ?since_id=100 or ?updated_after=ts | Filter by monotonic value | Great for sync and polling | Needs a monotonic column; late-arriving rows can be missed |
Keyset SQL, with a tie-breaker so equal sort values are never skipped or repeated:
-- sort: newest first. cursor = (created_at, id) of the last row from the previous page
SELECT id, created_at, ...
FROM orders
WHERE user_id = $1
AND (created_at, id) < ($2, $3) -- row-value comparison uses the index
ORDER BY created_at DESC, id DESC
LIMIT 21; -- fetch limit+1 to learn if there is a next page
-- index: (user_id, created_at DESC, id DESC)
Response shape:
{
"data": [ ... 20 items ... ],
"next_cursor": "eyJjIjoiMjAyNi0xMS0yOVQxMDoxNTozMFoiLCJpIjo5MjF9",
"has_more": true
}
- Make the cursor opaque (base64 of the sort key, optionally signed) so you can change its internals; clients must not construct it.
- Cap
limit(default 20, max 100) and return a clear error above it. - Total counts are expensive (
COUNT(*)on a big table scans an index). Skip them, return an approximate value, or cache it. Say so if asked “how many pages?”. - Sorting by a non-unique column without a tie-breaker is a classic bug: add
idto the order. - Pagination over a search engine has the same problem (
from+sizedeep paging); usesearch_after(Elasticsearch) or a point-in-time cursor.
1.3.9 Versioning and evolution#
Versioning is about not breaking existing clients (mobile apps live for years).
| Strategy | Example | Pros | Cons |
|---|---|---|---|
| URL path | /v1/orders | Obvious, easy to route and cache | Version applies to the whole API |
| Header / media type | Accept: application/vnd.example.v2+json | Clean URLs, per-resource versions | Hidden, harder to test in a browser |
| Query parameter | /orders?version=2 | Easy | Pollutes cache keys, easy to forget |
| Date-based header (Stripe) | Stripe-Version: 2026-11-01 | Accounts pinned to a version, small changes | Needs infrastructure to translate versions |
What counts as a breaking change: removing or renaming a field, changing a type or meaning, making an optional field required, tightening validation, changing an error code clients branch on, changing default sort or page size. Non-breaking: adding an optional request field, adding a response field (clients must ignore unknown fields: the tolerant reader rule), adding a new endpoint or enum value (warn clients that enums may grow).
Process: (1) add, never rename: introduce the new field, keep the old one; (2) announce deprecation with Deprecation and Sunset headers and a changelog; (3) measure usage per version and per client; (4) contact remaining clients; (5) remove only at zero or agreed usage. Keep at most 2–3 live major versions. Internally, translate old versions to the current model at the edge instead of maintaining duplicated logic.
1.3.10 Conditional requests and optimistic concurrency#
- Caching: the server sends
ETag: "v7"; the client repeats the GET withIf-None-Match: "v7"; unchanged returns 304 with no body, saving bandwidth. - Lost-update protection: the client sends
If-Match: "v7"with its PUT/PATCH. If the resource changed (ETag differs), the server returns 412 and the client re-reads and merges. In a database this isUPDATE ... WHERE id = $1 AND version = $2and checking affected rows. It avoids two users silently overwriting each other without taking locks. Cache-Control:public, max-age=300(shared caches may store),private(browser only: personalised),no-store(never cache: tokens, balances),stale-while-revalidate(serve stale while refreshing in the background).
1.3.11 Long-running operations and callbacks#
For anything slower than a few seconds (video transcoding, reports, bulk import): POST /exports returns 202 Accepted with Location: /exports/abc and a body { "status": "queued" }. The client polls GET /exports/abc (include Retry-After and progress) or registers a webhook. Webhooks need: signed payloads (HMAC with a shared secret and a timestamp to stop replay), retries with backoff, a unique event ID so receivers can dedupe, and a way to re-fetch events (do not rely on delivery alone).
1.3.12 Authentication and authorisation (the API view)#
- API keys: simple, identify an application; send in a header, never in the URL (URLs are logged). Store hashed.
- OAuth 2.0 / OIDC: delegated access for users (authorisation code with PKCE for apps). Short-lived access tokens (5–60 minutes, typically JWT) plus a refresh token.
- JWT trade-off: stateless verification (no DB hit) but hard to revoke before expiry; keep them short-lived and keep a revocation list for emergencies.
- Service-to-service: mTLS or signed tokens issued by the mesh or identity provider.
- Always check authorisation per object (not just “is logged in”), use HTTPS only, set CORS deliberately, and never put secrets or PII in URLs.
1.3.13 Rate-limit headers (summary)#
Return 429 plus Retry-After: 30, and ideally RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (IETF draft) or the older X-RateLimit-* forms so clients can slow down before hitting the limit. Algorithms, placement and failure modes: Rate limiting.
Most asked questions#
1. How do you make a POST endpoint safe to retry?
Require an Idempotency-Key header (client-generated UUID reused on retries). Insert it with a unique constraint in the same transaction as the work; on a repeat return the stored response; on the same key with a different body return 409/422; expire keys after about 24 h. Pair with natural idempotency where possible (client-supplied IDs with PUT, unique constraints). For payments also pass the key to the gateway. Source: Idempotency.
2. Offset vs cursor pagination: when and why?
Offset is fine for small, stable data and admin screens that need page numbers. At scale it degrades (reads and discards N rows) and shows duplicates or misses rows when data changes. Cursor/keyset uses WHERE (sort_key, id) < (last_key, last_id) ORDER BY sort_key DESC, id DESC LIMIT n on a composite index: constant time and stable. Return an opaque cursor and has_more; avoid total counts.
3. How do you version an API?
Path versioning (/v1) for public APIs because it is explicit and cache-friendly, evolving additively inside a version (add fields, never rename or remove), deprecating with Sunset headers and usage metrics, and only cutting v2 when a breaking change is unavoidable. Clients follow the tolerant-reader rule.
4. What status codes would you return for these cases? Create resource → 201 + Location. Validation failure → 400/422 with field errors. Missing token → 401. Valid token but no permission → 403. Unknown ID → 404. Duplicate email → 409. Rate limited → 429 + Retry-After. Dependency down → 503. Upstream timeout → 504. Queued job → 202.
5. 401 vs 403? 401: unauthenticated or bad credentials (retry after logging in). 403: authenticated but not allowed (retry will not help).
6. How do you design validation? Layered: schema (generated from OpenAPI), semantic, authorisation, business rules, DB constraints as the final race-free guard. Allowlist fields, enforce size limits, return all errors in a consistent problem-details body with machine-readable codes.
7. PUT vs PATCH?
PUT replaces the whole resource and is idempotent. PATCH changes some fields; make patch operations idempotent (set rather than increment) or protect with If-Match/version columns.
8. REST vs GraphQL vs gRPC? Table in 1.3.1. REST externally and for caching; gRPC internally for performance; GraphQL when many clients need flexible shapes and you can afford resolver batching (DataLoader) and query cost limits.
9. How would you design the “create order” API?
POST /orders with Idempotency-Key; body has items and client-side total (server recomputes the price from the source of truth); returns 201 and the order in pending_payment; POST /orders/{id}/payments takes the payment; state transitions guarded by conditional updates; GET /orders?cursor= for history; webhooks or events for status changes; errors in problem+json; rate-limited per user.
10. How do you handle partial failures in a batch endpoint (create 100 items)?
Either all-or-nothing in a transaction (simple semantics), or 207 Multi-Status-style per-item results: [{index:0, status:201}, {index:1, status:422, error:...}], with a per-item idempotency key. Document the choice and limit batch size.
Senior-level questions#
1. “Clients retry on timeout and you see duplicate orders in production although you use idempotency keys. Why?” Typical causes: the key is regenerated per attempt (client bug: generate once per user intent and persist it before sending); the key check is a SELECT-then-INSERT race instead of a unique constraint; the idempotency record and the business write are not in the same transaction (a crash between them leaves the order created but the key unrecorded, or vice versa); the key is scoped globally rather than per user/endpoint (collisions) or too short a TTL (retry arrives after expiry); a retry through a different path (mobile resend after app restart without the stored key, or a message queue redelivery) bypasses the HTTP layer check. Fix with a constraint, a transaction, per-tenant scoping, client persistence, and reconciliation.
2. “How do you deep-paginate a 500M-row table sorted by a non-unique, mutable column such as updated_at?”
Keyset on (updated_at, id), with the caveat that rows that change while the client is paging can move; rows updated mid-scan may appear twice or be skipped. For consistent snapshots use a point-in-time/snapshot read, or paginate on an immutable column (created_at/id) and treat updates as a separate change feed (updated_after with CDC). For export use an async job writing to object storage, not API pagination.
3. “How do you change a field’s type without breaking mobile apps that cannot be force-updated?”
Add a new field next to the old one (price_minor beside price), write both, migrate clients, read both on the server, deprecate with metrics showing remaining old-client traffic, and remove only after the old version’s usage reaches zero or the sunset date, using forced upgrade only for security issues. Gate behaviour with a client version header or feature flags rather than separate deployments.
4. “You return 503 under load and clients retry immediately, making it worse. What do you do?”
A retry storm. Server: shed load early (admission control), return Retry-After, apply per-client limits. Client: exponential backoff with jitter, a retry budget (e.g. retries ≤ 10% of requests), a circuit breaker, and no retries at multiple layers (retries at each hop multiply: 3 retries × 3 layers = 27× load).
5. “Design the API for a long-running payment where the final result may arrive hours later.”
POST /payments returns 202 with a payment in processing; the idempotency key ensures one payment; state moves via webhooks from the provider (signed, deduped by event ID) and a reconciliation job that polls the provider for stuck payments; clients get status via GET or their own webhook. The API never claims success until the provider confirms.
6. “How would you secure an API against IDOR and mass assignment?”
Object-level authorisation on every read and write (the query includes the owner: WHERE id=$1 AND tenant_id=$2), unguessable IDs as defence in depth (not as the control), DTOs with explicit allowlisted fields instead of binding raw bodies to models, and automated tests that call each endpoint with another tenant’s IDs.
7. “How do you keep API behaviour backward compatible when your database is sharded or your service is split?” Keep the external contract stable behind an API gateway or BFF, map old shapes to new internals at the edge, run old and new paths in parallel with shadow traffic and response diffing, and migrate consumers by version. Contract tests (e.g. consumer-driven) in CI catch breaking changes before release.
8. “Where do you enforce rate limits, validation and auth?” Cheap, generic checks at the edge or API gateway (TLS, auth token validation, coarse rate limits, size limits, WAF); object-level authorisation, business validation and fine-grained quotas in the service that owns the data; database constraints as the final guarantee. Never rely on a single layer.
Quiz#
1. Which HTTP methods are idempotent, and why does it matter?
GET, HEAD, PUT, DELETE (and OPTIONS/TRACE) are idempotent; POST is not and PATCH may not be. Idempotent requests can be retried automatically after timeouts by clients and proxies without extra side effects.
2. A client gets a 504 from POST /payments. Was the payment made?
Unknown. The gateway timed out waiting for the upstream, which may have completed. Retry with the same idempotency key (safe) or query the payment status; never create a second payment with a new key.
3. Why is OFFSET 100000 slow and unstable?
The database must read and discard 100,000 rows before returning the page, and inserts or deletes between page requests shift rows so items repeat or disappear. Use keyset pagination on an indexed, unique ordering.
4. Write the keyset condition for ORDER BY created_at DESC, id DESC.
WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT :n, supported by an index on (created_at DESC, id DESC) plus any equality filter columns first.
5. 401 or 403: an expired token? A normal user calling an admin endpoint?
Expired token: 401 (not authenticated). Normal user on an admin endpoint: 403 (authenticated, not permitted).
6. Is adding a new enum value to a response a breaking change?
It can be: clients with exhaustive switches may crash. Document that enums can grow and require a default case (tolerant reader), or version the change.
7. How do you stop two admins overwriting each other's edits through the API?
Optimistic concurrency: return an ETag/version, require If-Match on updates, reject mismatches with 412 (or 409) and let the client re-read and merge. In SQL: UPDATE ... WHERE id=? AND version=? and check the affected row count.
8. What should a good 429 response contain?
Status 429, Retry-After (seconds or date), a problem-details body with a stable error code, and ideally rate-limit headers (limit, remaining, reset) on normal responses too so clients can pace themselves.
9. Why return 404 instead of 403 for another tenant's resource?
It avoids confirming that the resource exists, preventing enumeration of IDs across tenants.
10. What are the six validation layers in order?
Transport (size, content type, parse), schema (types, required, ranges), semantic (cross-field rules), authorisation (object-level), business rules (state, stock, balance), database constraints (unique, foreign key, check).
11. How should a bulk-create endpoint report that 3 of 100 items failed?
Either reject the whole batch in one transaction, or return per-item results (index, status, error) with an overall 207/200, each item carrying its own idempotency key so the client can retry only the failed ones.
12. Why use integer minor units for money in APIs?
Floating point cannot represent decimal fractions exactly (0.1 + 0.2 ≠ 0.3), producing rounding errors. Integers (paise, cents) plus an ISO currency code are exact.