How to cache the data in AWS Lambda Function using Node JS (use /tmp storage of AWS Lambda)

Vipin Katiyar
2 min readJun 9, 2021

Lambda uses /tmp directory which is dedicated to data storage on AWS Lambda with a hard limit of 512 MB.

The same Lambda execution environment may be reused by multiple Lambda invocations to optimize performance.

The /tmp area is preserved for the lifetime of the execution environment and provides a transient cache for data between invocations. Each time a new execution environment is created, this area is deleted.

Below is the event handler code in Node JS to implement the cache.

const cachedItem = {}; // as you know, anything declared outside the event handler function is reused between invocations.
exports.handler = (event, context, callback) => {
let data;
if (cachedItem && cachedItem.expiresOn > Date.now()) {
// Fetch data from cache
data = cachedItem.value;
} else {
// Set the data in cache
setCachedData("tobecaheedvalue");
}
console.log("isDataCached", data);
}
const setCachedData = (val) => {
cachedItem = {
expiresOn: Date.now() + 3600 * 1000, // Set expiry time of 1H
value: val
}
}

For the very first time of execution of lambda, there is no-cache and once the event handler is executed for the first time, it will set the data in the cache and this cache will be store in the lambda’s temp space.

For every subsequent call, it will check first if the cache is available using if condition, if available it will return the data from the cache and if not then it will set the data in cache.

you can also add the expiration time of the cached data. you can define the expiration time as per your need.

Note: Once you update/deploy Lambda’s function then all the cached storage will automatically be removed.

--

--