Rate Limiting System Design

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-11-19

Problem Statement

Design a Low-Level Design (LLD) for a Rate Limiter that controls the number of requests a client (user or service) can make to an API within a defined time window. The system should handle high concurrency, multiple clients, and support different limiting strategies.


Functional Requirements (FR)

Core Rate Limiting


•Limit the number of requests a client can make in a given time window.
•Reject requests exceeding the limit with a proper response (429 Too Many Requests).


Rate Limiting Strategies


•Fixed Window Counter: Count requests in discrete fixed intervals.
•Sliding Window Log / Sliding Window Counter: Maintain a rolling window for smoother control.
•Token Bucket: Allow requests if tokens are available; refill tokens periodically.
•Leaky Bucket: Smooth out bursty traffic by processing requests at a fixed rate.


Client-Specific Limits


•Different clients can have different rate limits.
•Support per-user, per-service, or per-API rate limiting.


Concurrency & Thread Safety


•Support multiple simultaneous requests from many clients.
•Ensure counters or token updates are atomic to avoid race conditions.


Metrics & Monitoring (Optional)


•Track number of requests, limit breaches, and system usage metrics.


Non-Functional Requirements (NFR)


•Performance: allowRequest() should ideally run in O(1) time.
•Scalability: Handle thousands of clients with high request volumes.
•Reliability: Prevent race conditions and maintain accurate request counts.
•Extensibility: Add new limiting strategies easily.


Core Classes / Entities


RateLimiter (Interface / Abstract Class)

•Methods: allowRequest(clientId) → returns true if request allowed, else false.


FixedWindowRateLimiter (extends RateLimiter)

•Attributes: windowSize, maxRequests, Map<clientId, counter & windowStartTime>
•Logic: Count requests in the current fixed window; reset when window expires.


SlidingWindowRateLimiter (extends RateLimiter)

•Attributes: windowSize, maxRequests, Map<clientId, Deque<Timestamps>>
•Logic: Track timestamps of requests, remove expired ones for rolling count.


TokenBucketRateLimiter (extends RateLimiter)

•Attributes: bucketCapacity, refillRate, Map<clientId, tokens & lastRefillTime>
•Logic: Add tokens periodically; allow request if tokens > 0.


LeakyBucketRateLimiter (extends RateLimiter)

•Attributes: bucketCapacity, leakRate, Map<clientId, queue>
•Logic: Process requests at fixed rate, drop excess requests.


ClientConfig

•Attributes: clientId, limit, strategyType
•Holds per-client configuration.


Key Operations


•allowRequest(clientId) → Check and update counters/tokens to allow or reject request.
•setLimit(clientId, maxRequests, strategyType) → Configure client-specific limits.
•refillTokens() (for token bucket strategy).


Example Flow


1.Initialize TokenBucketRateLimiter with capacity 10 and refill 2 tokens/sec.
2.Client A sends 5 requests → all allowed.
3.Client A sends 6th request immediately → rejected as no tokens left.
4.Tokens refill at 2 per second → future requests allowed as tokens become available.


Design Considerations


•Use thread-safe data structures (ConcurrentHashMap, atomic counters).
•Support distributed deployment with a centralized store (Redis, DynamoDB) for global limits.
•Consider batching or caching for high-performance lookups.
•Use strategy pattern for easily swapping rate-limiting algorithms.


✅ This is a complete LLD Problem Statement for a Rate Limiting System.

Solution

Comments