Back to Tech Q&A
Tech Q&A

Redis Caching Strategies

Dec 2, 2024
RedisCachingArchitecturePerformance
Question

When should I use Redis vs in-memory caching?

Answer

Use Redis when you have multiple app instances that need shared cache, or when cache needs to survive restarts. In-memory is fine for single instances with volatile data. Consider latency: in-memory is ~100ns, Redis is ~1ms.

Question

How do I handle cache invalidation?

Answer

Use TTL-based expiration for simple cases. For complex invalidation, use cache tags or pub/sub patterns to notify all instances when data changes. The hardest part is knowing WHEN to invalidate—document your invalidation rules clearly.

Question

What's the difference between cache-aside and write-through?

Answer

Cache-aside: app checks cache first, fetches from DB on miss, writes to cache. Write-through: writes go to cache AND DB simultaneously. Cache-aside is simpler; write-through ensures consistency but adds latency to writes.

Question

How do I prevent cache stampede?

Answer

Cache stampede happens when many requests hit an expired key simultaneously. Solutions: use probabilistic early revalidation, implement locking (only one request refreshes), or use stale-while-revalidate patterns.

Question

Should I cache null/empty results?

Answer

Yes, but with shorter TTLs. This prevents 'cache penetration' where repeated requests for non-existent data hit your database. A 30-second TTL for null results is usually sufficient.