Python Rate-Limiter using Leaky-Bucket Algorithm for controlling request rates in applications with multiple backend storage options.
81
Build a rate limiting system for an API service that uses persistent database storage to track request limits across server restarts and multiple processes. The system should enforce rate limits and maintain consistency even under concurrent access.
Implement a rate limiter that:
Create a module rate_limiter.py that exports:
check_rate_limit(api_key: str) -> bool - Returns True if the request is allowed, False if rate limit exceededreset_rate_limit(api_key: str) -> None - Clears all rate limit data for the specified API keyclose_limiter() -> None - Cleanup function to release database resourcesThe database connection should use these parameters:
POSTGRES_HOST (default: "localhost")POSTGRES_PORT (default: 5432)POSTGRES_DB (default: "ratelimit")POSTGRES_USER (default: "postgres")POSTGRES_PASSWORD (default: "postgres")True @testTrue @testFalse @testTrue even if previously exceeded @testclose_limiter(), database connections are properly released @testProvides rate limiting functionality with PostgreSQL storage backend.
@generates
def check_rate_limit(api_key: str) -> bool:
"""
Check if a request from the given API key should be allowed.
Args:
api_key: The API key to check rate limits for
Returns:
True if the request is allowed, False if rate limit is exceeded
"""
pass
def reset_rate_limit(api_key: str) -> None:
"""
Reset rate limit data for the specified API key.
Args:
api_key: The API key to reset
"""
pass
def close_limiter() -> None:
"""
Release database resources and cleanup connections.
"""
passInstall with Tessl CLI
npx tessl i tessl/pypi-pyrate-limiterdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10