How to handle quickly lambda functions warmup in the Serverless Framework

By Daniel Aniszkiewicz · 5 April, 2022

General

A lot of blogposts have already been written about the pains associated with the coldstart problem, so I won't elaborate.


In a nutshell:


A cold start happens when you execute an inactive function. AWS can drop the container after a period of inactivity. In theory AWS needs a ready supply of containers to spin up when functions are invoked. That means that functions are kept warm for a limited amount of time (usually 30 – 45 minutes).


In a project this can often occur for workloads that are not in production and have irregular traffic, e.g. for different environments (demo, staging, test) or for different schedulers, or according to working hours (office hours, out of office hours).


Let's say we have a myImportantFunction, which non-regularly during typical business hours, does something important for us, and we would like it to be active all the time, and we wouldn't want cold starts.


Fortunately, there are already ways to solve this, the most recommended probably being - provisioned concurrency.


This can also be done a little differently, and certainly cheaper, by regularly pinging our lambdas using AWS services.


The duration cost is much less than the Lambda ping approach, but you need to consider the provisioned capacity cost as well, which could be costly (please do check this splendid blogpost here).


The easiest way is to use a plugin for Serverless Framework is to use a plugin.

The plugin solves cold starts by creating a scheduled lambda (the warmer) that invokes all the selected service's lambdas in a configured time interval (default: 5 minutes) and forcing your containers to stay warm.


aws-lambda-node-16

It is easy to use:


Within the Lambda function:



Inside our handler, we check the content of the source of the event. If it contains the value serverless-plugin-warmup, we know that this is a trigger from a plugin that does a warmup of our lambda, so we can return a callback (we don't want to touch the code of our lambda, just do a warmup of the lambda).


With normal invocations, this condition will be bypassed, and our lambda code will be touched.


The plugin itself has a lot of options, be it for automatically heating all lambda functions as well as other useful things.


Repository with working solution, written in TS can be found here.