DEV Community 👩‍💻👨‍💻

Cover image for Catch AWS Lambda Timeouts
Martin Muller for AWS Community Builders

Posted on • Originally published at martinmueller.dev

Catch AWS Lambda Timeouts

cdk-lambda-timeout-eng
(Click me :D)

Ahoy,

AWS Lambda is probably one of the most famous if not the most famous compute service from AWS. In fact, Lambda is also my favorite AWS service because it makes implementing business logic very easy and straightforward. However, a few times I had the problem that the timeout of Lambda was too low and thus the code was not completely executed. Debugging or catching this error was also often exhausting and annoying. A good solution for me was to use the Lambda Duration Metrics to define an alarm.

import * as cw from 'aws-cdk-lib/aws-cloudwatch';
import * as lambdajs from 'aws-cdk-lib/aws-lambda-nodejs';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as subscriptions from 'aws-cdk-lib/aws-sns-subscriptions';

const exampleLambda = new lambdajs.NodejsFunction(this, 'ExampleLambda', {
    timeout: core.Duration.seconds(10),
});

new timeoutAlarm - new cw.Alarm(this, 'TimeoutAlarm') {
    metric: exampleLambda.metricDuration({ statistic: 'max' }),
    threshold: exampleLambda.timeout?.toMilliseconds() ?? 1,
    evaluationPeriods: 1,
}

const topic = new sns.Topic(
    this,
    'ErrorTopic',
);
topic.addSubscription(
    new subscriptions.EmailSubscription('alice@bob.com')
);
timeoutAlarm.addAlarmAction(
    new actions.SnsAction(topic)
);
Enter fullscreen mode Exit fullscreen mode

As you can see here, a simple Lambda JS Function is created at the beginning. By the way the NodejsFunction construct also supports TypeScript. Then the timeout alarm is defined which uses the duration metric and the timeout value from the Lambda to configure.

After that, an Error Topic is created via which the triggered alarm is forwarded by email using an EmailSubscription.

Advantages

The advantage of this solution is that the Lambda code does not need to be modified and the problem is solved on infrastructure level or AWS CDK level. This solution can be applied to other Lambda languages like Python or Java as well.

Conclusion

Lambda timeout caching is annoying. With a little AWS CDK code and the Lambda Duration metric, the problem is quickly solved.

I love to work on Open Source projects. A lot of my stuff you can already use on https://github.com/mmuller88 . If you like my work there and my blog posts, please consider supporting me on:

Buy me a Ko-Fi

OR

Buy me a Ko-Fi

And don't forget to visit my site

martinmueller.dev

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.