Video in progress

Your team built a cache with a plain static ConcurrentHashMap. What problems do you see and what do you propose?

The main problems are unbounded growth (no eviction), stale data (no TTL), parallel loading for the same key (a stampede) and no metrics. I would propose a ready-made library like Caffeine, with a size limit, a TTL and statistics.

📖 Answer

The code usually looks like this:

private static final Map<String, Product> CACHE = new ConcurrentHashMap<>();

Product get(String sku) {
    return CACHE.computeIfAbsent(sku, repo::load);
}

It works great in tests. On prod:

  1. Nothing is ever removed. If the number of keys is unbounded (user ids, search terms), the heap slowly fills up. First Full GCs become more frequent, then an OOM.
  2. Data goes stale. A price changed in the DB, but the cache keeps returning the old price until the service restarts. With several instances, each one shows a different price.
  3. A DB call inside computeIfAbsent holds the bucket, so other keys in that bucket wait too. When the DB is slow, that is an unexpected bottleneck.
  4. Hit rate, size, load time: none of it is visible. You don't know whether the cache is helping or not.
  5. If it returns null, computeIfAbsent stores nothing and goes to the DB every time.

The proposal:

LoadingCache<String, Product> cache = Caffeine.newBuilder()
        .maximumSize(50_000)
        .expireAfterWrite(Duration.ofMinutes(10))
        .recordStats()
        .build(repo::load);

In Spring Boot, with spring-boot-starter-cache + Caffeine and Micrometer, the statistics come out automatically.

If there are several instances, there is an extra question: how do we get a change to all the copies? A short TTL, invalidation through events, or a shared Redis cache. That depends on how stale the data is allowed to get.