Currently, the CachingCharacterRepository saves data to both the cache (Redis) and the database (PostgreSQL) synchronously. This behavior introduces potential latency, especially when the database operation is slow or under high load.
To improve performance and responsiveness, the database save operation should be made non-blocking while keeping the cache update synchronous. This ensures quick cache updates while delegating the database save to a background process.
Proposed Solutions
1. ThreadPoolExecutor
Use Python's built-in concurrent.futures.ThreadPoolExecutor to execute the database save operation in a separate thread.
Currently, the
CachingCharacterRepository
saves data to both the cache (Redis) and the database (PostgreSQL) synchronously. This behavior introduces potential latency, especially when the database operation is slow or under high load.To improve performance and responsiveness, the database save operation should be made non-blocking while keeping the cache update synchronous. This ensures quick cache updates while delegating the database save to a background process.
Proposed Solutions
1. ThreadPoolExecutor
Use Python's built-in
concurrent.futures.ThreadPoolExecutor
to execute the database save operation in a separate thread.Implementation:
Pros:
Cons:
max_workers
).2. Celery with Redis as Task Queue
Integrate a task queue system using Celery to offload the database save operation to a worker process.
Implementation:
Define a Celery task to handle the database save:
Modify
CachingCharacterRepository
:Pros:
Cons:
Comparison Table
max_workers
Acceptance Criteria
CachingCharacterRepository
using one of the proposed solutions.Additional Notes
ThreadPoolExecutor
is chosen, ensure thread safety and proper cleanup of threads during shutdown.