Video in progress

What is the difference between the cache-aside, write-through and write-behind approaches?

In cache-aside, the application reads from the cache itself, and on a miss fetches from the DB and puts it in the cache. In write-through, the write goes synchronously through the cache to the DB. In write-behind, the cache accepts the write and writes to the DB later, asynchronously.

📖 Answer

Cache-aside (lazy loading) is the most common:

public Product get(long id) {
    Product p = cache.get(id);
    if (p == null) {
        p = repository.findById(id).orElseThrow();
        cache.put(id, p, Duration.ofMinutes(10));
    }
    return p;
}
// on write: update the DB, then cache.evict(id)

Spring's @Cacheable / @CacheEvict do exactly this. If the cache goes down, the system still works, just slower. And the first request is always a miss.

In write-through, the write goes to the cache layer, which also writes to the DB, and the response is returned after both succeed. The cache is always fresh, but writes are slower and data nobody reads also ends up in the cache.

In write-behind (write-back), the cache says "OK" right away and writes to the DB later in batches. Writes are very fast, but if a cache node dies before flushing, the data is lost. It suits things like counters and view counts, not money.

In practice most projects run on cache-aside + TTL. The other two are usually used when the cache store itself implements them (for example, Hazelcast MapStore).