I am using AWS lambda . We tried using node-cache
module to some key with expiry for fetching data from another api. Even though the data is being set . When the next request is coming node-cache
is not able to cache that data.
here my sample code
//not the original code
let ClassService = require("./NodeCacheTest");
exports.handler = async (event) => {
let classService = new ClassService();
classService.getKey("myKey", (err, value)=> {
console.log(value);
});
};
//NodeCacheTest
const NodeCache = require( "node-cache" );
const myCache = new NodeCache();
let CACHEDATA = {
testing: true,
time_to_live: 10
};
class NodeCacheTest {
constructor () {
let obj = { my: "Special", variable: 42 };
myCache.get( "myKey", function( err, value ){
if( err || value == undefined) {
console.log("No value available!!!");
myCache.set( "myKey", obj, 10000 );
console.log("value got cached!!!");
}
});
}
getKey(key, cb) {
let obj = { my: "Special", variable: 42 };
myCache.get( "myKey", function( err, value ){
if( err || value == undefined) {
console.log("No value available!!!");
myCache.set( "myKey", obj, 10000 );
console.log("value got cached!!!");
return cb(null,obj);
} else {
return cb(null, value);
}
});
}
}
module.exports = NodeCacheTest;
every time i hit the aws lambda
endpoint using Jmeter
... I see for each call No value available!!!
is getting printed. But when I use some global variable like CACHEDATA
to implement the same scenario , the value are getting cached. Can anyone can explain me the behavior in this regard.
You're not able to use a node-cache in Lambda because of the way Lambda works.
The storage that Lambda uses is not persistent. Lambdas run in containers. On occassion you may get container reuse, and cached data is still available but this is very unreliable.
If you're caching data you should look at other services like Elasticache, or you could even potentially user DynamoDB on-demand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With