How to Mock Daily and Monthly Quota Counters in Python
Track daily and monthly API call usage with automatic resets, quota checks, and limits using a Python class.
Python code
44 linesimport random
from datetime import datetime, timedelta
class QuotaCounter:
def __init__(self, daily_limit=1000, monthly_limit=20000):
self.daily_limit = daily_limit
self.monthly_limit = monthly_limit
self.daily_usage = 0
self.monthly_usage = 0
self.current_day = datetime.now().date()
def track_usage(self, amount=1):
today = datetime.now().date()
if today != self.current_day:
self.daily_usage = 0
self.current_day = today
self.daily_usage += amount
self.monthly_usage += amount
def check_quota(self):
return {
"daily_used": self.daily_usage,
"daily_limit": self.daily_limit,
"daily_remaining": max(0, self.daily_limit - self.daily_usage),
"monthly_used": self.monthly_usage,
"monthly_limit": self.monthly_limit,
"monthly_remaining": max(0, self.monthly_limit - self.monthly_usage),
}
def is_within_daily(self):
return self.daily_usage <= self.daily_limit
def is_within_monthly(self):
return self.monthly_usage <= self.monthly_limit
if __name__ == "__main__":
quota = QuotaCounter(daily_limit=10, monthly_limit=100)
for _ in range(random.randint(5, 12)):
quota.track_usage()
print(quota.check_quota())
print("Daily OK:", quota.is_within_daily())
print("Monthly OK:", quota.is_within_monthly())
Output
{'daily_used': 7, 'daily_limit': 10, 'daily_remaining': 3, 'monthly_used': 7, 'monthly_limit': 100, 'monthly_remaining': 93}
Daily OK: True
Monthly OK: True
How it works
The QuotaCounter class stores usage counters and resets the daily counter whenever the date changes, simulating real-world daily limit resets. The track_usage method increments both daily and monthly counters, and check_quota returns a dictionary with remaining limits, ensuring the returned values never go negative with max(0, ...). The is_within_daily and is_within_monthly methods provide boolean checks to gate API calls. This pattern is ideal for mocking rate limits before integrating with a real quota service.
Common mistakes
- Not resetting the daily counter at midnight, causing usage to accumulate indefinitely.
- Forgetting to handle monthly resets, leading to incorrect monthly quota enforcement.
- Using `random.randint` in tests without a fixed seed, making output non-deterministic for assertions.
Variations
- Add a `reset_monthly()` method to manually reset the monthly counter at the start of each month.
- Use a timezone-aware datetime to handle daylight saving and regional boundaries.
Real-world use cases
- Simulating rate limit enforcement in unit tests before integrating with a real quota API.
- Testing client-side throttling logic for API calls without spending actual quota credits.
- Building a development stub for a quota service to validate error handling in production code.
Sponsored
More from Reliability & rate limiting
- At Least Once with Idempotent Consumer in Python medium
- Build a Rate Limiter Decorator in Python easy
- Build a queue-based admission control system in Python easy
- Chaos Inject Random Failures in Python easy
- Circuit breaker failure threshold count in Python medium
- Exactly Once Processing Dedupe Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.