Choose the Right Approach:
- Scenario: Let's imagine an API server handling multiple clients.
- Simple Token Bucket: Good for allowing bursts up to a limit. Not strictly "fair" in scheduling terms (who gets the CPU next?), but good for rate limits.
- Sliding Window Log/Counter: More accurate than fixed window, but slightly higher memory/CPU.
- Fair Queueing (simplified): A priority queue where the "virtual finish time" determines who gets served. This is the most robust interpretation of "fairness" in computer networking, but might be overkill for a simple "API rate limiter" code snippet unless specified.
- Weighted Round Robin / Token Bucket per User: This is the most practical implementation for a coding interview-style question. It ensures User A with a high quota doesn't starve User B with a low quota if they arrive simultaneously, simply by processing requests.
Decision: I will implement a Token Bucket strategy per client, but wrapped in a manager that handles concurrency. To specifically address "Fairness" beyond just "Rate Limiting", I should explain the difference between limiting a specific user vs global resource protection.
Better Approach for "Fairness": Generalized Cell Rate Algorithm (GCRA) or Sliding Window. However, often "Fairness" in interviews implies preventing the "noisy neighbor" problem.
Let's stick to a robust per-user Token Bucket implementation (standard in industry - e.g., AWS, Stripe) because it allows for some bursting (which users like) but enforces a strict average rate (fair to the system).
Correction: "Fairness" usually implies Weighted Fair Queuing or simply ensuring that the rate limiter doesn't allow a user to monopolize the connection pool.
Let's refine: I will implement a Sliding Window Counter or Token Bucket. Why? Because the "Fairness" aspect usually refers to Global Rate Limiting (limiting the whole system) vs User Rate Limiting.
Actually, a very specific interpretation of "Fair Rate Limiting" is Craq (Cancellation, Reordering, and Queuing) or just simply ensuring no starvation.
Let's go with a standard Token Bucket per client. It's the industry standard for "fair" traffic shaping because it limits the rate, not just the count.
Wait, let's look at the "Fairness" keyword again.
If I have 10 request slots/sec, and User A sends 100 requests and User B sends 10.
Strict FIFO: User A might fill the queue.
Fairness: User A gets 5, User B gets 5? No, that's equal division.
Fairness usually means: Enforcing the defined limits strictly so User A doesn't exceed their allocation, preventing them from degrading service for User B.
So, a Per-User Rate Limiter is the fairness mechanism.
Plan:
- Create a
RateLimiter interface.
- Implement a Token Bucket algorithm.
- Capacity (Burst size).
- Refill Rate.
- Implement a User-Bucket Map to track individual users.
- Use a background thread (goroutine/async task) or lazy refilling to add tokens.
- Demonstrate concurrent access.
Language: Go (Golang) is perfect for this because concurrency is built-in, and rate limiters are common in backend services. Python is also good but GIL makes concurrency examples trickier. Java is verbose. Let's use Go for a robust backend example, or Python for readability.
I'll choose Python for maximum readability, using a Class-based structure. It's easier for a general audience to grasp the algorithm logic without getting bogged down in syntax.
Refining the "Fairness" concept in code:
To make it "Fair", I should implement Weighted Fair Queuing concepts?
No, that's too complex for a single file program.
I will interpret "Fairness" as:
- Multi-tenancy: Handling multiple users independently (Noisy Neighbor prevention).
- Algorithm: Token Bucket is generally considered "fair" because it enforces an average rate, preventing a user from flooding the server at exact second boundaries (unlike Fixed Window).
Algorithm Choice: Token Bucket.
tokens: Current token count.
max_tokens: Bucket size.
refill_rate: Tokens per second.
last_refill_time: Timestamp.
Writing the Code (Iterative Refinement):
- Class
TokenBucketLimiter:
__init__(rate, capacity)
consume(tokens=1)
- Class
FairRateLimiter:
- Manages a dictionary of
TokenBucketLimiter.
- Clean up old users (optional, but good practice).
Self-Correction: The prompt asks for "Fairness".
In queueing theory, "Fair Queueing" means serving flows in round-robin.
If User A has 100 packets and User B has 10, Fair Queueing serves A, B, A, B... until B is empty, then A.
Rate Limiting is slightly different. It says "User A is allowed 10 req/s".
I will stick to the Per-User Token Bucket approach but add a comment explaining that this ensures fairness by isolating user resources (Noisy Neighbor problem).
Code Implementation Details:
- Use
time.monotonic() for time.
- Use
threading.Lock for thread safety.