# RateLimiter Implementation ## Overview The RateLimiter class provides sophisticated rate limiting and quota management for the voice control optimization system. It implements sliding window rate limiting with multi-window tracking, provider-specific limit enforcement, and automatic provider switching capabilities. ## Features ### Multi-Window Tracking - **Sliding Windows**: Requests per minute/hour with automatic cleanup of old entries - **Fixed Windows**: Daily and monthly quotas with scheduled resets - **Audio Duration Limits**: Track audio minutes across different time periods - **Request Count Limits**: Track number of requests across different time periods ### Provider-Specific Configuration - **Individual Limits**: Each provider can have different rate limits and quotas - **Free Tier Management**: Separate tracking for free tier limits vs paid usage - **Multiple Quota Types**: Support for requests/minute, requests/day, audio minutes/day, audio minutes/month ### Intelligent Quota Management - **Proactive Checking**: Check if requests would exceed limits before consuming quota - **Automatic Switching**: Integration with ProviderManager for automatic provider switching - **Usage Statistics**: Detailed usage tracking and reporting - **Cost Estimation**: Calculate estimated costs based on usage and provider pricing ### Exponential Backoff - **Rate Limit Violations**: Implement exponential backoff for repeated quota violations - **Provider-Specific**: Independent backoff state for each provider and quota type - **Automatic Recovery**: Reset backoff state on successful requests ## Architecture ``` RateLimiter ├── Provider Configuration │ ├── Rate Limits (requests/minute, requests/hour, requests/day) │ ├── Free Tier Limits (audio minutes/day, audio minutes/month) │ └── Cost Per Minute ├── Multi-Window Tracking │ ├── Sliding Windows (cleanup old entries) │ ├── Fixed Windows (scheduled resets) │ └── Usage Statistics ├── Quota Management │ ├── Quota Checking (before consumption) │ ├── Quota Consumption (with validation) │ └── Quota Reset (manual and automatic) └── Backoff Management ├── Exponential Backoff ├── Provider-Specific State └── Automatic Recovery ``` ## Usage ### Basic Setup ```python from voice_control.rate_limiter import RateLimiter from voice_control.models import ProviderConfig, ProviderType # Initialize rate limiter rate_limiter = RateLimiter() await rate_limiter.initialize() # Configure a provider config = ProviderConfig( name="google_speech", provider_type=ProviderType.GOOGLE_SPEECH, enabled=True, priority=2, free_tier_limits={"audio_minutes_per_month": 60}, rate_limits={"requests_per_minute": 1000}, supported_formats=["webm", "wav"], supported_languages=["en-US"], cost_per_minute=0.006, api_credentials={"api_key": "your-key"} ) await rate_limiter.configure_provider(config) ``` ### Quota Management ```python # Check if request would exceed quota quota_status = await rate_limiter.check_quota("google_speech", 30.0) if not quota_status.is_exceeded: # Consume quota for 30 seconds of audio success = await rate_limiter.consume_quota("google_speech", 30.0, 1) ``` ### Usage Statistics ```python # Get usage statistics for different time windows minute_stats = await rate_limiter.get_usage_stats("google_speech", "minute") daily_stats = await rate_limiter.get_usage_stats("google_speech", "day") print(f"Requests: {minute_stats.requests_count}") print(f"Audio minutes: {minute_stats.audio_minutes}") print(f"Estimated cost: ${minute_stats.estimated_cost:.4f}") ``` ### Provider Availability ```python # Check if provider is available (not rate limited) available = await rate_limiter.is_provider_available("google_speech", 60.0) if available: # Provider can handle a 60-second request pass ``` ## Integration with ProviderManager The RateLimiter integrates seamlessly with the existing ProviderManager: ```python # In ProviderManager.transcribe_audio() if self._rate_limiter: audio_duration = len(audio_data) / (44100 * 2) # Estimate duration quota_status = await self._rate_limiter.check_quota(provider_name, audio_duration) if quota_status.is_exceeded: continue # Try next provider # After successful transcription await self._rate_limiter.consume_quota(provider_name, result.audio_duration) ``` ## Configuration Examples ### Web Speech API (Free, No Limits) ```python ProviderConfig( name="web_speech_api", provider_type=ProviderType.WEB_SPEECH_API, free_tier_limits={}, # No limits rate_limits={"requests_per_minute": 60}, # Basic rate limiting cost_per_minute=0.0 # Free ) ``` ### Google Speech-to-Text (60 minutes/month free) ```python ProviderConfig( name="google_speech", provider_type=ProviderType.GOOGLE_SPEECH, free_tier_limits={"audio_minutes_per_month": 60}, rate_limits={ "requests_per_minute": 1000, "requests_per_day": 1000000 }, cost_per_minute=0.006 ) ``` ### Azure Speech Services (5 hours/month free) ```python ProviderConfig( name="azure_speech", provider_type=ProviderType.AZURE_SPEECH, free_tier_limits={"audio_minutes_per_month": 300}, rate_limits={ "requests_per_minute": 20, "requests_per_hour": 1000 }, cost_per_minute=0.004 ) ``` ## Error Handling The RateLimiter raises specific exceptions for different scenarios: - **QuotaExceededError**: When quota limits would be exceeded - **RateLimitExceededError**: When rate limits are exceeded with backoff ```python try: await rate_limiter.consume_quota("provider", 30.0, 1) except QuotaExceededError as e: logger.warning(f"Quota exceeded: {e}") # Switch to different provider except RateLimitExceededError as e: logger.warning(f"Rate limited: {e}") # Wait for retry_after seconds ``` ## Testing Comprehensive test suite covers: - **Unit Tests**: Individual method functionality - **Integration Tests**: Multi-provider scenarios - **Edge Cases**: Concurrent access, large durations, zero values - **Error Conditions**: Quota exceeded, rate limiting, backoff Run tests with: ```bash python -m pytest voice_control/tests/test_rate_limiter.py -v ``` ## Performance Considerations - **In-Memory Storage**: Default storage for development and testing - **Redis Support**: Optional Redis backend for distributed rate limiting - **Cleanup Tasks**: Background cleanup of old sliding window data - **Async Operations**: All operations are async for non-blocking performance ## Future Enhancements - **Redis Integration**: Distributed rate limiting across multiple instances - **Metrics Export**: Integration with monitoring systems (Prometheus, etc.) - **Dynamic Limits**: Runtime adjustment of rate limits based on provider status - **Predictive Switching**: Machine learning-based provider selection