There is an irresistible attraction to writing custom caching solutions since it seems to be the easiest path to “improving” the overall application performance. Well, caching is a great technique, but there are few steps to consider before even considering it.

A key/value collection is not a Cache Almost all projects I worked on have been using some sort of custom caching solutions, built on top of Java Maps. A Map is not an out-of-the-box Caching solution, since a Cache is more than a key/value store. A Cache also requires: eviction policies

max size limit

persistent store

weak references keys

statistics A Java Map doesn’t offer these features and you shouldn’t spend your customer’s money to write a custom cache solution either. You should choose a professional cache like EHCache or Guava Cache, which are both powerful and simple to use. Those tools are constantly tested by all those projects employing them, so the code quality is higher than most custom built solutions.

Use a cache abstraction layer A very flexible solution is the Spring Cache abstraction. The @Cacheable annotation allows you to separate the business logic code from the caching cross-cutting concern. The caching solution is therefore configurable and it’s not going to pollute your business methods.

Beware of the caching overhead Every API has a cost and caching is no different. If you cache a web service or an expensive database call, then the overhead is probably negligible. If you use a local cache for a recursive algorithm, you need to be aware of the overall caching solution overhead. Even the Spring cache abstraction has an overhead, so make sure the benefits outweigh the costs.

If your database queries are slow, the cache should be your last resort If you use an ORM tool like Hibernate, that’s the first place where your optimization process should start from. Make sure the fetching strategy is properly designed, and you don’t suffer from N+1 query problems. You could also assert the SQL statement count to validate the ORM generated queries. When you’re done optimizing your ORM SQL query generation, you should check your database for slow queries. Make sure all indexes are in place and that your SQL queries are effective.

The indexes must always fit into RAM, otherwise, you will hit the more expensive SSD or HDD. Your database has the ability to cache query results, so take advantage of it. If the data set is large and the growth rate is high you could horizontally scale it on multiple shards. If all of those actions are not enough, you may consider a professional caching solution such as Memcached.