MODULO System Design: Comprehensive Architecture MasterclassLAB

"Rate Limiting Mastery: Token Bucket and Leaky Bucket Algorithms"

Introduction to Rate Limiting

Rate limiting is a crucial technique used to prevent excessive usage of a system, network, or API. It ensures that the system remains responsive and available by limiting the number of requests or actions that can be performed within a specified time frame. In this masterclass, we will delve into the world of rate limiting, focusing on two popular algorithms: Token Bucket and Leaky Bucket.

What is Rate Limiting?

Rate limiting is a mechanism that restricts the number of requests or actions that can be performed within a specified time frame. It is commonly used in various applications, including:

  • API gateways to prevent abuse and ensure fair usage
  • Web servers to prevent denial-of-service (DoS) attacks
  • Network devices to prevent excessive traffic

Token Bucket Algorithm

The Token Bucket algorithm is a widely used rate limiting technique. It works as follows:

  • A bucket is filled with tokens at a constant rate (e.g., 10 tokens per second)
  • Each incoming request consumes one token from the bucket
  • If the bucket is empty, incoming requests are blocked until the bucket is refilled

Here's an example implementation of the Token Bucket algorithm:

import time

class TokenBucket:
    def __init__(self, rate, capacity):
        self.rate = rate  # tokens per second
        self.capacity = capacity  # maximum tokens in the bucket
        self.tokens = capacity
        self.last_update = time.time()

    def consume(self):
        current_time = time.time()
        elapsed_time = current_time - self.last_update
        self.tokens = min(self.capacity, self.tokens + elapsed_time * self.rate)
        self.last_update = current_time

        if self.tokens < 1:
            return False  # not enough tokens
        self.tokens -= 1
        return True  # token consumed

# Example usage:
bucket = TokenBucket(rate=10, capacity=100)
while True:
    if bucket.consume():
        print("Request allowed")
    else:
        print("Rate limit exceeded")
    time.sleep(0.1)

Leaky Bucket Algorithm

The Leaky Bucket algorithm is another popular rate limiting technique. It works as follows:

  • A bucket is filled with water (representing incoming requests) at a variable rate
  • The bucket leaks water at a constant rate (e.g., 10 requests per second)
  • If the bucket is full, incoming requests are blocked until the bucket is empty

Here's an example implementation of the Leaky Bucket algorithm:

import time

class LeakyBucket:
    def __init__(self, rate, capacity):
        self.rate = rate  # requests per second
        self.capacity = capacity  # maximum requests in the bucket
        self.water = 0
        self.last_update = time.time()

    def add_water(self, amount):
        current_time = time.time()
        elapsed_time = current_time - self.last_update
        self.water = max(0, self.water - elapsed_time * self.rate)
        self.water += amount
        self.last_update = current_time

        if self.water > self.capacity:
            return False  # bucket is full
        return True  # water added

# Example usage:
bucket = LeakyBucket(rate=10, capacity=100)
while True:
    if bucket.add_water(1):
        print("Request allowed")
    else:
        print("Rate limit exceeded")
    time.sleep(0.1)

Comparison of Token Bucket and Leaky Bucket Algorithms

| | Token Bucket | Leaky Bucket | | --- | --- | --- | | Mechanism | Consumes tokens from a bucket | Leaks water from a bucket | | Rate Limiting | Strict rate limiting | Average rate limiting | | Burst Tolerance | Allows for bursty traffic | Smooths out bursty traffic | | Implementation | More complex | Less complex |

Real-World Applications

Rate limiting is used in various real-world applications, including:

  • API Gateways: To prevent abuse and ensure fair usage
  • Web Servers: To prevent denial-of-service (DoS) attacks
  • Network Devices: To prevent excessive traffic
  • Cloud Services: To prevent abuse and ensure fair usage

Best Practices

  • Monitor and Analyze Traffic: To understand usage patterns and adjust rate limits accordingly
  • Implement Queueing: To handle requests that exceed rate limits
  • Use Distributed Rate Limiting: To ensure consistency across multiple nodes or instances
  • Test and Validate: To ensure rate limiting is working correctly

Conclusion

Rate limiting is a crucial technique used to prevent excessive usage of a system, network, or API. The Token Bucket and Leaky Bucket algorithms are two popular rate limiting techniques used in various applications. Understanding the strengths and weaknesses of each algorithm is essential for designing effective rate limiting systems.

⚔️ YOUR MISSION

Implement a rate limiting system using the Token Bucket algorithm. The system should allow for a maximum of 10 requests per second and have a bucket capacity of 100 tokens. Test the system by sending requests at a rate of 5 requests per second and observe the output.

Design response
Read the exercise prompt
import time

class TokenBucket:
    def __init__(self, rate, capacity):
        self.rate = rate  # tokens per second
        self.capacity = capacity  # maximum tokens in the bucket
        self.tokens = capacity
        self.last_update = time.time()

    def consume(self):
        current_time = time.time()
        elapsed_time = current_time - self.last_update
        self.tokens = min(self.capacity, self.tokens + elapsed_time * self.rate)
        self.last_update = current_time

        if self.tokens < 1:
            return False  # not enough tokens
        self.tokens -= 1
        return True  # token consumed

bucket = TokenBucket(rate=10, capacity=100)
while True:
    if bucket.consume():
        print("Request allowed")
    else:
        print("Rate limit exceeded")
    time.sleep(0.2)  # send requests at 5 requests per second
WAITING FOR SIGNAL...
BACKNEXT STAGE