API Design for a Frequency Analysis Service
System DesignModel answerLast updated
Design comprehensive input validation, error handling, and operational safeguards for a RESTful endpoint that returns the most common elements from a dataset.
You're building a RESTful service that accepts a collection of elements and returns the most frequently occurring ones. The algorithmic implementation is out of scope—focus instead on designing a production-ready API surface and its surrounding operational concerns.
Your design should address:
-
Request/response schema — Define the HTTP method, path, headers, and JSON structure. Provide a concrete example showing both a valid request and its corresponding success response.
-
Boundary conditions — Specify limits on payload dimensions, element cardinality, result size, element data types, and compression. Justify each choice.
-
Multi-tier validation — Describe what checks occur at the client library, edge layer, and application service, and in what sequence. Explain how you handle schema evolution.
-
Identity and access control — Detail authentication mechanisms for external consumers versus internal services, tenant separation, and permission models.
-
Traffic management — Define rate limiting and quota strategies, including what gets metered and how throttled clients learn when to retry.
-
Safe retries — Design an idempotency mechanism for POST requests. Handle scenarios where the same identifier arrives with different payloads.
-
Time budgets and retry guidance — Allocate time across request phases, specify which HTTP status codes signal timeout conditions, and recommend a client-side retry strategy.
-
Structured error reporting — Create a complete error classification with stable machine-readable codes and a uniform response envelope. Show examples for both client and server errors.
-
Handling partially invalid input — Decide whether to reject requests containing some malformed elements or process valid ones and report what was skipped.
-
Load adaptation — Define behavior when facing oversized but syntactically correct requests: return approximate results, apply sampling, or shed load entirely.
-
Attack surface hardening — Protect against compression exploits, malformed character encodings, excessive JSON depth, ambiguous JSON constructs, and inputs designed to maximize memory or CPU consumption.
-
Operational visibility — Specify structured logging, metric collection, and distributed tracing requirements. Identify data that must be redacted.
-
Quality assurance — Outline pre-deployment testing approaches and production alerting criteria.
Make explicit choices about defaults and articulate the engineering trade-offs behind each decision.
Hints
Hint 1
Start by defining strict defaults: fail fast on ambiguous input, return exact results by default, and make every limit explicit and documented.
Hint 2
Think about the order of validation: run cheap checks (authentication, size limits) before expensive ones (parsing, computation) to protect resources.
Hint 3
Design your error codes to be actionable: clients should know whether to retry, fix their request, or escalate to support based solely on the error code.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
API Design for Frequency Analysis Service
Core Philosophy
The value of this system lies not in the counting logic—that's straightforward—but in treating the API as a reliable contract. Every input must have defined bounds, every failure must carry a stable identifier, every retry must be safe, and incorrect results must never be returned silently. The baseline behavior: strict validation and exact computation, with approximation only as an explicit opt-in.
1. Request/Response Schema
POST /v1/frequency/top
Authorization: Bearer <token>
Content-Type: application/json; charset=utf-8
Content-Encoding: gzip (optional)
Idempotency-Key: <uuid> (recommended)
X-Deadline-Ms: 1500 (optional, server enforces maximum)
Request body:
{
"elements": ["apple", "banana", "apple", "cherry", "banana", "apple"],
"top_n": 2,
"computation_mode": "exact",
"invalid_element_handling": "reject_all"
}
Success response (200):
{
"request_id": "req_a7f3bc...",
"top_elements": [
{"element": "apple", "frequency": 3},
{"element": "banana", "frequency": 2}
],
"is_exact": true,
"metadata": {
"total_elements": 6,
"distinct_elements": 3,
"elements_skipped": 0
}
}
Ties are resolved deterministically: descending by frequency, then lexicographically by element value. If top_n exceeds the distinct count, all distinct elements are returned—this is a valid result, not an error. Deterministic ordering ensures idempotent replays produce byte-identical responses.
2. Boundary Conditions
| Constraint | Value | Reasoning |
|---|---|---|
| Compressed payload | 2 MiB max | Caps network ingress time |
| Uncompressed payload | 8 MiB max | Bounds memory for parsing |
| Compression expansion | 20:1 max | Mitigates decompression attacks |
| Element count | 1–1,000,000 | Keeps p99 latency under 300ms |
top_n | 1–1,000 | Keeps response size manageable |
| Element type | Uniform: all strings XOR all integers | Avoids type coercion ambiguity (1 vs "1") |
| String length | 256 UTF-8 bytes max, no null bytes | Memory bound: n × 256 worst-case |
| Integer range | [−2^53+1, 2^53−1] | JSON safe integer range |
| Compression formats | identity, gzip only | Reduces attack surface |
Floating-point numbers, null, booleans, and nested structures are rejected. Floats are excluded because NaN inequality and signed-zero make equality semantics undefined. Clients needing larger datasets should use an asynchronous batch API instead of requesting raised synchronous limits.
3. Multi-Tier Validation
Client SDK layer:
- Pre-flight checks on element count,
top_nrange, and type uniformity - Provides fast feedback but is never trusted server-side
Edge layer (API gateway/WAF):
- TLS termination and credential validation
- Request-level rate limiting
- Content-Type and Content-Encoding allowlisting (HTTP 415 on mismatch)
- Compressed payload size enforcement via Content-Length and streaming counter (HTTP 413)
- Upload timeout to prevent slowloris attacks (HTTP 408)
Application service:
- Streaming decompression with byte accounting
- Strict streaming JSON parser (enforces depth limits, rejects duplicate keys, validates UTF-8)
- JSON Schema validation against versioned specification
- Semantic validation (top_n bounds, type homogeneity, element constraints)
- Cost-based quota check
- Computation
Ordering matters: cheap authentication and size checks precede expensive parsing and computation.
Schema evolution: Major version in URI path (/v1). Within a major version, only additive changes. Unknown fields cause UNKNOWN_FIELD errors—catches typos like "toop_n" at the cost of requiring client upgrades before using new fields.
4. Identity and Access Control
- External clients: OAuth 2.0 bearer tokens (JWT). Service validates signature, expiration, audience, and required scope
frequency:compute. - Internal services: Mutual TLS with workload identity attestation (e.g., SPIFFE), plus explicit caller allowlist.
- Tenant identity: Always derived from credential, never from request body.
- Isolation: Quotas, idempotency records, and caches are partitioned by tenant identifier.
- Missing/invalid credential → 401
UNAUTHENTICATED. Valid credential lacking scope → 403PERMISSION_DENIED.
5. Traffic Management
Per-tenant token buckets:
- Request rate: 100 req/s sustained, burst to 200
- Computational cost: 50M elements per minute (normalizes small vs large requests)
Daily caps overlay these buckets. Limit violations return HTTP 429 with Retry-After header and RateLimit-* headers per draft RFC. Error codes distinguish causes: RATE_LIMITED (transient) vs QUOTA_EXHAUSTED (wait for reset window).
6. Safe Retries via Idempotency
Service maintains (tenant, Idempotency-Key) → {request_hash, status, response} with 24-hour TTL.
| Scenario | Behavior |
|---|---|
| Matching key and request hash | Replay stored response; add Idempotent-Replayed: true header; no quota charge |
| Matching key, request in flight | HTTP 409 IDEMPOTENCY_IN_PROGRESS; client should retry |
| Matching key, different request hash | HTTP 422 IDEMPOTENCY_KEY_MISMATCH; never retry |
Only 2xx and deterministic 4xx responses are cached. 5xx responses aren't stored, permitting retry to succeed. If idempotency storage is unavailable, the service fails open: computes without storing, emits metric. Risk is duplicate billing, which is acceptable versus service unavailability.
7. Time Budgets and Retry Strategy
Server-side deadline: 2 seconds or client-specified value, whichever is smaller.
| Phase | Budget | Timeout Status |
|---|---|---|
| Body upload | 500ms | 408 REQUEST_TIMEOUT |
| Decompress + parse + validate | 300ms | 504 DEADLINE_EXCEEDED |
| Computation | 1000ms | 504 DEADLINE_EXCEEDED |
| Response serialization | 100ms | 504 DEADLINE_EXCEEDED |
Service checks deadline cooperatively during computation and cancels early when exceeded.
Client retry policy:
- Retry only: 408, 429, 409 (in-progress), 503, 504, connection errors
- Always reuse same idempotency key
- Exponential backoff with full jitter: 200ms base, 2× factor, 5s cap, 3 attempts maximum
- Honor
Retry-Afterheader when present - Never retry other 4xx codes
8. Structured Error Reporting
Uniform envelope:
{
"error": {
"code": "VALIDATION_FAILED",
"http_status": 422,
"retryable": false,
"message": "Request contains 2 invalid elements.",
"request_id": "req_a7f3bc...",
"details": [
{"path": "/elements/17", "issue": "STRING_TOO_LONG", "max_length": 256},
{"path": "/elements/42", "issue": "MIXED_TYPES", "expected_type": "string"}
]
}
}
Client errors (4xx):
- 400:
MALFORMED_JSON,INVALID_UTF8,DUPLICATE_JSON_KEY,NESTING_TOO_DEEP - 401:
UNAUTHENTICATED - 403:
PERMISSION_DENIED - 408:
REQUEST_TIMEOUT - 409:
IDEMPOTENCY_IN_PROGRESS - 413:
PAYLOAD_TOO_LARGE - 415:
UNSUPPORTED_MEDIA_TYPE - 422:
VALIDATION_FAILED,TOP_N_OUT_OF_RANGE,UNKNOWN_FIELD,IDEMPOTENCY_KEY_MISMATCH - 429:
RATE_LIMITED,QUOTA_EXHAUSTED
Server errors (5xx):
- 500:
INTERNAL_ERROR - 503:
SERVICE_OVERLOADED - 504:
DEADLINE_EXCEEDED
Clients branch on code, not HTTP status, for maximum forward compatibility.
9. Handling Partially Invalid Input
Default: "invalid_element_handling": "reject_all" fails the entire request if any element violates constraints (HTTP 422 with details array).
Opt-in: "invalid_element_handling": "skip_invalid" processes valid elements, returns results, and reports skipped count in metadata.elements_skipped with warning-level details. This mode only skips element-level issues (oversized strings, type mismatches), not structural problems (malformed JSON).
10. Load Adaptation
When facing well-formed but oversized payloads:
- Default (
"computation_mode": "exact"): Reject if exceeding element count limit (HTTP 422). - Opt-in (
"computation_mode": "approximate"): Apply reservoir sampling or Count-Min Sketch. Response includes"is_exact": falseand"approximation_error_bound": 0.05. Service may still reject if approximate computation would exceed deadline. - Severe overload: HTTP 503 with exponential backoff in
Retry-After, regardless of mode.
Load shedding priority: reject new exact-mode requests before approximate-mode requests.
11. Attack Surface Hardening
- Compression bombs: Enforce 20:1 expansion ratio during streaming decompression; abort and return 413.
- Character encoding: Require valid UTF-8; reject on invalid sequences (400
INVALID_UTF8). - JSON depth: Cap nesting at 10 levels (400
NESTING_TOO_DEEP). - Duplicate keys: Strict mode rejects duplicate JSON keys (400
DUPLICATE_JSON_KEY). - Adversarial cardinality: Element count limit indirectly caps distinct element count, bounding hash table size.
- Algorithmic complexity: Use hash functions with randomized seeds per request to prevent hash collision DoS.
12. Operational Visibility
Structured logging:
- Every request:
request_id,tenant_id,endpoint,status,latency_ms,element_count,top_n - Errors:
error_code,error_message - Redact: credential values, element content (log only hashes for debugging)
Metrics:
- Request rate, latency (p50/p90/p99), error rate by code
- Quota utilization per tenant
- Idempotency cache hit rate
- Payload size distribution
- Computation mode breakdown (exact vs approximate)
Distributed tracing:
- Trace across gateway → service → dependencies
- Annotate spans with
element_count,top_n,computation_mode - Never include PII or element values in span attributes
13. Quality Assurance
Pre-deployment testing:
- Unit: Schema validation, error envelope structure, idempotency logic
- Integration: Authentication flows, quota enforcement, timeout handling
- Load: Sustained traffic at 2× expected peak, measure p99 latency and error rates
- Chaos: Kill dependencies, inject latency, exhaust quotas; verify graceful degradation
- Fuzz: Malformed JSON, oversized payloads, compression bombs, invalid UTF-8
Production monitoring:
- Alert: Error rate >1%, p99 latency >1.5s, quota exhaustion for any tenant
- Dashboard: Request volume, top error codes, idempotency replay rate, approximate-mode adoption
- Canary: Deploy to 5% traffic, monitor for 1 hour, auto-rollback on elevated errors