0
0
Rest APIprogramming~30 mins

Token bucket algorithm in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Set up the token bucket dictionary
Create a dictionary called token_bucket with keys 'capacity' and 'tokens' both set to 10.
Rest API
Need a hint?

Use curly braces to create a dictionary with the exact keys and values.

2
Add the refill rate variable
Create a variable called refill_rate and set it to 2.
Rest API
Need a hint?

Just assign the number 2 to the variable named refill_rate.

3
Write the token consumption function
Write a function called consume_tokens that takes a parameter tokens_needed. Inside, check if token_bucket['tokens'] is at least tokens_needed. If yes, subtract tokens_needed from token_bucket['tokens'] and return True. Otherwise, return False.
Rest API
Need a hint?

Use an if-else statement to check tokens and update the dictionary.

4
Print the result of token consumption
Print the result of calling consume_tokens(5).
Rest API
Need a hint?

Use the print function to show the result of consume_tokens(5).