Design rate limiter
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2023-02-15
Problem Statement
Design a Rate Limiting System that can control and restrict the number of API requests a user, client, or service can make within a given time interval, ensuring fair usage, abuse prevention, and system stability.
Functional Requirements (FR)
Request Limiting
•Limit number of requests per user/client/IP/service within a defined time window.
Policy Support
•Fixed Window (e.g., 100 requests/min).
•Sliding Window.
•Token Bucket.
•Leaky Bucket.
Granularity
Support limits at:
•Global level (all users combined).
•User level (per account).
•API/Endpoint level.
1.API Endpoints
•allowRequest(userId, apiId) → returns allow/deny.
•updatePolicy(userId, policyConfig) → update limits dynamically.
•getUsage(userId) → fetch usage metrics.
Observability
•Track request counts, rejections, and latency.
•Expose metrics for monitoring (Grafana/Prometheus).
Non-Functional Requirements (NFR)
•Scalability → Handle millions of requests/sec.
•Low Latency → Allow/deny decision in < 5 ms.
•Consistency → Rate limits should be enforced globally across distributed instances.
•Fault Tolerance → Must work even during node failures.
•Configurable → Easy to change per-user or per-endpoint limits.
Core Components
API Gateway / Rate Limiter Service
•First entry point for requests.
•Checks limits before forwarding to backend.
Rate Limiting Algorithms
•Fixed Window / Sliding Window Counters.
•Token Bucket / Leaky Bucket.
Distributed Data Store
•Redis / DynamoDB / Cassandra for maintaining counters & tokens.
•Must support atomic increments.
Policy Management Service
•Stores configuration (e.g., 100 requests/min/user).
•Supports dynamic updates.
Monitoring & Alerting
•Collect usage stats.
•Alert on anomalies or abuse.
High-Level Flow
1.User makes a request → API Gateway / Rate Limiter Service intercepts.
2.Service identifies userId + endpoint.
3.Checks counters/tokens from distributed store (e.g., Redis).
4.Applies rate-limiting algorithm.
•If allowed → forward request to backend.
•If denied → return 429 Too Many Requests.
5.Logs metrics for observability.
Scalability & Trade-offs
•Centralized store (Redis) → simple, consistent, but may be bottleneck.
•Sharded counters → scalable, but complex consistency.
•Local + Sync with distributed store → low latency but eventual consistency.
Design Goals
•Ensure fair access across users.
•Prevent system overload due to abuse/spikes.
•Support flexible policies for different APIs.
•Minimize latency impact on normal requests.
✅ This HLD covers API gateway integration, distributed counters, and algorithm choice — common discussion points in system design interviews.