From f5efdcd29b17c8dba6ea693cb8133af20dd3b50f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joon=20Hwan=20=EA=B9=80=EC=A4=80=ED=99=98?= Date: Thu, 9 Dec 2021 19:03:28 +0900 Subject: [PATCH] Drastically reduce cold start times by calling LambdaHandler externally (#982) * ADD: LambdaHandler outside * UPDATE: apply to INSTANTIATE_LAMBDA_HANDLER_ON_IMPORT variable Co-authored-by: Will Boyce --- README.md | 5 +++++ zappa/handler.py | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index aec948dbf..ae4bcae0f 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ - [Application Load Balancer Event Source](#application-load-balancer-event-source) - [Endpoint Configuration](#endpoint-configuration) - [Example Private API Gateway configuration](#example-private-api-gateway-configuration) + - [Cold Starts (Experimental)](#cold-starts-experimental) - [Zappa Guides](#zappa-guides) - [Zappa in the Press](#zappa-in-the-press) - [Sites Using Zappa](#sites-using-zappa) @@ -1443,6 +1444,10 @@ apigateway_resource_policy.json: } ``` +### Cold Starts (Experimental) + +Lambda may provide additional resources than provisioned during cold start initialization. Set `INSTANTIATE_LAMBDA_HANDLER_ON_IMPORT=True` to instantiate the lambda handler on import. This is an experimental feature - if startup time is critical, look into using Provisioned Concurrency. + ## Zappa Guides * [Django-Zappa tutorial (screencast)](https://www.youtube.com/watch?v=plUrbPN0xc8&feature=youtu.be). diff --git a/zappa/handler.py b/zappa/handler.py index 41336dc15..dd0dcd26a 100644 --- a/zappa/handler.py +++ b/zappa/handler.py @@ -248,7 +248,8 @@ def import_module_and_get_function(whole_function): @classmethod def lambda_handler(cls, event, context): # pragma: no cover - handler = cls() + if not os.environ.get("INSTANTIATE_LAMBDA_HANDLER_ON_IMPORT"): + handler = cls() exception_handler = handler.settings.EXCEPTION_HANDLER try: return handler.handler(event, context) @@ -663,3 +664,7 @@ def keep_warm_callback(event, context): event={}, context=context ) # overriding event with an empty one so that web app initialization will # be triggered. + + +if os.environ.get("INSTANTIATE_LAMBDA_HANDLER_ON_IMPORT"): + handler = LambdaHandler()