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.
Advanced API Patterns is a depth lesson in the Networking & APIs family of the Thita system design course.
Protocols (REST, gRPC, WebSocket, SSE), API design, pagination, and idempotency.
It sits on the Deep Dive path — worth reading once the Interview Soon lessons are solid, or when a role names this area explicitly.
Advanced API patterns move failures from clear request errors to hidden overload, duplicate work, and broken customer integrations. Interviewers use GraphQL, webhooks, and versioning to test fanout, trust boundaries, retries, compatibility, and blast radius.
GraphQL lets clients choose response shape. That flexibility creates a server-side cost problem. A REST endpoint has a fixed access pattern. A GraphQL query can combine fields in ways the backend team did not predict.
The interview signal: preserve client flexibility while blocking one query from triggering thousands of backend calls.
The classic failure is N+1 queries. A client asks for 100 posts and each post’s author. The resolver fetches posts once, then fetches each author separately. One API request becomes 101 database or service calls.
1query {
2 posts(first: 100) {
3 id
4 title
5 author {
6 id
7 name
8 }
9 }
10}A naive resolver can look clean and still fail under load.
1const resolvers = {
2 Post: {
3 author: (post, _, ctx) => {
4 return ctx.userService.getUser(post.authorId);
5 }
6 }
7};That code does one user lookup per post. If each lookup is a 2 ms network call, 100 posts can produce hundreds of milliseconds of tail latency after connection overhead, queueing, retries, and service contention. The resolver hides the fanout cost.
DataLoader batches and caches loads within a single request. Resolvers enqueue keys. DataLoader performs one batched lookup such as WHERE id IN (...).
Keep DataLoader scoped to the request. A global DataLoader cache can leak data across users unless every cached object is safe to share.
1const userLoader = new DataLoader(async (userIds) => {
2 const users = await db.users.findByIds(userIds);
3 const byId = new Map(users.map(u => [u.id, u]));
4 return userIds.map(id => byId.get(id));
5});
6
7const resolvers = {
8 Post: {
9 author: (post, _, ctx) => ctx.userLoader.load(post.authorId)
10 }
11};The resolver turns 100 user fetches into one batched user fetch. DataLoader also deduplicates repeated IDs inside the same request, so ten posts by the same author cause one lookup.
In interviews, say: “I would create one DataLoader per request for each entity or backend dependency.”
DataLoader reduces round trips. It does not make an expensive query cheap. If a query asks for deeply nested data across large collections, batching reduces call count while the server still does too much work.
| Problem | Bad behavior | Mitigation |
|---|---|---|
| N+1 resolver calls | 1 parent query + N child calls | Request-scoped DataLoader batching |
| Duplicate child IDs | Same entity fetched repeatedly | Per-request DataLoader memoization |
| Deep nested traversal | Exponential backend work | Query depth and complexity limits |
| Cross-service fanout | Many downstream calls per GraphQL request | Batching, timeouts, partial failure rules |
| Authorization per field | Repeated auth checks | Batch auth checks or precompute permissions |
Fetching 100 posts with authors takes 101 calls when each author is loaded alone. DataLoader collects the author ids in one request and fetches them with a single batched lookup.
A query complexity budget assigns a cost to a GraphQL query before execution. The server rejects or throttles queries above the budget. The budget protects the backend from valid GraphQL queries that are unsafe to run.
Depth limits help, but they are too blunt on their own. A depth-4 query can be cheap if it fetches one user. The same depth can be expensive if each level expands to 100 objects. Use depth limits as a guardrail. Use weighted complexity as the main control.
A simple scoring model works for most interviews:
1cost = base_field_cost
2 + list_limit * child_selection_cost
3 + expensive_field_multiplierExample:
1posts(first: 100) {
2 comments(first: 100) {
3 author {
4 name
5 }
6 }
7}That query can imply 10,000 comments before author lookups. DataLoader helps with author batching, but the server still allocates large response objects, hits database limits, and creates slow clients.
The safe move: cap list sizes and enforce a total cost budget per request, tenant, and token.
| Control | What it prevents | Interview answer |
|---|---|---|
| Max depth | Infinite or recursive traversal | Set a depth limit such as 5-8 |
| Max list size | Huge collections per field | Require pagination and cap first or limit |
| Complexity score | Expensive queries that look small | Reject queries above budget before execution |
| Persisted queries | Unknown arbitrary query shapes | Allow pre-approved query hashes for high-scale clients |
| Per-tenant quota | One customer exhausting shared capacity | Rate limit by tenant, token, and operation type |
For public APIs, prefer persisted queries for high-traffic clients. The client sends a query hash. The server executes only registered queries. Product teams keep GraphQL flexibility during development, and production hot paths get predictable query shapes.
GraphQL backfires when the API boundary hides backend cost. Teams adopt it to reduce client-server coordination, then every screen becomes a custom distributed query. Unbounded query shape over high-fanout backends creates the failure.
Pick GraphQL when clients need flexible projections over a bounded domain, such as mobile clients fetching user profile fragments.
Avoid GraphQL as the primary API for:
Use REST or RPC endpoints for those cases. Explicit request and response contracts make scaling, security, observability, and versioning easier.
A clean interview recommendation: use GraphQL for read-heavy composition at the edge. Keep writes explicit. Protect execution with DataLoader, pagination, complexity budgets, and persisted queries.
If the interviewer asks why you would avoid “GraphQL everywhere,” answer: predictable operations are easier to scale, observe, secure, and version.
A webhook is an outbound HTTP call from your system to a customer-controlled endpoint. Your reliability now depends on customer code, infrastructure, DNS, TLS, and deploys.
Use at-least-once delivery. Expect duplicates, delays, and permanent failures.
Avoid designing webhooks like internal RPC. Internal RPC usually assumes both sides share operational standards. Webhooks cross a trust and reliability boundary. Add signatures, retries, idempotency, dead-letter handling, and customer-visible delivery status.
A good webhook event has a stable envelope:
1{
2 "event_id": "evt_123",
3 "event_type": "payment.succeeded",
4 "created_at": "2026-01-12T10:30:00Z",
5 "api_version": "2026-01-01",
6 "data": { "payment_id": "pay_456", "amount": 2500 }
7}event_id is the dedupe key. Receivers use it for idempotency. Your system uses it for tracing, retries, support, and deduplication.
Sign webhook payloads so the receiver can verify the request came from you and was not modified. Use HMAC-SHA256 with a per-endpoint secret.
Sign the timestamp plus raw request body. Avoid signing parsed JSON because parsing can change whitespace, ordering, or number formatting.
A common header design:
1X-Webhook-Timestamp: 1768213800
2X-Webhook-Signature: v1=hex(hmac_sha256(secret, timestamp + "." + raw_body))Receiver-side verification should check three things:
1def verify(secret, timestamp, raw_body, signature):
2 msg = f"{timestamp}.{raw_body}".encode()
3 expected = hmac_sha256_hex(secret, msg)
4 if abs(now() - int(timestamp)) > 300:
5 return False
6 return constant_time_equal(f"v1={expected}", signature)Support secret rotation by allowing two active secrets per endpoint for a short overlap window. Avoid one shared secret across all customers. A leaked shared secret turns one customer incident into a platform-wide incident.
Webhook delivery should use exponential backoff with jitter. Retry immediately once only when the failure looks transient, such as a connection reset. After that, back off to avoid amplifying a customer outage.
A reasonable schedule starts with seconds, then minutes, then hours. Stop automatic retries after one to three days based on business impact.
Treat HTTP results differently:
| Result | Meaning | Action |
|---|---|---|
2xx | Receiver accepted event | Mark delivered |
400/401/403/404 | Bad endpoint, config, or auth in most cases | Surface to customer and avoid aggressive retries |
408/429/5xx | Timeout, rate limit, or server failure | Retry with exponential backoff and jitter |
| Network error | Endpoint unreachable or TLS/DNS failure | Retry with backoff |
| Repeated failure | Endpoint unhealthy | Move to DLQ and alert customer |
Idempotency is mandatory because retries create duplicates. The receiver should store processed event_id values and ignore repeats. Your platform should also avoid duplicate events from upstream jobs, but the receiver still needs dedupe because HTTP cannot guarantee exactly-once delivery.
A dead-letter queue stores events that cannot be delivered after the retry policy ends. The DLQ should retain enough data to replay safely:
Give customers a replay button or API. Support teams should not need database access to recover a webhook integration.
A webhook platform needs a per-endpoint circuit breaker because one broken customer endpoint can consume all delivery workers. If an endpoint has repeated failures, open the circuit and pause new deliveries for that endpoint. Keep delivery running for healthy endpoints.
A global circuit breaker treats one customer outage like a platform outage. Use endpoint or customer endpoint subscription as the breaker unit.
A simple policy works well:
| State | Condition | Behavior |
|---|---|---|
| Closed | Recent success rate is healthy | Deliver normally |
| Open | Failure threshold exceeded | Pause delivery and schedule probes |
| Half-open | Cooldown elapsed | Send limited test deliveries |
| Closed again | Probe succeeds | Resume normal delivery |
| DLQ | Retry window exhausted | Stop automatic delivery until replay |
Tie the breaker to queue scheduling. If endpoint A is open, workers should skip A and continue processing B, C, and D. Healthy customers should not wait behind failed endpoints.
API versioning manages compatibility. Clients need to know which contract they are using. Servers need a way to change behavior without preserving every historical behavior forever.
The three common strategies are URL versioning, header versioning, and date-based versioning.
| Strategy | Example | Best use | Tradeoff |
|---|---|---|---|
| URL versioning | /v1/payments | Public REST APIs with clear major versions | Simple, but can look like duplicated APIs |
| Header versioning | API-Version: 2026-01-01 | APIs needing cleaner URLs or per-request negotiation | Harder to see in logs and docs without good tooling |
| Date-based versioning | Stripe-Version: 2026-01-01 | Long-lived public APIs with gradual behavior changes | Requires disciplined changelog and compatibility rules |
| Media type versioning | Accept: application/vnd.company.v2+json | Hypermedia-heavy APIs | Too complex for most product APIs |
| GraphQL schema evolution | Add fields, deprecate fields | GraphQL APIs | Breaking changes require client tracking |
For interviews, pick URL versioning for simple public REST APIs unless there is a clear reason to use date-based versions. URL versions are visible, debuggable, cache-friendly, and easy for clients to understand.
If the system resembles payments, billing, or developer platforms with long-lived integrations, pick date-based versioning. Clients often need precise behavior pinned over time.
Versioning rules matter more than syntax:
For GraphQL, prefer additive schema evolution. Add new fields, deprecate old fields, and track field usage before removal. Version the whole GraphQL endpoint only when the schema has diverged so much that compatibility rules are no longer understandable.
Match the API shape to the operational problem.
GraphQL works best for client-driven reads. Webhooks work best for asynchronous outbound notifications. Versioned REST or RPC works best for stable commands and external integrations.
| Need | Pick | Why |
|---|---|---|
| Mobile screen needs partial user, profile, or order data | GraphQL | Client controls projection and reduces overfetching |
| Payment succeeded notification to merchant | Webhook | Receiver reacts asynchronously without polling |
| Create payment, refund order, update address | REST/RPC | Explicit command semantics and clear idempotency |
| Public API with many external clients | Versioned REST | Easier compatibility and documentation |
| High-scale known read path | REST or persisted GraphQL | Predictable query shape and cache behavior |
Use GraphQL at the edge where flexible reads help clients. Use REST/RPC for commands where correctness matters. Use webhooks for event delivery across organizational boundaries.
Interview default: Propose GraphQL only for read-heavy composition. Add request-scoped DataLoader, pagination, query complexity budgets, and persisted queries for high-volume clients.
For webhooks, state at-least-once delivery, HMAC-SHA256 signatures over timestamp plus raw body, exponential backoff with jitter, receiver-side idempotency using event_id, DLQ, replay, and per-endpoint circuit breakers.
For versioning, choose URL versioning for straightforward public REST APIs. Choose date-based versions for long-lived developer platforms where clients need precise behavior pinned.
Common interview failures:
event_id.400 or 401 errors.| Category | 2026 number | Interview use |
|---|---|---|
| General-purpose machine RAM | 512 GiB | Avoid splitting services or sharding small datasets too early |
| Memory-optimized RAM | 4 TB | Large caches and in-memory indexes are realistic |
| High-memory machine RAM | 24 TB | Single-machine memory capacity is much larger than older estimates |
| General-purpose CPU | 128 vCPUs | One service instance can handle substantial batching and JSON work |
| Local SSD | 60 TB | Local fast storage is large enough for queues, caches, and logs on one node |
| Local HDD | 336 TB | Cheap local bulk storage works for retained data that can be rebuilt |
| Datacenter network | 25-100 Gbps | Raw bandwidth is usually enough; service latency and saturation often dominate |
| Same-AZ latency | < 1 ms | Keep hot service dependencies in the same AZ when possible |
| Cross-AZ latency | 1-2 ms | Cross-AZ calls add up in fanout-heavy GraphQL resolvers |
| US-EU latency | 70-90 ms | Cross-region synchronous API calls hurt user-visible latency |
| US-India latency | 150-250 ms | Avoid request paths that synchronously cross this distance |
| Redis GET | < 1 ms | Good for idempotency keys, rate limits, and short-lived dedupe |
| Postgres indexed lookup | 1-5 ms | Indexed reads are cheap; avoid caching blindly |
| S3 first byte | 50-100 ms | Avoid S3 in synchronous hot API paths unless the latency budget allows it |
| CDN edge | 5-30 ms | Good for static API docs, schemas, and cached public resources |
| Redis throughput | 100K-500K ops/sec per instance | One Redis instance can handle many idempotency and rate-limit checks |
| Postgres single primary | 10K-50K TPS | Single Postgres handles many API backends before sharding |
| Postgres scale | Tens of TB before sharding | Avoid sharding at 100 GB |
| Kafka cluster throughput | 1M+ msg/sec | Strong fit for webhook event pipelines and replayable delivery logs |
| Kafka latency | Single-digit ms | Good enough for async event fanout |
| Elasticsearch cluster throughput | 10K-50K queries/sec | Useful for delivery logs and customer-facing event search |
| QPS estimate | DAU × actions/user / 86,400 | Estimate average QPS quickly |
| Peak estimate | 2-3× average | Use peak QPS for capacity planning |
| Storage estimate | writes/day × bytes/write × retention days | Size webhook event logs and DLQs |
| Bandwidth estimate | QPS × avg response size | Validate API and webhook egress cost |