I'm looking into adding in-memory cache, like redis, to my application, and I'm having some issues understanding how it all fits together.
const postLoader = new DataLoader(async keys => {
// ... sql code to get multiple posts by ids
})
const postRepository = {
async get(id) {
let post = await cachingImplementation.get("post:" + id)
if (!post) {
post = await postLoader.load(id)
}
return post
}
}
I understand the need to batch queries to the database, but does the same principle apply to queries to a redis server?
In this scenario, if I run the postRepository.get
method 10 times within the same tick, I would have to make 10 different requests to the redis server.
Is this a problem? Should I move the actual fetching source ( cache or database ) inside the dataloader resolver, so that it, instead of executing the sql code directly, would first look into cache and then into the database.
For example
cache = {
1: ...,
2: ...
}
If I ask for posts with id's 1,2,3, the cache has only two of them. So I would have to filter out the existing ones and query the database for the remaining ones, or just check if the requested id's match the returned rows length, and if it doesn't, query the database for everything.
What are the downsides of both approaches? Is there a preferred solution?