Challenge¶
You run a company called Ticket King 👑 that sells tickets to concerts and events. You have an API that lets people check ticket prices, but now you need to lock it down to prevent your servers from being overloaded.
Your company offers three plans:
- Peasant: 10 API calls per day
- Noble: 20 API calls per day
- Royal: 30 API calls per day
Quotas are tracked per user_id, and are reset at the start of each UTC day. Implement this fixed-window api rate limiter.
Starter Code
Solution¶
Tests
How to clear the database
You might want to flush your database before running the tests above. You can do so with flushdb()
.
Explanation
-
The first step is to connect to Redis.
-
Define redis keys. We'll keep track of two key-values per user:
key_limit
:
Stores the limit for a particular (user, date).
Example: (key =limit:123456:2022-05-15
, value =20
)key_usage
:
Stores the number of API calls made for a particular (user, date).
Example: (key =usage:123456:2022-05-15
, value =12
)
-
Determine the user's limit (for today).
-
Determine how many API calls this user made prior to the current one.
-
If the user's usage is below the user's limit, increment
usage
by one and save the new value on Redis.Why don't we always increment usage by 1?
You certainly could. But it's important to make the distinction between a successful API call and an unsuccessful API call. If the user's usage equals the limit, this call is going to get denied, making it an unsuccessful call. We've made the design decision to store successful API calls only.
One benefit of this is, if the user upgrades their plan midday, their unsuccessful API calls from before the upgrade will not be counted against their new quota.
-
Return True or False.