Token Bucket algorithm

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-18

Problem Statement

Design the Low-Level Design (LLD) of a Token Bucket algorithm, which is a rate-limiting mechanism used in APIs, network systems, or distributed applications to control the rate of incoming requests.


Your task is to model the classes, attributes, and behaviors that implement a configurable Token Bucket rate limiter, ensuring that no client or service exceeds the allowed rate of requests.


🧩 Functional Requirements

Rate Limiting

•Each client or API has a token bucket that controls how many requests it can make per unit time.
•Requests are allowed only if a token is available; otherwise, they are throttled or delayed.

Token Bucket Behavior

•Each bucket has:

Capacity (max tokens) — maximum burst size allowed.


Refill Rate — number of tokens added per second or per minute.

•Every request consumes one token.
•If bucket is empty → request is denied or queued.

Refilling Logic

•Tokens are added periodically (e.g., every second) up to the capacity limit.
•The refill should be thread-safe and non-blocking.

Multi-Client Support

•The system should support multiple users or API endpoints, each having its own rate limit configuration (capacity + refill rate).

Monitoring

•Allow querying of:
•Current tokens available.
•Last refill time.
•Allowed/blocked request count (optional).


🚫 Non-Functional Requirements

Thread-safe: Handle concurrent requests safely.


•Accurate: Token refill timing must reflect real time.
•Extensible: Support future enhancements like sliding-window rate limiting.
•Low latency: Should not block incoming requests unnecessarily.


🧱 Suggested Classes


ClassResponsibility


TokenBucket


Core class representing a single token bucket. Manages tokens, refill, and consumption.


RateLimiter


Interface or wrapper managing multiple token buckets per client or endpoint.


BucketRefillStrategy


Defines how and when tokens are refilled (e.g., fixed-interval, timer-based).


RequestHandler


Consumes tokens before allowing a request to proceed.


Clock / TimeProvider


Utility to fetch current time (useful for testing).


Metrics (optional)


Collects statistics (requests allowed, denied).


⚙️ Class-Level Overview

1 2TokenBucket 3 ├── capacity: int 4 ├── tokens: double 5 ├── refillRate: double # tokens per second 6 ├── lastRefillTime: long 7 ├── synchronized boolean allowRequest() 8 └── void refill() 9 10RateLimiter 11 ├── Map<clientId, TokenBucket> 12 ├── boolean isAllowed(clientId) 13 └── void registerClient(clientId, capacity, refillRate)

🔄 Example Flow

1.Initialization
1 2bucket = TokenBucket(capacity=10, refillRate=1 token/sec)
1.Incoming Requests
1 2Request #1 → allowRequest() → token consumed → tokens left = 9 3Request #2 → allowRequest() → tokens left = 8 4... 5Request #11 → bucket empty → request blocked
1.Refill
1 2After 5 seconds → refill adds 5 tokens → available = 5
1.Multi-Client Example
1 2clientA → 5 tokens/sec 3clientB → 10 tokens/sec 4Each has its own independent bucket.


🧪 Example Input / Output


Input:

1 2RateLimiter: 3 clientA: capacity=10, refillRate=2/sec 4 clientB: capacity=5, refillRate=1/sec 5Requests: 6 clientA makes 12 requests in 4 seconds


Output:

1 2Requests allowed: 10 3Requests blocked: 2 4Tokens refilled: 8 (after 4 seconds)


📏 Constraints


•Max clients: 10⁴
•Min token refill granularity: 1 per second
•Time precision: milliseconds
•Threading: multiple threads may call allowRequest() concurrently


🧠 Extension Ideas


•Add burst allowance or weighted tokens.
•Support asynchronous refill scheduler.
•Integrate with API gateway or reverse proxy.
•Include distributed caching (Redis) for cross-instance token tracking.


✅ In short:


Design a Token Bucket rate limiter that manages per-client request quotas by maintaining a refillable bucket of tokens. Each request consumes a token; if no tokens remain, requests are throttled.


Your design should focus on object modeling, concurrency control, and refill logic.

Solution

Comments