This article introduces the Leaky Bucket algorithm, a fundamental technique for smoothing API traffic and preventing system overload. It explains the mechanism of controlling request rates and discusses its application in maintaining system stability and fairness among API consumers. The Leaky Bucket is a key component in designing resilient and scalable distributed systems.
Read original on Medium #system-designRate limiting is a critical mechanism in system design to control the number of requests a server or service receives within a given timeframe. Its primary goals are to prevent resource exhaustion, protect against malicious attacks (like DoS), ensure fair usage among consumers, and maintain overall system stability. Without effective rate limiting, a sudden surge in traffic can lead to service degradation or complete unavailability.
The Leaky Bucket algorithm is an analogy to a bucket with a fixed capacity that leaks at a constant rate. Requests arrive and are added to the bucket. If the bucket is full, arriving requests are dropped (or rejected). Requests are processed and leave the bucket at a constant rate, simulating the 'leak'. This mechanism ensures that the output rate of requests never exceeds a defined maximum, effectively smoothing out bursty traffic.
class LeakyBucket:
def __init__(self, capacity, leak_rate_per_second):
self.capacity = capacity
self.leak_rate = leak_rate_per_second
self.current_tokens = 0
self.last_leak_time = time.time()
def allow_request(self):
current_time = time.time()
time_passed = current_time - self.last_leak_time
# 'Leak' tokens over time
leaked_tokens = time_passed * self.leak_rate
self.current_tokens = max(0, self.current_tokens - leaked_tokens)
self.last_leak_time = current_time
if self.current_tokens < self.capacity:
self.current_tokens += 1
return True
return FalseWhen to Use Leaky Bucket
The Leaky Bucket algorithm is ideal for scenarios where a stable, predictable output rate is paramount, such as protecting downstream services from being overwhelmed or ensuring fair resource allocation. It is less suitable when immediate request processing is critical, as it can introduce delays due to its queuing behavior. For scenarios requiring more flexibility in burst handling, the Token Bucket algorithm might be a better fit.