Replace plain dict cache in analytics_service with cachetools TTLCache
Problem
app/services/analytics_service.py uses a plain _cache = {} dict with manual preloading (_preload_medicines(), _preload_doctors()) to avoid N+1 queries. This cache has no TTL, no eviction policy, and no thread safety guarantees — stale data will accumulate for the lifetime of the process.
Location
app/services/analytics_service.py lines ~34–45
Fix
Option A (quick): Replace with cachetools.TTLCache:
from cachetools import TTLCache
_cache = TTLCache(maxsize=128, ttl=300) # 5-minute TTL
Option B (correct): Remove the manual cache entirely and use SQLAlchemy eager loading (selectinload / joinedload) on the queries that cause N+1.
Option B is preferred long-term. Option A is a safe immediate improvement.
References
- https://cachetools.readthedocs.io/
- https://docs.sqlalchemy.org/en/20/orm/queryguide/relationships.html
Effort
Low–Medium (1–2h)