DEV Community

KenjiGoh
KenjiGoh

Posted on • Edited on

Ways to Improve Lambda Performance

✒️Reuse the Execution Context

what is the execution context? Lambda invokes your function in an execution environment (an isolated runtime environment). The execution context is a temporary runtime environment that initializes any external dependencies of your Lambda code.

🏋️‍♂️Explanation Exercise:

Create a testLambda with a 3 sec timeout limit:

Image description

Image description

Bad Practice:

import json
import os
import time

def connect_to_db():
    time.sleep(3)

def lambda_handler(event, context):
    connect_to_db()
    return os.getenv('ENVIRONMENT_NAME')
Enter fullscreen mode Exit fullscreen mode

Test with sleep 3 sec, no timeout as it is within the 3 sec limit we set. But everytime we call this lambda, it will always take 3 sec because it is trying to connect to the database everytime we run. This way of writing is not efficient.

Image description

Also, let's say if the connection to database took more than 3 sec, example 5 sec:

import json
import os
import time

def connect_to_db():
    time.sleep(5)

def lambda_handler(event, context):
    connect_to_db()
    return os.getenv('ENVIRONMENT_NAME')
Enter fullscreen mode Exit fullscreen mode

We will faced this timeout issue:
Image description

Good Practice for Better Performance:

So a Good Practice is to put the connection code outside of the lambda handler function:

import json
import os
import time

def connect_to_db():
    time.sleep(3)

# shift this out of handler
connect_to_db()

def lambda_handler(event, context):
    return os.getenv('ENVIRONMENT_NAME')
Enter fullscreen mode Exit fullscreen mode

So even though the initial run will likely take 3 sec but subsequent run only took 1.64 ms, which is much more efficient! This is because it is re-using the execution context of the previous invocation.

Image description

Top comments (0)