Databases

Caching in Redis in practice: strategies and invalidation

Ruslan Ismailov Published 9 min read
C

The cache is an accelerator, not a source of truth

The main principle: the system must remain correct even when the cache is completely flushed. If data exists only in the cache, it is no longer a cache but an unreliable store.

Choosing a pattern

Most often we use cache-aside: the application first looks in the cache, on a miss reads from the database and puts the result back. For data that requires freshness, write-through is suitable, when writing goes both to the database and to the cache.

What to pay attention to

  • Meaningful keys and namespaces.
  • Reasonable TTLs to match the nature of the data.
  • Tags for group invalidation of related records.

Fighting the cache stampede

When a popular key expires, dozens of requests rush to recompute it at once, overloading the database. We solve this with a recomputation lock and early cache refresh before the TTL expires.

Invalidation is the hardest part

We tie invalidation to domain events: when an entity changes, exactly the keys related to it are flushed. This is more reliable than relying on TTL alone and avoids showing stale data.

Conclusion

Proper caching in Redis takes the main load off the database and stabilizes latency, but requires discipline in choosing a pattern and thought-out invalidation.

Technologies

Tags

Ruslan Ismailov

Senior Web / Backend Developer. Senior web/backend developer with 9 years of experience. Stack: PHP, Laravel, PostgreSQL, Redis, Docker, Kubernetes, REST, microservices, CI/CD. More about me →