OptimaAI Logo

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:

EntityCache KeyTTLRationale
KPI snapshotsoptimaai:latest_kpi5 minutesModel metrics change only after retraining
Forecast resultsoptimaai:latest_forecast10 minutesForecasts are stable between requests
LLM recommendationsoptimaai:recommend:<role>1 hourLLM calls are costly; advice doesn't change minute-to-minute
Business Model Canvasoptimaai:latest_bmc24 hoursBMC 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:*")

On this page