Bird
Raised Fist0

REST API Design Principles - Resources, Methods, Status Codes, Pagination

HLDmediumInterview freq: common
Choose your preparation mode4 modes available
🎯
REST API Design Principles - Resources, Methods, Status Codes, Pagination
45 min · senior
senior

You are designing REST APIs for a startup with 50 million daily active users (DAU). The APIs must support secure, scalable, and performant access to core business resources. The system requires end-to-end encryption, must maintain P99 latency under 200ms, and handle high concurrency with consistent pagination for large datasets.

  • All API traffic must be encrypted using TLS 1.3 to protect user data in transit.
  • P99 latency for API responses must be under 200ms to ensure good user experience.
  • API must support cursor-based pagination to handle large datasets efficiently and avoid offset pitfalls.
  • Use standard HTTP status codes to clearly communicate success and error states to clients.
  • Design must consider idempotency for safe retries on write operations.
📋
Guided Steps
1/5
Step 1
Resource Modeling and URI Design
How would you model resources and design URIs for RESTful access to core entities?
💡 Hint
Focus on nouns for resources, hierarchical URIs for relationships, and avoid verbs in paths.
Use plural nouns for resource names in URIs (e.g., /orders), and nested URIs for sub-resources (e.g., /orders/{orderId}/items) following REST best practices.
Mid-level: Names plural resource nouns and basic URI structure. Senior: Explains why verbs in URIs break REST semantics and how hierarchical URIs improve clarity and caching.
⚠️Common Wrong Answer
Using verbs in URIs like /getOrder or /createOrder - this breaks REST uniform interface and complicates client caching.
Step 2
HTTP Methods and Idempotency
Which HTTP methods will you use for create, read, update, and delete operations? How do you ensure safe retries?
💡 Hint
Consider idempotency guarantees of PUT vs POST and safe methods like GET.
Use POST for create (non-idempotent), GET for read (safe, idempotent), PUT for full update (idempotent), PATCH for partial update, and DELETE for removal (idempotent).
Mid-level: Correctly maps CRUD to HTTP methods. Senior: Explains idempotency implications for retries and why POST is non-idempotent while PUT is idempotent.
⚠️Common Wrong Answer
Using POST for updates - leads to non-idempotent operations causing duplicate side effects on retries.
Step 3
HTTP Status Codes for Success and Errors
What HTTP status codes will you return for typical success and error scenarios?
💡 Hint
Use 2xx for success, 4xx for client errors, 5xx for server errors, and specific codes for common cases like 201 Created or 404 Not Found.
Return 200 OK for successful GET, 201 Created with Location header for POST, 204 No Content for successful DELETE, 400 Bad Request for validation errors, 404 Not Found for missing resources, and 500 Internal Server Error for unexpected failures.
Mid-level: Lists common status codes. Senior: Explains why 201 must include Location header and how 204 avoids unnecessary payloads improving latency.
⚠️Common Wrong Answer
Returning 200 OK for all responses including errors - confuses clients and breaks REST semantics.
Step 4
Pagination Strategy for Large Result Sets
How will you implement pagination to efficiently handle large lists and maintain consistent ordering?
💡 Hint
Offset-based pagination can cause duplicates or missing items under concurrent writes; cursor-based pagination is preferred.
Implement cursor-based pagination using opaque cursors (e.g., encoded timestamps or IDs) passed as query parameters, enabling consistent, performant pagination without offset pitfalls.
Mid-level: Mentions pagination with limit and offset. Senior: Explains offset pagination issues at scale and why cursor-based pagination with stable sort keys is necessary for consistency.
⚠️Common Wrong Answer
Using offset pagination at 50M DAU - leads to inconsistent results and high DB load causing latency spikes.
Step 5
Security and Encryption
How will you ensure data security and encryption for API requests and responses?
💡 Hint
TLS 1.3 is standard for encrypting data in transit; consider authentication and authorization mechanisms.
Enforce TLS 1.3 for all API endpoints to encrypt data in transit, use OAuth 2.0 Bearer tokens for authentication, and validate scopes for authorization.
Mid-level: Mentions HTTPS usage. Senior: Details TLS 1.3 benefits, token-based auth, and scope validation to minimize attack surface.
⚠️Common Wrong Answer
Relying on HTTP without TLS - exposes sensitive data to interception and breaks compliance.
🔌
API Design Challenge
Sketch 3 core REST API endpoints for a resource (e.g., 'orders') including resource URIs, HTTP methods, expected status codes, and pagination approach.
  • How does the client create, retrieve, and list resources following REST conventions?
  • What HTTP methods and status codes best represent each operation's outcome?
  • How will you implement pagination to efficiently handle large result sets?
📊
Scoring Rubric
▼ Show
Must Have - 60%
  • Correct REST resource naming and URI design using plural nouns.
  • Appropriate HTTP methods with idempotency considerations.
  • Standard HTTP status codes with correct usage (201, 204, 400, 404).
  • Cursor-based pagination implementation for large datasets.
  • TLS 1.3 enforced for all API traffic.
Good to Have - 30%
  • OAuth 2.0 token-based authentication and scope-based authorization.
  • Idempotency keys for safe retries on non-idempotent methods.
  • Use of HTTP caching headers like ETag for performance.
Bonus - 10%
  • Explanation of trade-offs between offset and cursor pagination with scale impact.
  • Discussion of how REST principles improve client-server decoupling and scalability.
Using verbs in URIs (e.g., /getOrder) breaks REST uniform interface and complicates client caching, leading to poor scalability and maintainability.
Using POST for update operations causes non-idempotent side effects and retry issues, resulting in duplicate resource modifications and inconsistent state.
Returning 200 OK for all responses including errors confuses clients and breaks REST semantics, making error handling unreliable.
Offset-based pagination at scale leads to inconsistent results and high database load causing latency spikes, degrading user experience.
Not enforcing TLS exposes sensitive data to interception and breaks compliance, risking data breaches and loss of user trust.
Ignoring idempotency causes duplicate resource creation or inconsistent state on retries, leading to data corruption and client errors.
✅
Model Answer
▼ Reveal

This design outlines REST API best practices for a high-scale startup with 50M DAU, focusing on resource modeling, HTTP methods with idempotency, standard status codes, cursor-based pagination, and strong security via TLS 1.3 and OAuth 2.0.

  • Use plural resource names in URIs to align with REST semantics and improve caching.
  • Map CRUD operations to HTTP methods considering idempotency: POST (non-idempotent create), PUT (idempotent full update), PATCH (partial update), DELETE (idempotent delete), GET (safe read).
  • Return appropriate HTTP status codes: 201 Created with Location header on resource creation, 204 No Content on successful deletes, 400 Bad Request for validation errors, 404 Not Found for missing resources, and 500 Internal Server Error for unexpected failures.
  • Implement cursor-based pagination with opaque cursors (e.g., encoded timestamps or unique IDs) to avoid offset pagination pitfalls and maintain consistent ordering under high concurrency.
  • Enforce TLS 1.3 for all API traffic to secure data in transit, and use OAuth 2.0 Bearer tokens with scope validation for authentication and authorization.
  • Use idempotency keys or client-generated IDs on POST requests to safely handle retries and prevent duplicate resource creation.
  • Leverage HTTP caching headers like ETag and If-None-Match to enable conditional requests and reduce latency.
  • Plural resource names in URIs (e.g., /orders) for RESTful clarity and caching benefits.
  • HTTP methods mapped to CRUD with idempotency: POST (create, non-idempotent), PUT (update, idempotent), GET (read, safe), DELETE (idempotent).
  • Use of standard HTTP status codes: 201 Created with Location header for resource creation, 204 No Content for deletes, 400/404 for client errors.
  • Cursor-based pagination with opaque cursors to avoid offset pitfalls and ensure consistent ordering at scale.
  • TLS 1.3 enforced for all API traffic to secure data in transit.
  • OAuth 2.0 Bearer tokens for authentication and fine-grained authorization via scopes.
  • Idempotency keys or client-generated IDs for safe retries on POST requests to prevent duplicate resource creation.
  • Use of HTTP headers like ETag and If-None-Match for caching and conditional requests to reduce latency.

Practice

(1/5)
1. In the DNS resolution chain, at step 4 the recursive DNS server receives a referral response from the root server pointing to a TLD server. What state does the recursive server enter immediately after receiving this referral?
easy
A. It caches the referral to the TLD server and initiates a query to the TLD server
B. It discards the referral and retries querying the root server
C. It caches the IP address of the root server and returns it to the client
D. It forwards the referral directly to the client without caching

Solution

  1. Step 1: Understand recursive server behavior on referral

    When the recursive DNS server receives a referral from the root server, it caches the referral information (the TLD server's IP) and then queries the TLD server itself.
  2. Step 2: Eliminate incorrect states

    It does not cache the root server IP (already known), nor does it discard the referral or forward it directly to the client. The recursive server handles the full resolution chain transparently.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Recursive server caches referral and queries next server [check]
Hint: Recursive server caches referrals and queries next hop [check]
Common Mistakes:
2. A web API must limit incoming requests to 100 per second with bursts allowed up to 200 requests. Which component best enforces this rate limiting with burst handling?
easy
A. A fixed window counter that resets every second
B. A simple request queue that drops requests when full
C. A leaky bucket algorithm that processes requests at a fixed rate without bursts
D. A token bucket algorithm that refills tokens at a steady rate with a maximum bucket size

Solution

  1. Step 1: Identify rate limiting with burst support

    The token bucket algorithm allows tokens to accumulate up to a max bucket size, enabling bursts beyond the steady refill rate.
  2. Step 2: Eliminate other options

    Fixed window counters cause spikes at window boundaries and don't handle bursts well. Leaky bucket smooths traffic but disallows bursts. Simple queues drop excess requests without rate control.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Token bucket allows bursts by token accumulation [check]
Hint: Token bucket = steady refill + burst capacity [OK]
Common Mistakes:
3. Without a consistent hashing function in a hash-based sharding system, what exact failure occurs when a new shard is added?
medium
A. New shard receives no traffic because keys are not remapped dynamically
B. Range queries become inefficient due to overlapping shard boundaries
C. Directory lookup fails to find the new shard, causing requests to be dropped
D. All existing data must be rehashed and moved, causing massive downtime and inconsistent routing

Solution

  1. Step 1: Understand consistent hashing role

    Consistent hashing minimizes key remapping when shards change.
  2. Step 2: Trace failure without consistent hashing

    Adding a shard requires rehashing all keys, moving massive data, causing downtime and routing inconsistencies.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Without consistent hashing, shard addition triggers full rehash and data move [check]
Hint: Consistent hashing avoids full rehash on shard changes [check]
Common Mistakes:
4. If the prefix hash map component fails and becomes unavailable, what is the immediate impact on the autocomplete system's behavior?
medium
A. The system returns no results for prefix queries until the prefix hash map recovers
B. The Trie component automatically handles prefix queries without any degradation in performance
C. Autocomplete queries fall back to Elasticsearch but with increased latency and less precise prefix matching
D. User input is cached locally on the client until the prefix hash map is restored

Solution

  1. Step 1: Understand component roles

    The prefix hash map is an optimization for O(1) prefix lookups, but the Trie is the primary data structure for prefix matching.
  2. Step 2: Trace failure impact

    If the prefix hash map fails, the system falls back to the Trie for prefix queries, which still works but may have slightly higher latency.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Trie fallback ensures prefix queries continue despite prefix hash map failure [check]
Hint: Trie fallback keeps prefix search alive if prefix hash fails [check]
Common Mistakes:
5. At 10x current scale, which component in the YouTube view count system is most likely to fail first, and why?
hard
A. The CDN edge caches because they cannot handle the increased video delivery requests
B. The view count database because it is a centralized bottleneck for high write throughput
C. The transcoding pipeline because it cannot process 10x more video uploads in time
D. The upload service because it cannot handle 10x concurrent upload connections

Solution

  1. Step 1: Analyze component scalability at 10x load

    CDN edge caches (A) scale horizontally and are designed for massive read throughput. Transcoding pipeline (C) can be scaled with more workers. Upload service (D) can be scaled with load balancers and stateless servers.
  2. Step 2: Identify view count database bottleneck

    View count DB is a centralized write hotspot with high contention and latency sensitivity. At 10x scale, it becomes the first bottleneck due to write amplification and consistency requirements.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Centralized view count DB write bottleneck fails first [check]
Hint: Centralized DB write bottleneck breaks first at scale [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard