I am trying to implement a Redis cache on my backend server, But I actually don’t know what is the best way to do it. I am currently working with nest.js framework on node.js but I don’t care about the framework and the language.
I saw some solutions on the internet that are using a middleware for setting and retrieve caching in GET
APIs(or using decorators) and that is the first solution came to my mind, but this just cause so many problems when trying to show the user the up-to-date data. The other way of doing it is to handle Redis on every route manually. This way solves all the problems. But is it the best way of doing it? Does it worth to go and modify all the routes that are already implemented to handle caching?
When I am talking about problem, I mean not showing the user the last state of an record in database. Imagine we have two entities: AddressEntity and DeliveryEntity. The relaltion between these two is:
DeliveryEntity -> ManyToOne -> AddressEntity
and we have these routes for them:
GET /addresses
for retrieving all of the addresses.
PUT /addresses/:addressId
for updating an address.
GET /deliveries
for retrieving all of the deliveries.
Get /deliveries/:deliveryId
for retrieving details of a delivery including its address.
If I use a middleware for redis caching, I can handle the get requests with setting and getting the data (or with decorator solution). If I want to do more, I can even write a logic that when an address is updated, just go to the redis and delete all the keys starting with addresses
. But in middleware solution(or decorator solution) I can not handle all the scenarios. For example, if some user update the address and try to get the delivery details that uses that address, the user sees the old data if the ttl is not finished.
Obviuosly, I don’t want to set low ttl on the cached data and also I want a better way that handling caching on every route (if there is one).
Thanks in advance.