Token Bucket algorithm
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
Token Bucket Behavior
Capacity (max tokens) — maximum burst size allowed.
Refill Rate — number of tokens added per second or per minute.
Refilling Logic
Multi-Client Support
Monitoring
🚫 Non-Functional Requirements
Thread-safe: Handle concurrent requests safely.
🧱 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
2bucket = TokenBucket(capacity=10, refillRate=1 token/sec)1
2Request #1 → allowRequest() → token consumed → tokens left = 9
3Request #2 → allowRequest() → tokens left = 8
4...
5Request #11 → bucket empty → request blocked1
2After 5 seconds → refill adds 5 tokens → available = 51
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 secondsOutput:
1
2Requests allowed: 10
3Requests blocked: 2
4Tokens refilled: 8 (after 4 seconds)📏 Constraints
🧠 Extension Ideas
✅ 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.