Skip to content

Conversation

igorbenav
Copy link
Collaborator

Redis Rate Limiter Initialization Fix

Problem

The application was experiencing race conditions and state management issues with Redis initialization, particularly affecting the rate limiting functionality. When running with Uvicorn's auto-reload feature, module-level variables were being reset, causing the Redis client to be uninitialized even after startup.

Key issues:

  • Redis client was sometimes reported as uninitialized even after startup completion
  • Inconsistent state between module reloads during development
  • Race conditions between FastAPI startup and Redis initialization

Solution

Refactored the rate limiter implementation to use a singleton pattern, providing more reliable state management and initialization:

  1. Created a RateLimiter class to replace module-level variables:

    • Implements singleton pattern to maintain state
    • Provides clear initialization and client access methods
    • Better handles Redis connection lifecycle
  2. Updated dependency injection:

    • Modified rate limiter dependency to use the new class
  3. Enhanced initialization process:

    • Clear separation between initialization and usage
    • More reliable state management during development with auto-reload

closes #151

@igorbenav igorbenav added the bug Something isn't working label Feb 10, 2025
@igorbenav igorbenav merged commit 4119051 into main Feb 10, 2025
@igorbenav igorbenav deleted the rate-limiter-fix branch February 10, 2025 22:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Redis client not found when created background tasks in Swagger
1 participant