← Back to Index

9. Caching Strategies

Caching is critical for ML system performance. There are three distinct caching opportunities, each with different design considerations.

1. Feature Cache

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

2. Inference (Prediction) Cache

Cache entire prediction results for identical requests. Highly effective when the same input is requested repeatedly.

AspectDesign Choice
Cache keyhash(features + model_version)
Cache valueSerialized prediction + confidence score
EvictionLRU + TTL-based expiration
EffectivenessBest for: recommendations, search results, FAQs
RiskStale predictions if features change — use short TTL or invalidate

3. Model Cache

Keep model weights loaded in GPU/CPU memory to avoid reloading for each request.

Cache Strategy Decision Matrix

ScenarioFeature Cache?Prediction Cache?Model Cache?
User features (demographics)Yes, TTL=1hr
Real-time features (session clicks)No (always compute)
Identical product recommendationsYes, TTL=5min
Fraud detection (unique transactions)No (rarely repeats)
Multi-model servingYes, LRU eviction
Exercise: Design caching for a real-time product search ranking system. Three cache types are available. For each: define cache key format, TTL, eviction policy, and invalidation strategy. Describe how the cache hit ratio changes during a flash sale event with 10x traffic.