Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 420
ArslanAnjum Avatar asked Aug 31 '26 06:08

ArslanAnjum


1 Answers

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)
    }
like image 105
Ehsan Bhatti Avatar answered Sep 02 '26 21:09

Ehsan Bhatti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!