Hi! Today I want to share some caching strategies that I've used and find interesting. Let's start:
Cache-Aside
This is the standard caching strategy most of us use. We try to load the data from the cache, and if it's missing, we load it from the database and store it in the cache. When the data is updated, we invalidate the cache.
Write-Through Cache
This one is interesting. It can improve read performance, at the cost of slower writes and more cache storage.
In this strategy, whenever the data is updated, we write it to both the database and the cache at the same time, overwriting the previously cached value. Since the cached data is always fresh, you can give it a long TTL.
Stale-While-Revalidate
In this strategy we have two TTLs: one for how long the data is considered fresh, and one for how long it can still be served as stale. When the freshness TTL expires, we don't invalidate the cache. Instead, we keep serving the stale data while a background process revalidates it. Only after the stale TTL also expires is the entry removed.
ETag Cache Validation
This isn't exactly a caching strategy. It's a cache validation strategy, used with HTTP. The server adds a response header called ETag, which identifies the version of the content. The browser stores it, and on its next request for the same resource it sends the value back in the If-None-Match header. The server compares that value with the current version of the content. If the content has changed, it returns the new content with a new ETag. If not, it returns an empty body with status 304 Not Modified, and the browser uses its cached copy.
Redis Client-Side Caching
This is a Redis feature (available since Redis 6) that only some clients implement. It relies on the CLIENT TRACKING command: once tracking is enabled, Redis remembers which keys our client has read. When another client modifies one of those keys, Redis sends us an invalidation message, so we can evict or update our local copy. This is especially useful for in-memory caches inside the application process, which are normally hard to invalidate, especially when you have several instances running. With this strategy, they can be!
Top comments (0)