javascriptaws-lambda

Simple global state for lambda functions


I'm using a lambda function to essentially do some long polling on a device API every 5 minutes to gather data. I also want to be able to trigger the data fetch in real time for testing purposes. I can set the last date time in the API call ... something like GET /data/?fromDate=$date

What I want to be able to do is somehow keep track of the last requested time so each time I run the lambda function I get all of the data that has been gathered since the last request whether it was done on a scheduled run or done manually.

Ordinarily I could simply use a variable for this:

// set initial date
let lastTime = moment().subtract("5 minutes").toDate();

// lambda function handler
export default async () => {
   const data = await gatherData();
   lastTime = new Date;
   return storeData(data);
}

However in lambda each run may be a new process so there is no guarantee that lastTime will be kept in memory.

Is there any way for me to keep track of global state in lambda functions for simple things like primitives?


Solution

  • You'll have to store that sort of thing somewhere outside of Lambda. I've been using a DynamoDB table to store Lambda function global state.