Ticket King Problem¶
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
def get_plan_limit(plan):
"""
Identify the daily API limit for this plan
:param plan: The plan name
:return: The daily limit. 0 if plan is not recognized
"""
plan_limits = {
'peasant': 10,
'noble': 20,
'royal': 30,
}
return plan_limits.get(plan, 0)
def get_user_plan(user_id: int):
"""
Fetch this user's plan from the SQL database.
(This function is slow and expensive..)
"""
users = {
22912157: 'peasant',
64792475: 'noble',
56488868: 'royal',
92899704: 'noble',
73532154: 'peasant',
68472103: 'peasant'
}
plan = users.get(user_id)
return plan
def allow_request(user_id: int):
"""
Check if this user is allowed to make a request right now.
:return: True or False
"""
pass