Best practice to take advantage of warm starts with node lambdas

Currently my lambdas are pretty naive. The event handler looks like this:

  • Fetches a config with things like DB credentials etc and creates a Knex (db client) instance. The DB creds are kept in parameter store.
  • Do the business logic (create a new thing etc)

Since we have super low volume this isn’t a big deal but soon with warm starts it makes sense to not fetch the creds from parameter store every time and not recreate a DB connection but to do it when the lambda spins up so invocations within that invocation can use the same data. I’m not sure how to do this. In a EC2/Express world I would have my DB config loaded when the application starts and all requests would use a shared instance. How does this happen in a lambda environment?

The most common way is to put the code outside the handler function so it is only executed during cold start. The alternative is to put it inside your handler function but conditionally execute it (i.e. check if you already have valid DB credentials before requesting them).

Thanks for the quick reply.

I’m a little new to node.js so maybe this is more of a JS question but if I put a getConfig() function outside of the handler which is async (as it calls AWS parameter store) I can’t be sure that it will have completed before the handler begins execution so there’s no way to be sure the data will be ready. Lambda really could use some more lifetime handlers onColdBoot(), onEvent(), onTeardown() etc.

The alternative is to put it inside your handler function but conditionally execute it (i.e. check if you already have valid DB credentials before requesting them).

Yeah, I think I’ll go this route. Just a bit of a shame as it adds some boilerplate-y async cache/singleton stuff which I was hoping to avoid.

Thanks!