Alex Edwards
Alex Edwards

Reputation: 1673

Waiting for lambda Initialization

I have some initialization i would like to do outside of my lambda event handling method, mostly just loading environment variables but some of them are encrypted with KMS so i need to decrypt them but i have to wait for the Promise to resolve. Javascript isn't my primary language so i'm not to sure on a sensible way (if any) of achieving this.

My current implementation looks like this

const controller = parseEnv(process.env).then((parsedEnv) => {
    return new InstallController(parsedEnv);
});

exports.handler = async (event, context, callback) => {
    const install = await controller;
    return install.handle(event, context, callback);
};

ideally I would like to move const install = await controller; outside of the exports.handler function. Can I do this without using a hardcoded sleep?

Upvotes: 1

Views: 1224

Answers (1)

hoangdv
hoangdv

Reputation: 16157

Lambda has been designed for serverless architecture, this mean a lambda function maybe go to "sleep" if does not have any invoking.

Then, if you call your lambda function consecutive, variables outside of handler have been cached.

I will show you the way I am on:

const initInstall = async () => {
  const parsedEnv = await parseEnv(process.env);
  return new InstallController(parsedEnv);
};

let install = null;

exports.handler = async (event, context, callback) => {
  if (!install) {
    install = await initInstall();
  } else {
    // Hit from "cache"
  }
  return install.handle(event, context, callback);
};

I refactor const controller to initInstall function, it is a async function.

And create a variable what called install to "cache" InstallController object.

In handler function, just check install is existed or not, if not, assign the result of initInstall to install.

Upvotes: 2

Related Questions