Token Bucket Algorithm Implementation
📖 Scenario: You are building a simple rate limiter for an API using the token bucket algorithm. This algorithm controls how many requests a user can make in a given time by using tokens that refill over time.
🎯 Goal: Create a Python program that simulates a token bucket rate limiter. You will set up the initial bucket, configure the refill rate, implement the token consumption logic, and finally print whether a request is allowed or denied based on available tokens.
📋 What You'll Learn
Create a dictionary called
token_bucket with keys 'capacity' and 'tokens' set to 10 and 10 respectively.Create a variable called
refill_rate and set it to 2 (tokens per second).Write a function called
consume_tokens that takes tokens_needed and reduces tokens if enough are available, returning True if allowed, False otherwise.Print the result of calling
consume_tokens(5).💡 Why This Matters
🌍 Real World
Token bucket algorithms are used in APIs and networks to limit how many requests or data packets can be processed in a given time, preventing overload.
💼 Career
Understanding rate limiting is important for backend developers and network engineers to build reliable and fair services.
Progress0 / 4 steps