Stedi-Archive / eslint-plugin-stedi-aws-rules

Best practices around using AWS SDK & Lambda runtime in JavaScript / TypeScript projects by Stedi.
https://stedi.com
30 stars 1 forks source link

Intialize SDK clients outside of handler #4

Open RafalWilinski opened 4 years ago

RafalWilinski commented 4 years ago

Rule name

initialize-awssdk-outside-handler

Use case description

Initializing AWS SDK client instances inside handler code slows down the execution and does not share them between executions. AWS SDK clients should be initialized outside of handler code to reduce costs and make handlers execution faster.

Examples

Incorrect

import S3 from 'aws-sdk/clients/s3';

exports.handler = async (event) => {
    const s3 = new S3();
}

Correct

import S3 from 'aws-sdk/clients/s3';

const s3 = new S3();

exports.handler = async (event) => {
    ...
}
aisamu commented 4 years ago

That may have some issues when we start assuming different roles on every invocation

tvanhens commented 4 years ago

That may have some issues when we start assuming different roles on every invocation

You can still update the role after the client has been initialized. However, I don’t know if this would have any performance benefits. It would be good to have some data or a reference before implementing this as a rule.

RafalWilinski commented 4 years ago

I found this: https://dev.to/sosnowski/optimizing-aws-lambda-3m13#code-and-package-structure