ArslanAnjum
ArslanAnjum

Reputation: 1724

Singleton instance lifecycle in AWS Lambda function (Python)

If I create a singleton instance in Lambda, and set lambda timeout to 30s. Upon next invocation, would I get the same singleton instance or a new one if same container is used. I am creating this singleton inside lambda handler and I am using python.

Upvotes: 6

Views: 8618

Answers (1)

Ehsan Bhatti
Ehsan Bhatti

Reputation: 304

AWS Lambda handles requests by bringing up containers. If a new request arrives and no container is free then it would spin up a new container use that to execute this request. However if there was a container which isn't currently processing any request, new request would be routed to this container.

So essentially if same container is used, you would get the same singleton instance. However if a new container is used to serve request, you would get a new singleton instance.

You can test it out easily by using following code. This lambda is being called from api gateway with proxy and name is sent as query param with GET request. 20 seconds delay is added so that multiple executions can run in different containers.

import json
import time

class Singleton:

   __instance = None

   @staticmethod 
   def getInstance(name):
      """ Static access method. """
      if Singleton.__instance == None:
         Singleton(name)

      print(Singleton.__instance.name)

      return Singleton.__instance


   def __init__(self,name):
      """ Virtually private constructor. """
      if Singleton.__instance != None:
         raise Exception("This class is a singleton!")
      else:
         self.name = name
         Singleton.__instance = self



def lambda_handler(event, context):
    # TODO implement

    param = event.get("queryStringParameters")
    s = Singleton.getInstance(param.get("name"))

    time.sleep(20)

    return {
        'statusCode': 200,
        'body': json.dumps(s.name)
    }

Upvotes: 14

Related Questions