Redis-cache — method caching with synchronization feature.

While working with redis using Springboot (Java) I hit a wall while I was trying to use method caching on endpoints (costing a lot to the database) which were used daily using the same parameters. My goal was to make the endpoint cost less and faster using caching with Redis but the main issue I ended up facing is that the cache containing the data to be returned from the endpoint would often go out of sync forcing me to use a TTL; defeating the purpose of speeding up the query and costing less. I started exploring possibillities to achieve a better method caching with a synchronization feature with the main datasource during this journey I studied how Springboot was storing data on the cache and came up with the idea to implement my own annotation based solution inspired by Springboot’s implementation. Thats how I came up with Redis-cache which is specialized to perform method caching with an auto-sync feature to allow data on the cache to always be in line with the datasource.

Neeschal Kissoon
3 min readAug 9, 2023

Redis-cache in action

Pre-requisites

Install postgres & Redis using docker.

docker run --name some-postgres -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=admin -d postgres
docker run --name some-redis -d redis

Getting started

Redis-cache can be added to your project using either maven or gradle.

<dependency>
<groupId>io.github.vashilk</groupId>
<artifactId>redis-cache</artifactId>
<version>1.0.6.1-BETA</version>
</dependency>
implementation("io.github.vashilk:redis-cache:1.0.6.1-BETA")

You can follow the README.md to complete the setup.

Working example

You can find a code sample for Redis-cache implementation on this repository. Let’s see how it works:

You can find the applications swagger here.

Trying out GET /books/{id}

As you will see from the logs, Hibernate triggers a query from the database because the data does not exist in cache. Following that the data returned is saved into cache. After which any query made using the same parameter on the endpoint will point to the cache instead of querying the database.

Trying out the synchronization feature

Trying out PUT /books/update

You will now see that once the update endpoint is triggered and modifies data with a method which is annotated with the same group. The code will fetch all methods annotated with the same group and synchronize the cache. From here whenever the endpoint is queried it will always query the cache instead of the database.

Seems fake or nice either way give the sample repo a try. 😆🚀

The first stable version of this repository is now out, requires a little more polishing but still has potential. If you are someone who can and wants to contribute to this venture please get in touch with me on LinkedIn.

--

--

Neeschal Kissoon

Software developer by day, passionate about software development by night.