System Design Part 2 From one machine to many

Caching in Depth: Hit Ratio Math, Write-Order Races, Penetration, Breakdown, Avalanche, and Multi-Level Caches

Bill.Lin 28 min read

System Design series Part 2-3 | Previous: Load Balancing in Depth | Next: CDNs and HTTP Caching | Series map

Read first: Part 2-1 Vertical Scaling, Horizontal Scaling, and Stateless Services.

Versions: the Java examples in this post target Spring Boot 3.x and Spring Data Redis 3.2 or later, unlike the Spring Boot 4.1 used in the rest of the series; where Boot 4 differs, the text says so.

Scenario and problem

During a big sale, the product detail API gets 10,000 requests a second, with a read/write ratio of about 200:1. The p99 of the MySQL primary climbs from 20 ms to 400 ms, so you put a layer of Redis in front of it: check the cache first, and on a miss query the database and write the result back to the cache. Database QPS immediately drops from 10,000 to 1,000, and the problem seems solved. Over the next few weeks, this happens:

  1. Operations changes a price, and some users see the old price for as long as 30 minutes
  2. The moment the key of the most popular product expires, 3,000 requests hit the database at once
  3. A crawler scans with product IDs that do not exist; every request misses the cache and goes straight to the database
  4. 200,000 keys warmed up by an overnight batch job expire at the same time and take the database down; one time Redis restarts, and it is even worse
  5. Order lookups get a cache the same way, and user A can see user B’s orders
Five incidents after adding Redis1 / 6
Five incidents after adding RedisUsersProduct APIRedisCrawlerMySQLBack officeUsersProduct APIRedisMySQL10,000 QPS90% hit1,000 QPSBack officeMySQLUsersProduct APIRedisupdate priceview productold price hitExpires only in 30 minRedisUsersProduct APIMySQLHot key expiredrush one item3,000 at onceCrawlerProduct APIRedisMySQLrandom IDsmissevery timeRedisUsersProduct APIMySQL200k keys expire at oncenormal trafficall hit the DBGoes downUsersProduct APIRedisA asks for 1024hit order:1024Gets B's order
  1. Add a cache, and the database can breatheAll 10,000 requests a second check Redis first, and 90% of them hit. Only the 10% that miss go to MySQL, and write the result back to the cache afterwards. Database QPS drops from 10,000 to 1,000.
  2. A price changes, users see the old oneOperations changes a price in the back office. The database already has the new value, but nobody deletes the cache entry. The old value expires only after 30 minutes, and until then every user sees the old price.
  3. The moment a hot key expiresThe moment the most popular product's key expires, the 3,000 requests arriving in that instant all miss the cache, all query the database, and all write back the same key. This is called cache breakdown, or hot key expiry.
  4. A crawler asks for products that do not existA crawler scans with product IDs that do not exist. They are not in the database, so they are never in the cache either, and every request goes straight to the database. This is called cache penetration.
  5. 200,000 keys expire togetherThe 200,000 keys warmed up by the overnight batch job all have the same TTL, so they expire at the same time; every request floods the database, and the database goes down. One time Redis restarts and the whole cache is wiped, and it is even worse. This is called a cache avalanche.
  6. A sees B's orderOrder lookups got a cache too, keyed only by the order number. Order 1024, which B looked up, is now cached. A asks for the same number, hits the cache directly, and the "only your own orders" condition in the SQL never runs.

A cache makes reads faster, and the price is a second copy of the data in your system. Consistency between the two copies, when entries become invalid, what to throw away when the cache is full, what happens when the cache itself goes down: all of it has to be designed.

The simplest approach and its limits

The simplest cache is a Map or Caffeine in the application’s own memory: an access takes tens of nanoseconds, with no network cost. It has three limits:

  • Every instance keeps its own copy: with 10 instances of a stateless service, the same data exists in 10 copies, and an update has to notify every one of them
  • Capacity is limited by the JVM heap: putting too much in it lengthens GC pauses
  • A restart empties it: after a deploy, every instance has to warm up again

A centralized cache (Redis) solves all three, at the cost of an extra network round trip on every access (about 0.2–1 ms within the same data center), serialization cost, and a new point of failure.

First, work out whether caching is worth it

The effect of a cache depends on the hit ratio h:

text
average latency = h × cache latency + (1 − h) × (cache latency + database latency)
database load   = (1 − h) × total QPS

The second formula explains something that is often misunderstood: what matters is the miss ratio, not the hit ratio. At 10,000 requests a second:

Hit ratio QPS reaching the database
90% 1,000
99% 100
99.9% 10

Raising the hit ratio from 90% to 99% looks like only 9 more percentage points, yet the database load drops by a factor of 10. Turn it around: if the database can only handle 2,000 QPS, it stays alive only because of the cache. If Redis goes down or restarts, 10,000 QPS lands directly on the database. At that point the cache is no longer an “accelerator” but a “load-bearing wall”, and its availability has to be taken as seriously as the database’s.

The hit ratio depends on the access distribution

How high a hit ratio you can reach depends on how much the requests concentrate on a small set of popular items. Real traffic often approximates a Zipf distribution: the probability of accessing the k-th most popular item is proportional to 1 ÷ k^α, and the larger α is, the more concentrated the traffic. Suppose there are 1 million products and 10,000 requests a second, and you cache only the top N% most popular:

The calculation (java ZipfHitRatio.java)
java
public class ZipfHitRatio {

    static final int PRODUCTS = 1_000_000;
    static final int QPS = 10_000;

    public static void main(String[] args) {
        double[] percents = {0.1, 1, 5, 10, 20};
        for (double alpha : new double[] {1.0, 0.8}) {
            double[] cumulative = new double[PRODUCTS + 1];   // cumulative[k] = total weight of the k most popular products
            for (int rank = 1; rank <= PRODUCTS; rank++) {
                cumulative[rank] = cumulative[rank - 1] + Math.pow(rank, -alpha);
            }
            System.out.printf("Zipf alpha = %.1f%n", alpha);
            for (double percent : percents) {
                int cached = (int) (PRODUCTS * percent / 100);
                double hitRatio = cumulative[cached] / cumulative[PRODUCTS];
                System.out.printf("  cache top %5.1f%% (%,9d keys)  hit %5.1f%%  DB %,6.0f QPS%n",
                        percent, cached, hitRatio * 100, QPS * (1 - hitRatio));
            }
        }
    }
}
text
Zipf alpha = 1.0
  cache top   0.1% (    1,000 keys)  hit  52.0%  DB  4,799 QPS
  cache top   1.0% (   10,000 keys)  hit  68.0%  DB  3,200 QPS
  cache top   5.0% (   50,000 keys)  hit  79.2%  DB  2,081 QPS
  cache top  10.0% (  100,000 keys)  hit  84.0%  DB  1,600 QPS
  cache top  20.0% (  200,000 keys)  hit  88.8%  DB  1,118 QPS
Zipf alpha = 0.8
  cache top   0.1% (    1,000 keys)  hit  20.7%  DB  7,932 QPS
  cache top   1.0% (   10,000 keys)  hit  36.2%  DB  6,376 QPS
  cache top   5.0% (   50,000 keys)  hit  52.3%  DB  4,775 QPS
  cache top  10.0% (  100,000 keys)  hit  60.9%  DB  3,909 QPS
  cache top  20.0% (  200,000 keys)  hit  70.8%  DB  2,915 QPS

Two observations:

  1. Diminishing returns are very clear: at α = 1, caching just 0.1% of the products gives a 52% hit ratio; but going from 1% to 10%, 10 times the capacity, adds only 16 percentage points of hit ratio
  2. The flatter the distribution, the less useful the cache: at α = 0.8, caching 10% of the products does not even reach 61%. In the web proxy traffic that Breslau et al. measured in 1999, α fell roughly between 0.64 and 0.83

So before adding a cache, estimate how popular your items are from the access logs. If traffic is spread evenly (back-office reports or long-tail search, for example), the benefit of a cache may not justify the complexity it brings. (This assumes the cache always holds exactly the most popular items, which is an ideal upper bound; real eviction policies can only approach it.)

Core mechanism

Read and write patterns

Pattern Read Write Characteristics
Cache-aside The application checks the cache first; on a miss it queries the database and fills the cache Write the database, then delete the cache entry The most common; if the cache goes down, you can still read the database directly
Read-through The application asks only the cache; on a miss the cache component loads the data itself — Loading logic lives in one place; Caffeine’s LoadingCache works this way
Write-through — Write the cache and the database synchronously The cache always has the latest value, but every write takes an extra step
Write-behind — Write the cache first, then write back to the database in asynchronous batches The fastest writes; if the cache goes down, data not yet written back is lost
Refresh-ahead Reload in the background shortly before an entry expires — Popular data never sees a spike of misses; cold data gets reloaded for nothing

The rest of this post focuses on cache-aside, the most common pattern.

On writes: why “update the database first, then delete the cache”

When writing, there are four possible orders for handling the cache: write the cache or the database first, and update or delete the cache entry. The order that feels most natural, “delete the cache first, then update the database”, easily goes wrong under concurrency:

sequenceDiagram
    participant W as Writer
    participant R as Reader
    participant C as Redis
    participant D as MySQL
    W->>C: DEL product:42
    R->>C: GET product:42 (miss)
    R->>D: SELECT (reads the old price 100)
    W->>D: UPDATE price = 80, COMMIT
    R->>C: SET product:42 = 100
    Note over C,D: The database has 80, the cache has 100, and it stays wrong until the TTL expires

The time between the writer deleting the cache entry and the transaction committing is usually a few milliseconds to a few tens of milliseconds. If any reader misses during that window, it writes the old value back. For a popular product, this is close to certain.

Switch to “update the database first, then delete the cache”, and the race that remains is much rarer:

sequenceDiagram
    participant W as Writer
    participant R as Reader
    participant C as Redis
    participant D as MySQL
    Note over C: product:42 has just expired
    R->>C: GET product:42 (miss)
    R->>D: SELECT (reads the old price 100)
    W->>D: UPDATE price = 80, COMMIT
    W->>C: DEL product:42
    R->>C: SET product:42 = 100 (written back late, e.g. after a GC pause)
    Note over C,D: The same inconsistency, but three conditions must hold at once

Three conditions have to hold at once: the cache happens to miss, the reader reads the old value before the write commits, and the reader’s write-back lands after the writer’s delete. A reader usually takes only a millisecond or two from “read the database” to “write the cache”, so the chance that this window spans the writer’s “commit to delete” is low, but it still happens during GC pauses or network jitter.

Why delete the cache entry instead of writing the new value into it? Because the order of two writers can be reversed at the cache layer: W1 writes 100 to the database, W2 writes 200 to the database, W2 writes 200 to the cache, W1 writes 100 to the cache, and the cache is stuck on the old value for good. Deleting has no ordering problem: the next read naturally loads the latest value. Besides, much of the data that gets written is rarely read, so computing it and putting it in the cache up front is wasted work.

Other sources of inconsistency

Source How it happens Countermeasure
Deleting the cache inside the transaction Deleted but not yet committed; a reader reads the old value from the database and fills the cache Delete only after commit (Spring’s transactionAware(), @TransactionalEventListener)
Filling from a replica Deleted, then a reader reads the old value from a replica that has not caught up yet Read the primary on a miss; or delete again a few hundred milliseconds later (delayed double delete)
A failed delete Redis times out, or the process dies before the delete Retry; or delete from the database binlog (CDC), so it does not depend on the application (Outbox Pattern)
The rare race from the previous section The reader’s write-back lands after the delete Cap it with a TTL; leases; carry a version number on writes and accept only newer versions
Multi-level caches One instance misses an invalidation message Give the local cache a shorter TTL

Whatever countermeasures you use, every cached entry needs a TTL. The TTL is the last safety net: it caps how long any inconsistency can last.

In Scaling Memcache at Facebook, Facebook uses leases to solve two problems at once. On a cache miss, the server hands the reader a lease token, which the reader must present when it fills the cache; if someone deletes the key in the meantime, the token becomes invalid and the stale fill is rejected. At the same time, the server issues only one token per key every 10 seconds, so other readers have to wait a moment or read a slightly stale value, which also blocks the cache breakdown discussed below.

Eviction policies: what to throw away when the cache is full

Policy Evicts Weakness
LRU The least recently used One large scan (a batch export, for example) can push out all the popular data
LFU The least frequently used Data that was popular once but nobody looks at anymore refuses to leave
W-TinyLFU (Caffeine) Uses a frequency estimate to decide whether new data deserves to get in Complex to implement, but handles both new hot items and scans

Redis’s maxmemory-policy defaults to noeviction: when memory is full, it evicts nothing and returns an error to write commands instead. A Redis used purely as a cache should switch to allkeys-lfu or allkeys-lru. The volatile-* policies evict only keys that have a TTL, which suits a mix of cache and persistent data, but the mix itself is worth reconsidering. Redis’s LRU and LFU are both sampled approximations (maxmemory-samples defaults to 5), not exact orderings.

Three incidents: penetration, breakdown, avalanche

Trigger Symptom Main countermeasures
Penetration Queries for data that does not exist The cache always misses, and every request hits the database Cache empty results (short TTL), Bloom filter, parameter validation, rate limiting
Breakdown A single hot key expires A burst of requests rebuilds the same entry at the same moment single-flight, mutex rebuild, logical expiry, early rebuild
Avalanche Many keys expire at once, or the whole cache goes down The database is crushed across the board Random TTL jitter, a highly available cache, multi-level caches, rate limiting at the database

Penetration: caching empty results is the simplest fix, but keep the TTL short, or a product will still be treated as nonexistent after it is listed. If an attacker can generate an unlimited number of different IDs, the empty results fill up the cache instead; then put a Bloom filter at the very front to decide “this ID definitely does not exist” (see Bloom Filters and HyperLogLog). The cheapest line of defense is actually parameter validation: reject requests whose ID has the wrong format or is out of range.

Breakdown: the moment a hot key expires, every request misses, every request queries the database, and every request fills the cache. The fix is to let only one request at a time rebuild a given key, a technique called single-flight:

java
public final class SingleFlight<K, V> {

    private final ConcurrentHashMap<K, CompletableFuture<V>> inFlight = new ConcurrentHashMap<>();

    public V execute(K key, Supplier<V> loader) {
        CompletableFuture<V> mine = new CompletableFuture<>();
        CompletableFuture<V> existing = inFlight.putIfAbsent(key, mine);
        if (existing != null) {
            return existing.join();          // someone is already loading this key; wait for their result
        }
        try {
            V value = loader.get();
            mine.complete(value);
            return value;
        } catch (RuntimeException e) {
            mine.completeExceptionally(e);   // waiting threads get a CompletionException
            throw e;
        } finally {
            inFlight.remove(key, mine);      // remove only the entry this call put there
        }
    }
}

Have 100 threads look up the same key at once, with each query simulated at 200 ms:

text
100 concurrent requests, 1 actual database query

Single-flight works only within a single JVM, so 20 instances can still send up to 20 queries to the database. In most cases that is already enough: from thousands down to 20. To get it down to just 1, you need Redis SET key value NX PX as a cross-machine mutex, but that costs an extra network round trip, and if the instance holding the lock dies, everyone else has to wait for the lock to expire (details in Distributed Locks and Fencing Tokens).

Another approach is to never let a hot key expire on the request path at all:

  • Logical expiry: the cache entry itself has no TTL; instead, the value stores an “expires at” time. When a read finds an expired value, it still returns the old value first, and lets only one thread rebuild it in the background. The cost is reading stale data for a short while after expiry
  • Early rebuild: rebuild early, with some probability, before the real expiry. The XFetch algorithm proposed by Vattani et al. uses a one-line formula to decide whether to rebuild early:
java
// expiresAtMs: expiry time; recomputeMs: how long the last rebuild took; beta: larger is more eager, default 1
static boolean shouldRecomputeEarly(long nowMs, long expiresAtMs, long recomputeMs, double beta) {
    double random = 1 - ThreadLocalRandom.current().nextDouble();          // (0, 1]
    return nowMs - recomputeMs * beta * Math.log(random) >= expiresAtMs;
}

With a rebuild that takes 200 ms, here are the results of 1 million simulations (the formula’s closed-form solution is e^(−time remaining ÷ rebuild time)):

text
1000 ms left: one request triggers an early rebuild  0.69% (formula  0.67%)
 600 ms left: one request triggers an early rebuild  5.00% (formula  4.98%)
 400 ms left: one request triggers an early rebuild 13.54% (formula 13.53%)
 200 ms left: one request triggers an early rebuild 36.78% (formula 36.79%)
 100 ms left: one request triggers an early rebuild 60.62% (formula 60.65%)

The closer to expiry and the slower the rebuild, the higher the chance of an early rebuild. A hot key with thousands of requests a second is almost certain to be rebuilt by some request before it expires; a cold key is rarely read, so it wastes no resources on early rebuilds. In practice this is usually paired with single-flight, so that several requests do not “win the draw” at the same time. Caffeine’s refreshAfterWrite is the same idea: when the time comes, the entry does not expire right away; the next access returns the old value and reloads it in the background.

Avalanche:

  • Add random jitter to the TTL: for data written in the same batch, add or subtract up to 10% around the base TTL, so the entries expire spread out over a period of time
  • A highly available cache: run Redis with replicas plus Sentinel, or as a Cluster, so a single node failure does not make the whole cache disappear
  • Protect the database: when the whole cache is down, use rate limiting or circuit breaking to block requests beyond what the database can handle; better to fail some requests than to let the whole database be crushed (Rate Limiting and Circuit Breakers and Bulkheads in Part 6)
  • Ramp traffic back up after a restart: Redis is empty after a restart, so warm up the popular data first, or let traffic come back gradually

Hot keys and big keys

Hot keys: Redis Cluster decides which shard holds data based on its key, so an extremely popular key always lands on a single node, and no cluster size can spread it out. Redis executes commands on a single thread; one node handles on the order of 100,000 simple commands a second (depending on hardware and commands). Countermeasures:

  • Put a local cache in front of hot keys (the multi-level cache in the next section)
  • Copy the same data into several keys (product:42#0 to product:42#7), pick one at random on reads, and delete all of them on writes
  • Since Redis 6, client-side caching is supported: the server remembers which keys each client has read, and tells the client to invalidate them when they change

redis-cli --hotkeys finds hot keys, but maxmemory-policy has to be one of the LFU policies so that there is access frequency data to use.

Big keys: a single value of several MB, or a hash or list with a million or more elements. Reading one saturates the network bandwidth; deleting one with DEL frees a large amount of memory synchronously, which blocks single-threaded Redis. Delete big keys with UNLINK (which frees the memory asynchronously), and split big keys into smaller ones in your design. redis-cli --bigkeys finds big keys.

Multi-level caches

flowchart LR
    R[Request] --> L1["L1: Caffeine<br/>one copy per instance<br/>microseconds"]
    L1 -- miss --> L2["L2: Redis<br/>shared by all instances<br/>sub-millisecond"]
    L2 -- miss --> DB[(MySQL)]
    W[Write] --> DB
    W -- after commit --> DEL["Delete from L2<br/>broadcast invalidation"]
    DEL -. pub/sub .-> L1

L1 takes the hot key pressure off Redis, and L2 lets every instance share what has been loaded. The hard part is invalidating L1: when data changes, the L1 on every instance has to be cleared. Broadcasting invalidation messages over Redis pub/sub is the simplest way, but pub/sub is “at-most-once”: an instance that happens to be disconnecting and reconnecting misses the message. So L1 must have a fairly short TTL (30 seconds, for example) as a safety net for missed messages.

Comparing options

The order of cache handling on writes

Order Main problem Verdict
Write the cache, then the database If the database write fails, the cache holds a value that never existed Not recommended
Write the database, then write the cache With concurrent writes, the order can be reversed in the cache Not recommended
Delete the cache, then write the database A read between the delete and the commit fills in the old value; this is likely Not recommended
Write the database, delete the cache after commit A rare race, capped by the TTL Default choice

Countermeasures for cache breakdown

Countermeasure Requests it holds back Can reads be stale? Cost
Single-flight (within a JVM) All but at most 1 per instance No Low
Distributed mutex (SET NX) All but 1 in the cluster No; the others wait or fail An extra network round trip; must handle the lock holder dying
Logical expiry All Yes, until the background rebuild finishes You manage the expiry time yourself
Early rebuild (XFetch, refreshAfterWrite) Most No, or only briefly An occasional extra rebuild

Where to put the cache

Local (Caffeine) Centralized (Redis) Multi-level
Latency Nanoseconds to microseconds 0.2–1 ms Hot data served from L1
Consistency Each instance has its own copy, hard to keep in sync One copy, the easiest to manage Must handle L1 invalidation
Capacity Limited by the heap Scales independently Both need planning
Good for Small, extremely hot data that can tolerate brief inconsistency (configuration, category trees) Most cases When hot keys overwhelm Redis

In Java

1. Redis settings

text
maxmemory 4gb
maxmemory-policy allkeys-lfu

Without maxmemory-policy, the moment memory fills up, every request that writes to the cache gets an OOM command not allowed error.

2. Spring Cache + Redis

The example uses Spring Boot 3.x and Spring Data Redis 3.2 or later (the rest of the series targets Spring Boot 4.1; where Boot 4 differs, the text says so):

java
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration product = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(jittered(Duration.ofMinutes(30)))
                .serializeValuesWith(SerializationPair.fromSerializer(
                        new Jackson2JsonRedisSerializer<>(ProductView.class)));   // the default is Java Serialization

        return RedisCacheManager.builder(connectionFactory)
                .withCacheConfiguration("product", product)
                .transactionAware()     // put and evict are deferred until the transaction commits successfully
                .enableStatistics()     // count hits and misses, so monitoring can see the hit ratio
                .build();
    }

    // Each entry's TTL is the base value plus or minus a random 10%, so keys written in one batch do not expire together
    private static RedisCacheWriter.TtlFunction jittered(Duration base) {
        long spread = base.toMillis() / 10;
        return (key, value) -> base.plusMillis(ThreadLocalRandom.current().nextLong(-spread, spread + 1));
    }
}
java
@Service
public class ProductQueryService {

    private final ProductRepository repository;

    public ProductQueryService(ProductRepository repository) {
        this.repository = repository;
    }

    @Cacheable(cacheNames = "product", key = "#id", sync = true)
    public ProductView findById(long id) {
        return repository.findView(id).orElse(null);   // a missing row is cached too, which stops repeated lookups of the same nonexistent ID
    }

    @Transactional
    @CacheEvict(cacheNames = "product", key = "#id")
    public void changePrice(long id, BigDecimal price) {
        repository.updatePrice(id, price);
    }
}

The key points:

  • transactionAware(): without it, @CacheEvict may delete the cache entry before the transaction commits, which falls right into the “deleting the cache inside the transaction” trap above. With it on, evict waits until the transaction commits successfully, and does not run at all if the transaction rolls back
  • sync = true: lets only one thread load a given key. The javadoc says plainly that this is only a hint to the cache provider: how the synchronization actually works is up to the implementation, and it applies only within a single JVM
  • Empty results are cached too: RedisCacheConfiguration allows caching null by default (stored as a special marker), which blocks penetration. But it shares the 30-minute TTL with regular data, so when you add a product, clear its key too, or the new product will be treated as nonexistent
  • Value serialization: the default is Java Serialization, so changing one field of ProductView makes the old cache entries unreadable. Switch to a type-specific Jackson2JsonRedisSerializer, which needs no type information embedded in the JSON (Spring Data Redis 4 moves to Jackson 3, where the matching class is JacksonJsonRedisSerializer)

3. A two-level cache under your own control

When you need an L1 local cache, the Spring Cache abstraction is no longer enough, because it does not know that it has to notify the other instances. The code below works with Caffeine and Redis directly:

java
@Component
public class ProductCache {

    public static final String INVALIDATION_CHANNEL = "cache:product:invalidate";
    private static final String KEY_PREFIX = "product:";
    private static final Duration REDIS_TTL = Duration.ofMinutes(30);

    private final Cache<Long, ProductView> local = Caffeine.newBuilder()
            .maximumSize(10_000)
            .expireAfterWrite(Duration.ofSeconds(30))   // safety net when pub/sub misses a message: at most 30 seconds stale
            .build();

    private final RedisTemplate<String, ProductView> redis;
    private final StringRedisTemplate pubSub;
    private final ProductRepository repository;

    public ProductCache(RedisTemplate<String, ProductView> redis, StringRedisTemplate pubSub,
                        ProductRepository repository) {
        this.redis = redis;
        this.pubSub = pubSub;
        this.repository = repository;
    }

    public ProductView get(long id) {
        // Load from below only on an L1 miss; only one thread loads a given key at a time, the others wait for its result
        return local.get(id, this::loadFromRedisOrDb);
    }

    private ProductView loadFromRedisOrDb(long id) {
        String key = KEY_PREFIX + id;
        ProductView cached = redis.opsForValue().get(key);                 // L2: Redis
        if (cached != null) {
            return cached;
        }
        ProductView fromDb = repository.findView(id).orElse(null);         // source of truth
        if (fromDb != null) {
            redis.opsForValue().set(key, fromDb, withJitter(REDIS_TTL));
        }
        return fromDb;
    }

    /** Call only after the transaction has committed. */
    public void evict(long id) {
        redis.delete(KEY_PREFIX + id);
        local.invalidate(id);
        pubSub.convertAndSend(INVALIDATION_CHANNEL, String.valueOf(id));   // tell the other instances to clear their L1
    }

    void evictLocal(long id) {
        local.invalidate(id);
    }

    private static Duration withJitter(Duration base) {
        long spread = base.toMillis() / 10;                                // plus or minus 10%
        return base.plusMillis(ThreadLocalRandom.current().nextLong(-spread, spread + 1));
    }
}

Caffeine’s get(key, mappingFunction) already guarantees that a key is loaded only once, so it has single-flight built in. Note that ProductView is a record: L1 returns the same object instance every time, so if it were mutable, a caller changing it would change the cached data too.

Subscribe to the invalidation messages, and have RedisTemplate use type-specific JSON:

java
@Configuration
public class CacheInvalidationConfig {

    @Bean
    public RedisTemplate<String, ProductView> productRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, ProductView> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(ProductView.class));  // a specific type, no guessing
        return template;
    }

    @Bean
    public RedisMessageListenerContainer productInvalidationListener(RedisConnectionFactory connectionFactory,
                                                                     ProductCache productCache) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(
                (message, pattern) -> productCache.evictLocal(
                        Long.parseLong(new String(message.getBody(), StandardCharsets.UTF_8))),
                ChannelTopic.of(ProductCache.INVALIDATION_CHANNEL));
        return container;
    }
}

The write side invalidates only after the transaction commits:

java
@Service
public class ProductService {

    private final ProductRepository repository;
    private final ApplicationEventPublisher events;

    public ProductService(ProductRepository repository, ApplicationEventPublisher events) {
        this.repository = repository;
        this.events = events;
    }

    @Transactional
    public void changePrice(long productId, BigDecimal newPrice) {
        repository.updatePrice(productId, newPrice);
        events.publishEvent(new ProductChanged(productId));   // registered now, handled after commit
    }
}

@Component
public class ProductCacheInvalidator {

    private final ProductCache productCache;

    public ProductCacheInvalidator(ProductCache productCache) {
        this.productCache = productCache;
    }

    @TransactionalEventListener   // default phase = AFTER_COMMIT; does not run if the transaction rolls back
    public void on(ProductChanged event) {
        productCache.evict(event.productId());
    }
}

@TransactionalEventListener has a behavior that is easy to miss: if no transaction is in progress when the event is published, the event is simply dropped, unless you set fallbackExecution = true. If someone removes @Transactional one day, the cache is never cleared again, and there is not a single error message.

Pitfalls and gotchas

  • Deleting the cache inside the transaction: @CacheEvict without transactionAware(), or a manual delete in the middle of a @Transactional method, lets a read before the commit fill in the old value
  • Updating the cache on writes instead of deleting: the order of concurrent writes is reversed at the cache layer, and the old value is stuck until the TTL expires
  • No TTL: after any single failed invalidation, the wrong data stays forever
  • The same TTL for every key: data warmed up in one batch expires at the same time and causes an avalanche
  • Redis left on the default noeviction: when memory is full, it does not evict old data; every write fails instead
  • Storing cache entries with Java Serialization: change the class, and none of the old cache entries can be read
  • A @Cacheable method called from inside the same class: Spring caching works through proxy interception, so this.findById() does not go through the cache
  • Thinking sync = true is a distributed lock: it works only within a single JVM
  • Storing mutable objects in the L1 cache: a caller that modifies the returned value modifies the cache
  • Deleting big keys with DEL: it blocks all of Redis; use UNLINK instead
  • Treating the cache as the source of truth: for data that needs strong consistency, such as stock and balances, use the cache only for display, and always decrement against the database

Security

  • Skipping authorization on a cache hit is BOLA: the order lookup used to rely on WHERE id = ? AND member_id = ? to make sure you could only see your own orders; after adding @Cacheable(key = "#orderId"), an order that B looked up gets cached, and A, using the same orderId, gets B’s data straight from the cache, without the ownership condition in the SQL ever running. The rule is cache data, not authorization results: check authorization after reading the cache, or put the user’s identity in the cache key. BOLA (Broken Object Level Authorization) is number one in the OWASP API Security Top 10 2023, and Part 8 covers it in its own post
  • Multi-tenant keys without the tenant: two tenants share report:2026-11, and data leaks straight across tenants. Always start keys with the tenant
  • Unprotected Redis: Redis does not enable TLS by default, and people often turn off protected mode or skip the password for convenience. Keep it on the internal network, and turn on ACLs and TLS. Also, if the cache uses Java Serialization, anyone who can write to Redis can plant malicious serialized data that triggers a gadget chain when the application deserializes it; with type-specific JSON, that attack surface does not exist
  • Caching sensitive data: putting tokens or personal data in the cache creates one more copy to protect. When you have to, shorten the TTL, and delete the entries actively on logout and on permission changes

When to use it, and when not to

  • Good candidates for caching: read-heavy and write-light, can tolerate brief inconsistency, expensive queries or computations, access concentrated on a few popular items
  • Poor candidates for caching: data that needs strong consistency (stock decrements, account balances), write-heavy and read-light workloads, a flat access distribution (the hit ratio is bound to be low), a database that is already fast enough (primary key lookups under 1 ms and low QPS)
  • When to re-evaluate: the hit ratio stays low for a long time (the cache is wasting memory); the database already stays alive only because of the cache (raise the cache’s high availability to the same level as the database’s); CPU or network on a single Redis node is saturated by hot keys (add an L1 or copy the keys)

References

Comments