Video in progress
An in-process cache has to be bounded in bytes, not in number of elements. How do you estimate the real size of an object graph, and how do you configure the cache?
I measure object sizes on samples with JOL, work out the retained size, and look at the average and the heavy-tailed distribution. Then in Caffeine I set an approximate budget with maximumWeight and a cheap weigher, and check the result against the real size in the heap.
📖 Answer
maximumSize(100_000) is risky: if the average element is 2 KB, that is 200 MB, but if some customers' responses are 500 KB, the same cache can reach 2 GB. The budget has to be in bytes.
- Measuring. JOL's
GraphLayoutwalks the whole graph and gives the real size:
ProductView sample = loadRealSample();
System.out.println(GraphLayout.parseInstance(sample).totalSize()); // bytes
System.out.println(GraphLayout.parseInstance(sample).toFootprint()); // by class
I do this on a few hundred samples from prod data, to get the p50 and p99 sizes. Something unexpected often comes up: shared objects (enums, canonical strings) get counted into every element, or conversely, every element has its own HashMap.
- The weigher. On prod you can't use JOL on every
put, because it is expensive. I write a cheap estimation formula:
Cache<Long, ProductView> cache = Caffeine.newBuilder()
.maximumWeight(300L * 1024 * 1024)
.weigher((Long k, ProductView v) -> 200 + v.name().length() * 2 + v.attrs().size() * 120)
.recordStats()
.build();
I calibrate the formula against the JOL results, and ±20% accuracy is enough.
- Checking. Under load, in a heap histogram or dump, does the retained size of the cache object match the budget? If not, the formula is wrong.
Reducing the size itself is also often more useful: a compact record instead of an entity, canonicalizing repeated strings, long[] instead of List<Long>. Storing Hibernate entities in a cache is the most common mistake, along with their proxies and session references.
Eviction by weight also changes the cache hit rate: big elements get evicted sooner. Watch the hit rate and evictions in recordStats().
Sign up to mark studied questions and save your progress.