Caching is critical for ML system performance. There are three distinct caching opportunities, each with different design considerations.
Features are computed once and cached for reuse across requests.
# Feature cache flow
def get_features(user_id):
cache_key = f"features:{user_id}"
features = redis.get(cache_key)
if features:
return deserialize(features)
features = compute_features(user_id)
redis.set(cache_key, serialize(features), ttl=300) # 5 min
return features
Cache entire prediction results for identical requests. Highly effective when the same input is requested repeatedly.
| Aspect | Design Choice |
|---|---|
| Cache key | hash(features + model_version) |
| Cache value | Serialized prediction + confidence score |
| Eviction | LRU + TTL-based expiration |
| Effectiveness | Best for: recommendations, search results, FAQs |
| Risk | Stale predictions if features change — use short TTL or invalidate |
Keep model weights loaded in GPU/CPU memory to avoid reloading for each request.
| Scenario | Feature Cache? | Prediction Cache? | Model Cache? |
|---|---|---|---|
| User features (demographics) | Yes, TTL=1hr | — | — |
| Real-time features (session clicks) | No (always compute) | — | — |
| Identical product recommendations | — | Yes, TTL=5min | — |
| Fraud detection (unique transactions) | — | No (rarely repeats) | — |
| Multi-model serving | — | — | Yes, LRU eviction |