Search code examples
pythonamazon-web-servicesaws-lambda

Why does my AWS Lambda time out unexpectedly?


I have a working set of lambdas acting as API request handlers, using a layer to handle shared dependencies.

I want to add my own module to the layer for shared functions and classes, but when I do the lambda I have set up for testing the layer times out when importing the new module.

I can confirm the files are there with listdir(), right next to the packages that have been working fine thus far.

Here is the simplified contents of my module, named functions.py

import json
import pymysql
import boto3

class InvalidInputException(Exception):

class FailedConnectionException(Exception):

class InternalAWSException(Exception):

def cors_response(_status_code:int, _response_body:dict) -> dict :

def get_db_connection() -> pymysql.Connection:

class XOREncryptor:
    

And __init__.py

from .functions import XOREncryptor
from .functions import InvalidInputException
from .functions import FailedConnectionException
from .functions import InternalAWSException
from .functions import cors_response
from .functions import get_db_connection

These are both within a folder named helper, which is alongside the other package folders in python/

My test lambda is as follows:

def lambda_handler(event, context):
    import os
    import json
    import ssl
    import helper
    
    layer_contents = os.listdir('/opt/python')
    helper_contents = os.listdir('/opt/python/helper')
    print(layer_contents)
    print(helper_contents)
    return {
        'statusCode': 200,
        'body': ''
    }

which times out when tested using the web console's built in test function.

Running the same code without the line "import helper" works totally fine, and shows that the files are where I expect them.


Solution

  • Answering my own question. Turns out it just needed a few more seconds than the default AWS Lambda timeout of 3000ms.

    The issue was that since I had just created the package files and uploaded them immediately, python did not create the __pycache__ dir with compiled code. The first run of the testing function took about 5 seconds, but after that it takes about 30ms as expected.