NodeJS In-memory Cache

In-memory cache in Node JS

There are countless times in you application when you need a functionality where you need a system to manage cache’s. Well basically I will elaborate how you can achieve such feature in your NodeJS application.

Let’s say you need to maintain users which are inside a particular pool. To perform repetative operations for the users of a particular pool it is efficient to maintain a cache which will basically maps users to that pool.

Obviously you can utlize services like Redis for this kind of operation but if you have a small use case like for development of POC, managing extra service seems an overhead. You can store cache inside the memory of your application and make it work.

Moving onto our example of pool & it’s users, you can maintain cache like below.

const poolCache = [];
// set pool cache
function setPoolCache(id, users) {    const index = poolCache.findIndex((poolData) => poolData.id === id);
    const poolData = { id, users };

    if (index === -1)
        poolCache.push(poolData);
    else
        poolCache[index] = poolData;

    return poolCache.find(poolData => poolData.id === id);
}
// Get pool users
function getPoolCache(id) {
    return poolCache.find(poolData => poolData.id === id);
}

module.exports = {
    setPoolCache,
    getPoolCache
}

The const variable poolCache = [] is an array which will hold your cache.

For assigning a user inside a pool lets see setPoolCache() function. The function accepts 2 parameters, id which is an pool identifier and users which is an array of users. Using findIndex() function you can find the index of your pool inside poolCache array. findIndex() function returns -1 if does not find the index of the pool id inside poolCache array.

The if ... else ... block checks the value of index, if it is -1 then simply push the object having id & users array. If the index value is not -1 then replace the cache data with the updated data.

Getting cache data is pretty easier, getPoolCache() function accepts a single parameter id which is nothing but pool identifier. The function finds the identifier data inside poolCache array. If data is found then it is returned else undefined is returned.

So this is everything in this article… Cheers 😃


Yash Narnaware
Written by@Yash Narnaware
I explain with words and code, visit my website www.yashify.in

InstagramGitHubFacebookLinkedIn