Scrivio Interview library
LeadershipAdvanced6 min read · updated 12 November 2026

Across 40 services you find many hand-written LinkedHashMap and ConcurrentHashMap caches, some unbounded, some with custom eviction. Two recent incidents were OutOfMemoryErrors from such caches. What standard would you set and how would you roll it out?

I would set a standard that every cache must be bounded, with an explicit size or weight limit and an expiry policy, and forbid unbounded maps used as caches. Teams would use one library, for example Caffeine behind Spring's cache abstraction, delivered in a shared starter with metrics enabled, and every cache would have hit rate, size and eviction metrics on a dashboard with alerts on growth. The standard would also say when a distributed cache is needed for consistency or size and when local caching is fine. I would roll it out with static analysis and a review checklist, migrating the riskiest caches, starting with the two that caused the incidents, first.

Why this question is asked

Hand-written caches are one of the most common sources of memory incidents in Java services. They start as a map and a get-then-put, nobody adds eviction because the data looked small, and two years later the heap fills on a busy day. With 40 services and many such caches, fixing them one incident at a time does not scale. Interviewers ask this leadership question to see whether we can turn a pattern of failures into a standard that teams will actually adopt, and roll it out without stalling feature work. In this answer, we will recap why map-based caches fail, define the standard and the reasons behind each rule, describe the shared starter, decide between local and distributed caching, and plan the rollout.

1A Quick Recap: Why Map-Based Caches Fail

A cache is only safe if something removes entries. A plain HashMap or ConcurrentHashMap never does, so a cache keyed by user, request parameter or product grows with the number of distinct keys ever seen, and a heap that was fine at launch runs out under a new traffic pattern. That is exactly an OutOfMemoryError from a cache.

Hand-written eviction has its own failure modes: a LinkedHashMap LRU that is not thread-safe, a custom cleanup thread that falls behind, a size check that counts entries while the entries themselves vary from bytes to megabytes. And without metrics, nobody knows the hit rate, so caches that never help stay in the code.

2The Standard and the Reason for Each Rule

The first rule is that every cache is bounded, by a maximum entry count or, when values vary in size, a maximum weight, and has an expiry policy that matches how stale its data may be. An unbounded map used as a cache is not allowed. The reason is simple: a bound turns an OutOfMemoryError into a lower hit rate, which is a much better failure.

The second rule is one library. Standardising on Caffeine, used through Spring's cache abstraction where it fits and directly where we need loading caches, means teams share knowledge, the library's eviction and concurrency are well tested, and we can tune and monitor every cache the same way.

The third rule is observability. Every cache publishes hit rate, size, eviction count and load time, and every service dashboard shows them. Alerts fire when a cache's size stays near its bound with a falling hit rate, or when heap after GC grows steadily, which is the early warning these two incidents did not have.

The cache standard
RuleRequiredWhy
BoundmaximumSize or maximumWeightturns OOM into lower hit rate
ExpiryexpireAfterWrite or expireAfterAccesscaps staleness and dead entries
LibraryCaffeine via the shared startertested eviction and concurrency
Metricshit rate, size, evictions, load timeknow whether the cache helps
Owner and purposenamed in the cache configsomeone decides when to remove it

3The Shared Starter

A standard is adopted when the right thing is the easy thing. So the platform team ships a cache starter, a Spring Boot auto-configuration in a shared dependency, that creates a CaffeineCacheManager, turns on recordStats() and Micrometer cache metrics by default, and refuses to create a cache without a configured bound and expiry.

YAML
# application.yml with the shared starter
company:
cache:
caches:
products:
maximum-size: 50000
expire-after-write: 30m
exchange-rates:
maximum-size: 500
expire-after-write: 5m
# a cache name used in @Cacheable but missing here fails at startup:
# "Cache 'prices' has no bound or expiry configured"

Notice that the failure happens at start-up, in development, not in production. The starter also adds a standard dashboard panel per cache, so teams get observability without writing any code.

4Local or Distributed?

The standard should also answer the question teams will ask next. A local cache in each instance is fine when the data can be a little stale, within its expiry, and when each instance can hold the part of the data it needs. A distributed cache such as Redis is justified when instances must agree, for example when a change must be visible to all instances at once, or when the data is too large for each heap, or when computing a value is so expensive that sharing it across instances pays for the network call. The cost is another system to run, a network hop on every lookup and new failure modes, so it is the exception, chosen with a reason written down.

Step throughChoosing a cache type
  1. Can the data be stale for its expiry time?
    YesConsider a local cacheNoDo not cache, or use events to invalidate
  2. Fits comfortably in each instance's heap?
    YesLocal Caffeine cacheNoConsider a distributed cache
  3. Must all instances see one value at once?
    YesDistributed cache with invalidationNoLocal cache is enough

3 steps in order. Play them, or step through them one at a time.

5Rolling It Out

I would begin with an inventory. Static analysis, for example ArchUnit rules or a custom Error Prone or Sonar check, finds fields of type Map that are written in request paths and never cleared, classes named like caches, and extensions of LinkedHashMap that override removeEldestEntry. A heap histogram from each service shows which maps are large in practice.

Then I would rank by risk: unbounded caches keyed by user input first, starting with the two that caused the incidents, then large caches, then hot ones with hand-written locking. Each migration is a small, mechanical change with the starter, done by the owning team with help from the platform team. New code is held to the standard through the review checklist and the static analysis rule, which fails the build for new unbounded caches while existing ones are tracked in a list that we burn down over a couple of quarters. I would report progress as the number of unbounded caches remaining and the hit rates of the migrated ones, and some caches will turn out to have such low hit rates that the right migration is deletion.

6Follow-up questions

What if a team needs a cache Caffeine cannot express?

Then they ask for an exception, with the reason, and the platform team reviews it. Most needs, such as weights, per-entry expiry, refresh and removal listeners, are already covered. A genuine exception is documented and still has to meet the bound and metrics rules.

How do we stop people from writing new map caches anyway?

By making the starter easier than a map, and by a build-time check for the common patterns. The review checklist then catches what the tools miss, and a short write-up of the two incidents explains why the rule exists, which helps more than the rule alone.

How do we choose the bound for a cache?

From its working set and its value sizes. We look at the number of distinct keys used per expiry period and the size of typical values, set a bound that covers most of that within a memory budget, and then check the hit rate and eviction metrics after deployment and adjust.

7Conclusion

In this answer, we set a standard for caches across 40 services: every cache is bounded by size or weight and has an expiry policy, unbounded maps used as caches are forbidden, and everyone uses one library, Caffeine behind Spring's cache abstraction, delivered in a shared starter with metrics enabled. Every cache shows hit rate, size and evictions on a dashboard with alerts on growth, and the standard explains when a distributed cache is needed for consistency or size and when local caching is enough. We rolled it out with an inventory from static analysis, migrating the riskiest caches first, and a review checklist and build check for new code.

What to say in the interviewAbout 110 seconds aloud

Open with

Two OutOfMemoryErrors from caches tell me this is a standards problem, not a series of bugs. A map with no eviction grows with every distinct key it sees, so the first rule I would set is that every cache must have an explicit bound, a maximum size or a maximum weight when values vary, plus an expiry that matches how stale the data may be.

Then, if they want more

Unbounded maps used as caches are not allowed, because a bound turns an out-of-memory crash into a lower hit rate. Second, one library: Caffeine, through Spring's cache abstraction, packaged in a shared starter that enables statistics and Micrometer metrics by default and fails at start-up if a cache has no bound or expiry.

Third, observability: every cache shows hit rate, size, evictions and load time on the service dashboard, with alerts when a cache sits at its bound with a falling hit rate or when heap after GC keeps growing.

The standard also explains when to use a distributed cache: when instances must agree on one value, or when the data does not fit in each heap, accepting the extra system and network cost; otherwise local is fine.

For the rollout I would build an inventory with static analysis and heap histograms, rank caches by risk, starting with the two incident caches and anything keyed by user input, and have owning teams migrate them with platform support.

New code is held to it with a build check and the review checklist, and I would track the count of unbounded caches until it reaches zero, deleting caches whose hit rates show they do not help.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Across 40 services you find many hand-written LinkedHashMap and ConcurrentHashMap...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/ffa5b771eb/