Design a rate limiting service

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

Problem Statement

Design a Rate Limiting Service that controls the number of requests a user, client, or IP can make to a system within a specified time window. The system should enforce limits to prevent abuse, throttling, or denial-of-service attacks.


Focus on class design, data structures, algorithms, and concurrency handling, rather than distributed system scaling (which belongs to HLD).


Functional Requirements (FR)


1.Request Limiting
•Allow only a certain number of requests per user/client/IP in a given time window.
•Example policies: 100 requests per minute, 1000 requests per day.
2.Flexible Policies
•Support multiple rate limiting strategies:
•Fixed Window
•Sliding Window
•Token Bucket
•Leaky Bucket
3.Scope of Limits
•Per user, per API key, per IP, or per endpoint.
4.Throttling & Enforcement
•Block or reject requests exceeding the limit.
•Optionally, send a warning when approaching the limit.
5.Monitoring & Metrics
•Track current usage per user/client.
•Provide APIs to query remaining quota.


Non-Functional Requirements (NFR)


•Low Latency – Rate checks should be fast and not add significant overhead.
•Thread Safety – Handle concurrent requests safely.
•Scalability – Efficiently track limits for thousands or millions of clients.
•Accuracy – Enforce limits correctly even under concurrency.
•Extensibility – Easy to add new policies or time windows.


Core Entities & Attributes


Class Key Attributes / Methods

RateLimiter userId/clientId, limit, timeWindow, strategy, allowRequest()

FixedWindowCounter userId → requestCount mapping, windowStartTime, increment(), reset()

SlidingWindowCounter userId → list of request timestamps, increment(), cleanOldRequests()

TokenBucket tokens, refillRate, lastRefillTime, consumeToken()

LeakyBucket queue of requests, leakRate, addRequest(), processQueue()


Service Layer / APIs


•allowRequest(userId) → Returns true/false based on whether request is allowed.
•getRemainingQuota(userId) → Returns remaining requests in current window.
•updatePolicy(userId, limit, timeWindow, strategy) → Update rate limit policy for a user/client.
•resetCounters() → Reset counters periodically (for fixed window).


Design Considerations


1.Data Structures
•HashMap for mapping user/client to counters.
•Queue or deque for sliding window tracking.
2.Concurrency
•Use atomic operations for counters.
•Locks or synchronized structures to avoid race conditions.
3.Algorithms
•Fixed Window: simple counter reset at end of window.
•Sliding Window: track timestamps of requests for accurate sliding calculation.
•Token Bucket: refill tokens at fixed rate, consume per request.
4.Design Patterns
•Strategy pattern for pluggable rate limiting algorithms.
•Singleton for global rate limiter instance (optional).
5.Trade-offs
•Fixed window is simple but can allow burst at window boundary.
•Sliding window is accurate but requires more memory and computation.
•Token bucket balances burst handling and smoothing.


✅ This LLD problem tests:


•OOP and class design skills
•Concurrency and thread-safe counters
•Algorithm selection for rate limiting strategies
•Performance and memory optimization


Solution

Comments