AWS nodejs Lambda performance

When you start making a serverless microservice backend using nodejs Lambda’s, you might overlook the fact that, while it is a single threaded language, it can perform things in parallel. Nodejs code can perform work while also waiting for some IO to finish.

Consider the following function for storing an array of items. Items can be either deleted or added to DynamoDB and each deletion/addition needs to be added to a Search index as well.

Initial code

Now this implementation of the method will execute everything sequentially. Which can lead to long execution time. Since all the individual actions are independent you could also spawn them to execute in parallel. This is shown in the following snippet.

Parallel method content

I actually only noticed this when I inspected the performance of my API using AWS XRay :-) Still I overlooked this instance. (Notice that also DynamoDB batch operations would improve the performance).

The trick to get performant code also in more complicated scenario’s is to always think: for what IO task do I have enough information. Start IO operations as soon as possible.

Another way to get more performance is to move some code out of the Lambda. In the above example the storeEvent needs to be executed here because channelId is only available inside the Lambda. But if you wouldn’t need it, you could move the code storeEvent into a DynamoDB stream trigger. This also brings nice decoupling with it.

Hope you liked this article. Let me know in the comments and encourage me to do more :-) Happy coding.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store