5 best practices for AWS Lambda function design standards
Tags: javascript, aws, lambda
Published: 2023-05-21 08:00:44

Here are a few best practices to incorporate into your Lambda function design standards.

## 1. Store and reference dependencies locally
If your code retrieves any externalized configuration or dependencies, make sure they are stored and referenced locally after initial execution. For example, if your function retrieves information from an external source like a relational database or AWS Systems Manager Parameter Store, it should be kept outside of the function handler. By doing so, the lookup occurs when the function is initially run. Subsequent warm invocations will not need to perform the lookup.

![Helper function for SSM Client](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ew8v1wn0xo6g19msvcfq.png)


![handler.js to get parameter value](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/enp6l94l5siqmfh70s1j.png)

If you see handler.js on line number 3, we are defining the global value. Then, on line number 6, we are checking either the value is exist or not, if yes, then we will get the value and assign back to the variable `value`. With this, in the next invocation of lambda, if the lambda is still warm, we do not need to get again the same parameter value.


## 2. Limit re-initialization of variables
You should also limit the re-initialization of variables or objects on every invocation. Any declarations in your Lambda function code (outside the handler code) remain initialized when a function is invoked.

To improve performance, limit the re-initialization of variables or objects in an AWS Lambda function. When a Lambda function is called, any code outside the handler function is only run once during the function's startup or cold start. Variable declarations and object initialization are included.

Re-initializing variables or objects on each invocation suggests that the code is doing redundant operations that might have been performed only once during startup. This can result in longer execution times and a decrease in the performance of your Lambda function.

Limiting variable or object re-initialization ensures that these activities are only executed once during the cold start. Subsequent Lambda function invocations (warm invocations) can then reuse the initialised variables.


## 3. Check and reuse existing connections
Add logic to your code to check whether a connection already exists before creating one. If one exists, just reuse it. 


![handler.js to reuse existing connections](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hc27e4sp636xx9cd4djs.png)

In this example, the database client is stored in a global variable dbClient. During the initial invocation (cold start), the code checks to see if dbClient is null. If it is null, a new database client is generated with the auxiliary function createDatabaseClient. If dbClient is not null, it indicates that a client already exists, and the function reuses existing client.

Following invocations of the Lambda function (warm invocations) might save the overhead of generating a new database connection and client setup, which can be time-consuming. Reusing the client aids in the performance and efficiency of the Lambda function.

Note: To ensure best practises for maintaining database connections, you must manage error scenarios, connection pooling, and proper client closure in a real-world scenario. The supplied example is simplified for demonstrative purposes.


## 4. Use /tmp space as transient cache
Add code to check whether the local cache has the data that you stored previously. Each execution context provides additional disk space in the /tmp directory that remains in a reused environment.


![handler.js to utilize /tmp space](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mgdckgrwperggjoq7x84.png)

The code uses fs.existsSync to check if the cache file exists in the /tmp directory. If the file exists, it reads the data from the cache file using fs.readFileSync and parses it as JSON for further processing.

If the cache file does not exist, it retrieves the data from an external source, processes it, and then stores it in the cache file located in the /tmp directory using fs.writeFileSync.

By utilizing the /tmp space as a transient cache in JavaScript, you can reduce the need to repeatedly retrieve the same data from an external source, thereby improving the performance and reducing the execution time of your Lambda function.


## 5. Check that background processes have completed
And finally, make sure any background processes (or callbacks in the case of Node.js) are complete before the code exits. Background processes or callbacks initiated by the function that don’t complete when the function ended will resume, if you get a warm start.


## Summary
By utilising the best practice above, you will be able to reduced latency, optimize cost, improve performance and reduced load on external resources of your AWS Lambda.


To read more, you can go to [AWS Lambda Documentation](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html) for more best practices.

Stay hungry, stay foolish, and keep learning!
Thank you for reading :D

----------
Psstt pstt :p
Do consider to love this article ❤️ and follow me! Why not right? It's FREE~
I would really appreciate it 👨🏻‍💻
Will be posting more on things related to AWS, JavaScript, Serverless and more!

Cover image by <a href="https://unsplash.com/@jdiegoph?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Diego PH</a> on <a href="https://unsplash.com/photos/fIq0tET6llw?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>