Warmup middleware for the middy framework, the stylish Node.js middleware engine for AWS Lambda
Warmup middleware that helps to reduce the cold-start issue. Compatible by default with serverless-plugin-warmup
, but it can be configured to suit your implementation.
This middleware allows you to specify a schedule to keep Lambdas that always need to be very responsive warmed-up. It does this by regularly invoking the Lambda, but will terminate early to avoid the actual handler logic from being run.
If you use serverless-plugin-warmup
the scheduling part is done by the plugin and you just have to attach the middleware to your "middyfied" handler. If you don't want to use the plugin you have to create the schedule yourself and define the isWarmingUp
function to define whether the current event is a warmup event or an actual business logic execution.
Important: AWS recently announced Lambda Provisioned Concurrency. If you have this enabled, you do not need this middleware.
To update your code to use Provisioned Concurrency see:
To install this middleware you can use NPM:
npm install --save @middy/warmup
isWarmingUp
: a function that accepts theevent
object as a parameter and returnstrue
if the current event is a warmup event andfalse
if it's a regular execution. The default function will check if theevent
object has asource
property set toserverless-plugin-warmup
.onWarmup
: a function that gets executed before the handler exits in case of warmup. By default the function just prints:Exiting early via warmup Middleware
.waitForEmptyEventLoop
: a boolean value (null
by default), that if set will change the current value forcontext.callbackWaitsForEmptyEventLoop
. In some circumstances it might be useful to force this value to befalse
to make sure that the lambda quits as early as possible in case of warmup (for instance if you have created a database connection in a previous middleware, this might be hanging and keeping you lambda active until timeout).
const middy = require('@middy/core')
const warmup = require('@middy/warmup')
const isWarmingUp = (event) => event.isWarmingUp === true
const onWarmup = (event) => console.log('I am just warming up', event)
const originalHandler = (event, context, cb) => {
/* ... */
}
const handler = middy(originalHandler)
.use(warmup({
isWarmingUp,
onWarmup
}))
For more documentation and examples, refers to the main Middy monorepo on GitHub or Middy official website.
Everyone is very welcome to contribute to this repository. Feel free to raise issues or to submit Pull Requests.
Licensed under MIT License. Copyright (c) 2017-2018 Luciano Mammino and the Middy team.