Design API Rate Limiter

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-04-28

Problem Statement

Design a rate limiter that restricts the number of API requests a client can make in a given time window. This is a common system component to prevent abuse, control load, and ensure fair usage. The focus is on class design, data structures, and concurrency handling.


Functional Requirements


1.Limit API Requests
•Limit requests per client (identified by API key or user ID).
•Example: max 100 requests per minute per client.
2.Allow / Reject Requests
•Expose a method isAllowed(clientId) that returns true if the request is allowed, false otherwise.
3.Reset / Sliding Window
•Support fixed window, sliding window, or token bucket algorithms.
4.Optional Features
•Different limits for different API endpoints or client tiers (e.g., free vs premium).
•Burst handling for short-term traffic spikes.


Non-Functional Requirements


•Performance: Low-latency response for isAllowed checks.
•Scalability: Support millions of clients and high request throughput.
•Thread Safety: Handle concurrent requests from multiple threads.
•Memory Efficiency: Efficiently store request counts for many clients.


Edge Cases & Constraints


•Clients sending bursts of requests → rate limiter must enforce limits accurately.
•Time window boundaries → requests at window edges should be handled correctly.
•High concurrency → avoid race conditions.
•Multiple rate-limiting strategies may be needed.


Design Hints


•Key Classes / Interfaces:
•RateLimiter → main API exposing isAllowed(clientId).
•ClientRequestTracker → tracks requests per client (timestamped).
•RateLimitPolicy → defines limit (requests per time window) and algorithm type.
•Data Structures:
•HashMap<ClientId, List<Timestamps>> → for sliding window approach.
•Queue / Deque → efficiently maintain timestamps within the window.
•Counters with reset time → for fixed window approach.
•Design Patterns:
•Strategy Pattern → for different rate-limiting algorithms (FixedWindow, SlidingWindow, TokenBucket).
•Singleton → for centralized rate limiter instance.


Example Flow


1.Client A calls isAllowed("A") → check current request count within the window.
2.If count < limit → allow request, record timestamp.
3.If count ≥ limit → reject request.
4.Repeat as requests come in; older timestamps expire automatically based on window.


Evaluation Areas


•Clean class and API design.
•Correct implementation of time-window logic.
•Concurrency handling and thread-safe updates.
•Flexibility to support different algorithms and policies.
•Memory and performance efficiency for large-scale clients.


Solution


Comments