Bird
Raised Fist0

GraphQL vs REST - Trade-offs for Different Query Patterns

HLDmediumInterview freq: common
Choose your preparation mode4 modes available
🏗️
GraphQL vs REST - Trade-offs for Different Query Patterns
Analyzing GraphQL and REST trade-offs for diverse query patterns at scale
mediumAPI Design and GatewayFreq: common
⚙️
Functional Requirements
  • Support flexible client queries with variable fields and nested data
  • Provide efficient data fetching minimizing over-fetching and under-fetching
  • Support batch and real-time query patterns with caching
  • Enable versioning and backward compatibility for evolving APIs
  • Provide clear error handling and validation for client queries
  • Support authentication and authorization at the API gateway
📊
Non-Functional Requirements
  • Handle 2 billion daily active users (DAU) generating 40 queries per user per day
  • Ensure 99.99% API availability with failover and retries
  • Maintain 100ms P99 latency for read queries under peak load
  • Support horizontal scaling to handle 925K peak queries per second (QPS)
  • Ensure data consistency within 1 second for real-time updates
❓
Clarifying Questions to Ask
  • What is the expected query complexity and nesting depth for GraphQL queries?
  • Are there specific use cases favoring batch vs real-time queries?
  • What is the expected write-to-read ratio for the APIs?
  • Is schema evolution and versioning required for REST endpoints?
  • What caching strategies are acceptable for stale data?
  • Are there any constraints on payload size or bandwidth usage?
Out of Scope
✗ Designing the underlying database schema or data storage engines
✗ Implementing client-side SDKs or UI components
✗ Detailed security policies beyond authentication and authorization
✗ Third-party API integrations or federation
📌
Assumptions
  • 2 billion DAU
  • 40 queries per user per day
  • Average query/request size 100 bytes
  • Read-to-write ratio 20:1
⚡
QPS Calculation
write qps2B × 40 / 86400 × (1/21) ≈ 44,444 writes/sec
peak write qpsAssuming 3× peak factor → 133,333 writes/sec
read qps2B × 40 / 86400 × (20/21) ≈ 888,889 reads/sec
💾
Storage Estimate
daily storage2B × 40 × 100 bytes = 8 TB/day
retention days7
total storage8 TB × 7 = 56 TB
with replication56 TB × 3 (replication factor) = 168 TB
🖥️
Server Estimate
api gatewayAssuming 1 server handles 10K QPS → 925K / 10K = 93 servers
cache layerRedis cluster with 500 MB RAM per node, total 1 TB RAM → ~2000 nodes for hot data
🏗️
Architecture Diagram
Architecture Diagram
          +-------------+
          |   Clients   |
          +------+------+
                 |
         +-------v--------+
         | API Gateway    |
         | (GraphQL +    |
         |  REST Support)|
         +-------+--------+
                 |
    +------------+-------------+
    |                          |
 +--v---+                  +---v---+
 |Cache |                  |Auth   |
 |Layer |                  |Service|
 +--+---+                  +---+---+
    |                          |
    |                          |
 +--v--------------------------v---+
 |       Backend Services (Microservices) |
 +---------------------------------------+
                 |
         +-------v--------+
         |  Database(s)   |
         +----------------+
🧩
Components
API Gateway
Entry point for all client requests, supports both GraphQL and REST APIs
Why thisUsing Apollo Server for GraphQL and Express.js for REST enables flexible query parsing and schema validation with mature ecosystem support
Why notNGINX alone cannot parse or validate GraphQL queries, limiting flexibility and error handling
Cache Layer
Caches frequent query results to reduce backend load and improve latency
Why thisRedis Cluster supports in-memory caching with TTL and pub/sub for cache invalidation, scaling horizontally to handle 925K QPS
Why notMemcached lacks pub/sub and persistence, making cache invalidation and consistency harder at scale
Authentication Service
Validates client tokens and enforces authorization policies
Why thisKeycloak provides OAuth2 and OpenID Connect support with scalable token introspection and fine-grained access control
Why notCustom auth solutions lack maturity and scalability for 2B DAU
Backend Services
Microservices implementing business logic and data aggregation for API responses
Why thisSpring Boot microservices enable modular development and independent scaling per domain, supporting complex GraphQL resolvers and REST endpoints
Why notMonolithic backend would bottleneck scaling and slow deployment cycles
Database(s)
Stores persistent data accessed by backend services
Why thisCassandra chosen for write-heavy workloads with linear scalability and tunable consistency to meet 100ms P99 latency
Why notPostgreSQL requires complex manual sharding at 133K writes/sec; B-tree writes don't scale linearly
🔄
Data Flow
1
Client → API Gateway
Client sends GraphQL or REST query
Gateway parses and validates query against schema
2
API Gateway → Authentication Service
Validate client token and permissions
Reject unauthorized requests early
3
API Gateway → Cache Layer
Check cache for query result
Return cached response if available to reduce latency
4
API Gateway → Backend Services
Forward query to backend if cache miss
Backend resolves data, possibly aggregating multiple sources
5
Backend Services → Database(s)
Read/write persistent data
Use Cassandra for scalable writes and reads
6
Backend Services → Cache Layer
Update cache with fresh query results
Cache invalidation ensures data freshness
7
Backend Services → API Gateway
Return aggregated response
Gateway formats response per client API type
8
API Gateway → Client
Send final response
Ensure 100ms P99 latency SLA

Practice

(1/5)
1. In the cache warming system, at step 3 the Cache Loader fetches data from the database. What happens if the database response is delayed beyond the configured timeout?
easy
A. Cache Loader retries indefinitely until data is fetched, blocking subsequent steps
B. Cache Loader falls back to a secondary cache layer to fetch the data synchronously
C. Cache Loader marks the key as stale and skips warming that key for this cycle
D. Cache Loader writes a null value to cache to prevent cache miss storms

Solution

  1. Step 1: Trace Cache Loader timeout behavior

    On timeout, Cache Loader skips warming that key to avoid blocking the entire warming process.
  2. Step 2: Eliminate retry and fallback options

    Indefinite retries block warming; fallback cache is not part of warming design; null writes risk stale data.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Timeout causes skipping key warming to maintain overall progress [check]
Hint: Timeout skips key warming to avoid blocking cache load [check]
Common Mistakes:
2. In the file sync system's upload flow, at Step 4 the Delta Upload Worker receives chunk hashes from the client. What does the worker do when it finds a chunk hash already stored on the server?
easy
A. Skips uploading that chunk and marks it as already present
B. Queues the chunk for re-chunking to optimize storage
C. Deletes the existing chunk and replaces it with the new one
D. Requests the client to resend the chunk data to verify integrity

Solution

  1. Step 1: Trace Delta Upload Worker behavior at Step 4

    When the worker finds a chunk hash already stored, it skips re-uploading the chunk to save bandwidth and marks it as present.
  2. Step 2: Eliminate incorrect behaviors

    Requesting resend wastes bandwidth; deleting existing chunks breaks deduplication; re-chunking is unrelated to upload step.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Delta Upload Worker skips existing chunks to avoid redundant upload [check]
Hint: Skip chunks with known hashes to save bandwidth [check]
Common Mistakes:
3. If the trace context extraction component is missing in a downstream service, what is the exact failure observed in the distributed trace?
medium
A. The downstream service starts a new root trace, breaking the parent-child relationship in the trace graph
B. The downstream service's spans are merged incorrectly with upstream spans causing duplication
C. Trace data is lost entirely and no spans are recorded for the downstream service
D. The trace collector rejects spans from the downstream service due to missing context

Solution

  1. Step 1: Understand missing context extraction impact

    Without extracting trace context, the downstream service cannot link its spans to the parent trace, so it starts a new root trace, breaking the trace continuity.
  2. Step 2: Eliminate other failure modes

    Spans are not merged incorrectly; they are disconnected. Spans are still recorded locally, so not lost entirely. Trace collector accepts spans but sees them as separate traces.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing extraction causes new root trace, breaking linkage [check]
Hint: No extraction -> new root trace breaks parent-child links [OK]
Common Mistakes:
4. At 10x scale, which component in a Write-Through caching system is most likely to become the bottleneck first, and why?
hard
A. The cache, because synchronous writes increase latency and reduce throughput
B. The application servers, because they block waiting for cache writes to complete
C. The database, because it must handle every write synchronously from both cache and application
D. The network, because cache-to-database communication saturates bandwidth

Solution

  1. Step 1: Identify Write-Through bottleneck

    Write-Through synchronously writes to DB on every write, increasing DB load linearly with scale.
  2. Step 2: Compare other components

    Cache handles fast reads; network bandwidth usually sufficient; app servers block but DB saturation causes overall failure first.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    DB synchronous writes bottleneck Write-Through at scale [check]
Hint: Write-Through sync DB writes bottleneck at scale [check]
Common Mistakes:
5. At 10x traffic scale, which component in a GeoDNS-based global traffic distribution system is most likely to fail first and why?
hard
A. Authoritative DNS servers, because they maintain stateful session info for each client
B. GeoDNS servers, because DNS query rate increases and caching TTLs limit cache effectiveness
C. Data center load balancers, because they cannot handle increased TCP connection counts
D. Network routers, because they cannot route Anycast IPs at scale

Solution

  1. Step 1: Identify GeoDNS scaling bottleneck

    GeoDNS servers handle DNS queries globally; at 10x scale, query volume spikes, and short TTLs reduce cache hits, increasing load.
  2. Step 2: Eliminate other options

    Authoritative DNS servers (A) are stateless per query. Data center load balancers (C) scale horizontally and are not the first bottleneck. Network routers (D) handle Anycast well at scale.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    GeoDNS query load spikes with limited caching cause first failure [check]
Hint: GeoDNS query load spikes first due to limited caching [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