I have a lambda@edge running on a client request. I'm dropping messages into SQS to be processed by another lambda.
The first run of my script after an update is extremely long - often blowing through the five second hard timeout, which is not a good user experience.
The majority of this is loading the AWS SDK, consistently above 2.5 seconds
var timerstart = new Date();
var timercheck = new Date();
console.log("Time check: 0");
const AWS = require('aws-sdk');
timercheck = new Date();
console.log("Time check - AWS sdk loaded: ", timercheck - timerstart);
I'm also loading https
const https = require('https');
which takes about 120ms the first run.
Many subsequent runs are entirely completed sub-millisecond, few exceed 5ms.
Has anyone else had this issue - and hopefully found a way to overcome it? I'm not finding anything via googlefu. An understanding of the disparity between first run and subsequent runs would be helpful.
Crazy idea
@jogold lead to some interesting reading.
For some reason, I thought it would be interesting to place the require outside the export.
From:
'use strict';
exports.handler = async (event, context, callback) => {
const AWS = require('aws-sdk');
//... stuff
To:
'use strict';
const AWS = require('aws-sdk');
exports.handler = async (event, context, callback) => {
//... stuff
The first time check is now down to about 300ms over the several (pretty certain) cold starts. Perhaps this is just something everyone else knows about and a gap in my knowledge of NodeJS, but if anyone else comes looking for issues with Lambda@Edge execution times, here ya go.
This is called Cold Start.
Have a look at Everything you need to know about cold starts in AWS Lambda.
If it's critical you should consider prewarming your functions.