Caching
Redis caching strategy and TTL configuration
Caching
OptimaAi uses Redis to cache expensive operations — ML KPI loads and LLM API calls — so dashboards feel instant even under load.
Configuration
REDIS_URL=redis://localhost:6379/0
Default: redis://localhost:6379/0
ℹ️ Note: Redis is optional. If it is unavailable at startup, the API falls back gracefully — all cache reads return
None(triggering live computation) and writes are silently skipped. No errors are raised to the caller.
TTL Strategy
Each entity type has its own Time-To-Live based on how frequently it changes:
| Entity | Cache Key | TTL | Rationale |
|---|---|---|---|
| KPI snapshots | optimaai:latest_kpi | 5 minutes | Model metrics change only after retraining |
| Forecast results | optimaai:latest_forecast | 10 minutes | Forecasts are stable between requests |
| LLM recommendations | optimaai:recommend:<role> | 1 hour | LLM calls are costly; advice doesn't change minute-to-minute |
| Business Model Canvas | optimaai:latest_bmc | 24 hours | BMC is a strategic document, rarely needs regeneration |
Cache Flow
For every cacheable endpoint:
Request arrives
│
▼
Redis GET(key)
│
├─ Hit → return cached value (+ "source": "cache")
│
└─ Miss → compute live
│
├─ Save to PostgreSQL
│
└─ Redis SET(key, value, ttl)
│
▼
Return value (+ "source": "live" or "database")
API Reference
from app.cache import cache_get, cache_set, cache_delete, cache_clear_pattern
# Store a dict
cache_set("my:key", {"result": 42}, ttl=300)
# Retrieve it
data = cache_get("my:key") # Returns dict or None
# Delete one key
cache_delete("my:key")
# Delete all keys matching a pattern
count = cache_clear_pattern("optimaai:recommend:*")
Standard Cache Keys
from app.cache import kpi_key, forecast_key, recommend_key, bmc_key
kpi_key() # → "optimaai:latest_kpi"
forecast_key() # → "optimaai:latest_forecast"
recommend_key("CFO") # → "optimaai:recommend:CFO"
bmc_key() # → "optimaai:latest_bmc"
Invalidation
There is no automatic invalidation beyond TTL expiry. To force a cache refresh:
# Clear all OptimaAi keys
redis-cli KEYS "optimaai:*" | xargs redis-cli DEL
# Clear only recommendations
redis-cli KEYS "optimaai:recommend:*" | xargs redis-cli DEL
Or use the cache_clear_pattern helper from Python:
from app.cache import cache_clear_pattern
cache_clear_pattern("optimaai:*")