Video in progress

How does the cache-aside pattern work?

The application looks in the cache first. If it finds the entry, it returns it. If not, it reads from the database, writes the result to the cache and returns it. When the data changes, it writes to the database and deletes the key from the cache.

📖 Answer

This is the most widely used scheme, because even if the cache goes down, the application keeps working by reading from the database.

public Product find(long id) {
    String key = "product:" + id;
    Product cached = cache.get(key);
    if (cached != null) return cached;          // hit

    Product p = repository.findById(id).orElseThrow(); // miss
    cache.put(key, p, Duration.ofMinutes(10));
    return p;
}

public void update(Product p) {
    repository.save(p);
    cache.delete("product:" + p.getId());  // we delete, not update
}

In Spring, @Cacheable and @CacheEvict do the same thing.

Why delete the cache entry on write instead of updating it? If two parallel updates write to the cache in a different order, a stale value can stay in the cache. If you delete, the next read fetches the fresh value from the database.