Skip to main content

How to implement Cache Aside Pattern with Spring?

Problem

You want to boost application performance by loading data from a cache and prevent the network trip to the persistent store (and also the query execution). This can be achieved by loading data from a cache. However, you want to load data on demand or lazily. Also, you want the application to control the cache data management – loading, eviction, and retrieval.

Forces

  • Improve performance by loading data from cache lazily.
  • Application code controls cache data management.
  • The underlying caching system does not provide read-through, write-through/write-behind strategies (strange really ??).

Solution

Use cache aside design pattern to solve the problems outlined above. This is also one of many caching patterns/strategies. I believe it is named in this because aside from managing the data store, application code is responsible for managing the cache also.

Let's now try to understand how this caching technique works and then explore how it solves the problems.

Read

       Cache Miss
  1. The application tries to get data from the cache.
  2. The data is not available in the cache.
  3. The application queries the data store.
  4. The data is retrieved from the datastore.
  5. The application adds the data in the cache (completes lazy loading)
1
Cache Hit
  1. The application tries to get data from the cache.
  2. The cache returns the data
(Performance improvement, yay!!!)

2

Write/Update
  1. The application writes to the data store (new or updated data).
  2. The application then writes to the cache.
(Cache synchronized, yay!!!)

3

Implementation

Spring cache abstraction makes it very easy to implement Cache-aside pattern. Also, it prevents code from being mixed between business logic and caching logic. It uses aspects to separate cross-cutting concerns and saves on reinventing the wheel. The default implementation for Spring cache is ConcurrentHashMap. However, it can transparently integrate with distributed caching systems like Ehcache, Hazelcast, Apache Ignite etc.

Spring cache documentation can be found here.
The important classes from the Employee example are below.

The @Cacheable annotation ensures that when the findOne method is called, first the cache is checked for an employee with the given id. If it is present then, the data is returned from the cache. If the employee record is missing in the cache, then the actual findOne method is called which in turn queries the repository to retrieve the data. The retrieved data is then added to the cache for future access.

The @CachePut annotation is used with the write methods - save and update. As a result, the new and modified data is added back into the cache. This ensures the data in the cache is not stale.


This class drives the quick tests. The logs below shows that the "employee" cache behaves in cache-aside mode.

Consequences
Benefits
  1. Low latency reads
  2. Reduced workload on data store, which may indirectly lead to lower bill from the cloud provider :)
Concerns
  1. The application is responsible for managing the cache. The problem is accentuated if the application framework does not support Spring like caching abstraction. In that case, the code has to be written to manage the cache. There is a chance that the business logic will be polluted with caching logic. Caching logic is a cross-cutting concern and aspect-oriented design can be implemented to keep code clean.
  2.  The cache-aside pattern works best for read-only data. If the data changes fast, then there is a possibility that the underlying data store will be stormed with requests.
  3. There are challenges of synchronizing the cache with the underlying data store. This will happen even in the case of local in-memory cache. One thread may be reading employee record(potentially stale or invalidated entry), while another thread might be updating the data store and hence the cache. The problem is even greater in the case of a distributed cache. It takes a while (due to network latency etc) to synchronize changes across a distributed cache.
  4. Also like any caching pattern, it's always a challenge to set the eviction rule and expiration policy or whether to pin data. This can be set after observing the usage pattern.

Comments

Popular posts from this blog

CKEDITOR 3.x - Simplest Ajax Submit Plugin

  I have assumed that you have downloaded and got started with CKEDITOR. Step 1 – The html file is shown below: <html> <head> <title>Writer</title> <meta content="text/html; charset=utf-8" http-equiv="content-type" /> <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <style> .cke_contents { height: 400px !important; } </style> </head> <body> <form action="sample_posteddata.php" method="post"> <textarea id="editor" > </textarea> <script type="text/javascript"> //<![CDATA[ CKEDITOR.replace( 'editor', { fullPage : true, uiColor : '#9AB8F3', toolbar : 'MyToolbar' }); //]]> </script> </form> </body> </html> Note that the jquery js

Part 3 - Integrating Tiles, Thymeleaf and Spring MVC 3

In this post I will demonstrate how to integrate Apache Tiles with Thymeleaf. This is very simple. The first step is to include the tiles and thymeleaf-tiles extension dependencies. I will include them in the pom.xml. Note we wil lbe using Tiles 2.2.2 Listing 1 - parent/pom.xml --- thymeleaf-tiles and tiles dependencies <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Tiles --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-core</artifactId> <version>${tiles.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-template</artifactId> <version>${tiles.version}</version> <scope>compile</s

How to Stand up a Spring Cloud Config Server?

Setup and Configure Spring Cloud Config Server Project Spring Cloud Config Server is just another Spring Boot application. It provides several infrastructure micro services to centralize access to configuration information backed by a version controlled (well at least in the case of default GIT storage) repository. Step 1 - Create a Spring Boot project in STS with the dependencies shown in Figure 2. Figure 1 - Creating Spring Boot project to setup Spring Cloud Config Server Figure 2 - Spring Cloud Config Server dependencies Click on 'Finish' to complete the creation of the Spring Boot project in STS. The build.gradle file is shown in listing below. There is only one dependency to the Spring Cloud Config Server. Also Spring Cloud release train 'Dalston.SR1'. Step 2 - Annotate the class containing main method The next step is to annotate the ConfigServerInfraApplication class with  @EnableConfigServer That's all is needed on the Java si