The user wants me to engineer a rate limiter library.
This library needs to support three specific algorithms:
Token Bucket
Leaky Bucket
Sliding Window
I need to design this as a production-quality library, likely in a popular language like Python or Java. I'll choose Python for readability and ease of demonstrating concepts, but structure it so it could be ported to a statically typed language or used with a distributed backend (like Redis) later.
Core Requirements:
Algorithms: Implementation of the three specified.
Interface: A clean, unified API for users.
Storage: An abstract storage layer. In-memory for basic usage, but extensible for distributed systems (Redis/Memcached).
Return types: A result object indicating allowed/denied, remaining tokens/time, retry-after time.
Storage Backend:
Since I'm writing a library, I shouldn't hardcode a dictionary. I should define an interface Storage and provide a default InMemoryStorage. I will add a note about Redis implementation.
Algorithm Implementations:
Token Bucket: Good for bursty traffic. Key parameters: capacity (max burst), refill_rate (tokens/sec). Logic: Check current tokens. If enough, deduct and allow. If not, deny. Refill based on time elapsed.
Leaky Bucket: Good for smoothing traffic to a constant rate. Key parameters: capacity (queue size), leak_rate (requests/sec). Logic: Add request to queue if space. "Leak" requests at a constant interval.
Sliding Window (Log/Counter): Good for strict limits (e.g., "100 requests per minute"). Key parameters: limit, window_size. Logic: Keep timestamps of requests. Count timestamps within (now - window_size). If count < limit, allow and add timestamp.
Analytics:
The prompt asks for "sliding window analytics." This usually means providing insights into usage patterns, not just a boolean pass/fail.
I should return metadata with the rate limit check: allowed, remaining, retry_after, current_usage.
Structure of the Code:
Contracts/Exceptions: Define custom exceptions and result types.
Storage Interface: Abstract Base Class for storage.
Algorithms:
TokenBucket
LeakyBucket
SlidingWindowCounter (Standard approach for distributed systems) or SlidingWindowLog (Exact approach). I'll implement the Log approach for precision as requested by "analytics".
State: List of timestamps (or a sorted set in Redis).
Logic: Remove timestamps < now - window.
Check: if len(timestamps) < limit: append(now); return True.
Language Choice: Python is best here for clarity. I will use dataclasses for structure and abc for interfaces.
Adding "Engineering" Polish:
Thread safety (using locks in the in-memory implementation).
Type hinting.
Docstrings.
Example usage.
Step-by-Step Implementation Plan:
Define RateLimitResult dataclass.
Define Storage ABC.
Implement InMemoryStorage.
Implement TokenBucket class.
Implement LeakyBucket class.
Implement SlidingWindow class (Log implementation for analytics).
Create a Factory/Manager to tie it all together.
Write a usage example.
Self-Correction during thought process:
The "Leaky Bucket" usually implies processing requests at a fixed rate. In a library context, strictly implementing a queue requires background processing (a consumer). For a rate limiting library (synchronous check), we model it as a "meter." The check calculates how much has leaked since the last check. If there is room in the bucket, we add water. If the bucket overflows, we deny. This is the standard algorithmic interpretation for middleware.
Analytics Specifics:
The user asked for "Sliding Window Analytics." This might mean returning the actual data points in the window for analysis (e.g., "show me traffic spikes"). I should include a method like get_usage_history(key) specifically for the sliding window implementation.
Let's write the code.
Here is a complete, production-ready Python library for rate limiting. It includes an abstract interface, thread-safe in-memory storage, and implementations for Token Bucket, Leaky Bucket, and Sliding Window algorithms.
Library Architecture
The library is designed with an ABC (Abstract Base Class) to ensure all limiters share the same interface. This allows you to swap strategies easily (e.g., moving from Token Bucket to Sliding Window) without changing your application logic.
1. Core Interfaces and Data Structures
python
import time
import math
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional, Dict, Any
@dataclass
class RateLimitState:
"""Return object describing the state of the limit."""
allowed: bool
remaining: int
limit: int
retry_after_seconds: float
reset_timestamp: float
class RateLimiterBackend(ABC):
"""
Abstract interface for a rate limiter backend.
Implementations can be In-Memory, Redis, Memcached, etc.
"""
@abstractmethod
def attempt(self, key: str, cost: int = 1) -> RateLimitState:
"""Try to consume 'cost' units of capacity."""
pass
@abstractmethod
def get_state(self, key: str) -> RateLimitState:
"""Check current state without consuming capacity."""
pass
2. In-Memory Storage (Thread-Safe)
For local applications or testing. Uses threading.Lock to ensure concurrency safety.
Best for: Allowing bursty traffic while maintaining an average rate.
Logic: A bucket fills with tokens at a fixed rate up to a max capacity. A request consumes a token. If empty, request denied.*
python
class TokenBucketLimiter(RateLimiterBackend):
def __init__(self, storage: InMemoryStorage, rate: float, capacity: int):
"""
:param rate: Tokens added per second.
:param capacity: Maximum bucket size (burst size).
"""
self.storage = storage
self.rate = rate
self.capacity = capacity
def _calculate_state(self, key: str) -> RateLimitState:
now = time.time()
data = self.storage.get(key)
if not data:
# Initialize: tokens, last_update
return None
tokens, last_update = data
elapsed = now - last_update
# Refill tokens
tokens = min(self.capacity, tokens + (elapsed * self.rate))
return tokens, now
def attempt(self, key: str, cost: int = 1) -> RateLimitState:
with self.storage.get_lock():
now = time.time()
data = self.storage.get(key)
if not data:
current_tokens = self.capacity - cost
self.storage.set(key, (current_tokens, now))
return RateLimitState(True, int(current_tokens), self.capacity, 0.0, now + 1.0)
old_tokens, last_update = data
# Calculate Refill
elapsed = now - last_update
current_tokens = min(self.capacity, old_tokens + (elapsed * self.rate))
if current_tokens >= cost:
new_tokens = current_tokens - cost
self.storage.set(key, (new_tokens, now))
return RateLimitState(True, int(new_tokens), self.capacity, 0.0, now)
else:
# Calculate wait time
deficit = cost - current_tokens
retry_after = deficit / self.rate
# Do not update state, just return failure
return RateLimitState(False, 0, self.capacity, retry_after, now + retry_after)
def get_state(self, key: str) -> RateLimitState:
with self.storage.get_lock():
now = time.time()
data = self.storage.get(key)
if not data:
return RateLimitState(True, self.capacity, self.capacity, 0.0, now)
tokens, last_update = data
current_tokens = min(self.capacity, tokens + ((now - last_update) * self.rate))
return RateLimitState(True, int(current_tokens), self.capacity, 0.0, now)
Algorithm 2: Leaky Bucket
Best for: Smoothing traffic to a strict constant output rate (no bursts).
Logic: Requests enter a queue (bucket). The queue empties at a constant rate. If the queue is full, request denied.*
python
class LeakyBucketLimiter(RateLimiterBackend):
def __init__(self, storage: InMemoryStorage, rate: float, capacity: int):
"""
:param rate: Requests processed per second (leak rate).
:param capacity: Maximum queue size.
"""
self.storage = storage
self.rate = rate
self.capacity = capacity
# Inverse of rate: time per request
self.per_request_time = 1.0 / rate
def attempt(self, key: str, cost: int = 1) -> RateLimitState:
with self.storage.get_lock():
now = time.time()
data = self.storage.get(key)
# 'level' represents the current water level in the bucket
# 'last_leak' is the timestamp the bucket was last processed
if not data:
level = cost
self.storage.set(key, (level, now))
return RateLimitState(True, self.capacity - level, self.capacity, 0.0, now)
level, last_leak = data
# Calculate how much water has leaked out since last time
elapsed = now - last_leak
leaked_amount = elapsed * self.rate
# Decrease level, ensure it doesn't go below 0
level = max(0, level - leaked_amount)
if level + cost <= self.capacity:
level += cost
self.storage.set(key, (level, now))
# Calculate retry_after based on current queue depth
# When will the current request be processed? It waits for (level/rate) roughly
wait_time = level / self.rate
return RateLimitState(True, int(self.capacity - level), self.capacity, 0.0, now + wait_time)
else:
# Bucket overflow
retry_after = (level + cost - self.capacity) / self.rate
return RateLimitState(False, 0, self.capacity, retry_after, now + retry_after)
def get_state(self, key: str) -> RateLimitState:
with self.storage.get_lock():
now = time.time()
data = self.storage.get(key)
if not data:
return RateLimitState(True, self.capacity, self.capacity, 0.0, now)
level, last_leak = data
elapsed = now - last_leak
current_level = max(0, level - (elapsed * self.rate))
return RateLimitState(True, int(self.capacity - current_level), self.capacity, 0.0, now)
Algorithm 3: Sliding Window Log
Best for: Strict rate limiting and detailed analytics.
Logic: Keeps a log of timestamps for every request. If count(timestamps in last window) < limit, allow.*
python
from collections import deque
class SlidingWindowLimiter(RateLimiterBackend):
def __init__(self, storage: InMemoryStorage, limit: int, window_seconds: int):
self.storage = storage
self.limit = limit
self.window_seconds = window_seconds
def _clean_window(self, queue: deque, now: float):
# Remove timestamps older than the window
while queue and queue[0] <= now - self.window_seconds:
queue.popleft()
def attempt(self, key: str, cost: int = 1) -> RateLimitState:
with self.storage.get_lock():
now = time.time()
queue = self.storage.get(key)
if not queue:
queue = deque()
self._clean_window(queue, now)
current_count = len(queue)
if current_count + cost <= self.limit:
# Add request(s) to log
for _ in range(cost):
queue.append(now)
self.storage.set(key, queue)
reset_at = now + self.window_seconds
return RateLimitState(
allowed=True,
remaining=self.limit - len(queue),
limit=self.limit,
retry_after_seconds=0.0,
reset_timestamp=reset_at
)
else:
# Calculate retry after: Time until the oldest request expires
oldest = queue[0]
retry_after = oldest + self.window_seconds - now
return RateLimitState(False, 0, self.limit, retry_after, oldest + self.window_seconds)
def get_state(self, key: str) -> RateLimitState:
with self.storage.get_lock():
now = time.time()
queue = self.storage.get(key)
if not queue:
return RateLimitState(True, self.limit, self.limit, 0.0, now + self.window_seconds)
self._clean_window(queue, now)
count = len(queue)
remaining = max(0, self.limit - count)
reset_at = queue[0] + self.window_seconds if queue else now + self.window_seconds
return RateLimitState(remaining > 0, remaining, self.limit, 0.0, reset_at)
def get_analytics(self, key: str) -> Dict:
"""Specific to Sliding Window: Get detailed timestamps for graphing."""
with self.storage.get_lock():
data = self.storage.get(key)
if not data: return {"count": 0, "timestamps": []}
self._clean_window(data, time.time())
return {"count": len(data), "timestamps": list(data)}
Usage Example
Here is how you would integrate this library into an application context (e.g., simulating an API gateway).
python
def main():
# Setup
storage = InMemoryStorage()
print("--- 1. Token Bucket (Burst Allowed) ---")
# 5 requests/sec, burst of 10
limiter = TokenBucketLimiter(storage, rate=5, capacity=10)
# Simulate Burst
for i in range(12):
res = limiter.attempt("user_123_api")
print(f"Req {i+1}: {'OK' if res.allowed else 'BLOCKED'} | Remaining: {res.remaining} | Retry: {res.retry_after_seconds:.2f}s")
print("\n--- 2. Leaky Bucket (Strict Rate) ---")
storage2 = InMemoryStorage()
# 2 requests/sec, buffer of 5
limiter2 = LeakyBucketLimiter(storage2, rate=2, capacity=5)
# Fill the bucket quickly
for i in range(6):
res = limiter2.attempt("user_456_api")
print(f"Leak {i+1}: {'OK' if res.allowed else 'OVERFLOW'}")
print("Waiting 1.5 seconds (should allow ~3 requests to process)...")
time.sleep(1.5)
res = limiter2.attempt("user_456_api")
print(f"After wait: {'OK' if res.allowed else 'OVERFLOW'}")
print("\n--- 3. Sliding Window Analytics ---")
storage3 = InMemoryStorage()
# 5 requests per 10 seconds
limiter3 = SlidingWindowLimiter(storage3, limit=5, window_seconds=10)
for i in range(6):
res = limiter3.attempt("user_789_api")
print(f"Slide {i+1}: {'OK' if res.allowed else 'LIMIT'}")
# Get Analytics Data
data = limiter3.get_analytics("user_789_api")
print(f"Analytics: Saw {data['count']} requests in window.")
if __name__ == "__main__":
main()
Comparison of Strategies
Token Bucket (TokenBucketLimiter):
Pros: Allows bursting (saving up tokens for a spike), memory efficient.
Cons: Can potentially saturate downstream services if the burst is large.
Use Case: General API limiting, allowing users to "save up" quota.
Leaky Bucket (LeakyBucketLimiter):
Pros: Smooths traffic perfectly to a constant rate. Protects downstream systems from spikes entirely.
Cons: Does not allow bursting; strict latency on the queue.
Use Case: Payment processing, database write operations, or interacting with legacy systems that cannot handle spikes.
Sliding Window (SlidingWindowLimiter):
Pros: Most accurate enforcement (no "burst" ambiguity), provides rich analytics (actual timestamps).