#1974·Zappa

Slow Cold Starts Becasue App Code Loaded Inside of Lambda Handler

Author: ElMoselYEECreated Dec 19, 2019Updated Dec 2, 2023

Context

For my Flask + Zappa setup, I noticed that the app code gets loaded inside of the lambda_handler. This prevents us from taking advantage of the bumped up horsepower that Amazon providers for free during the initialization phase.

self.app_module = importlib.import_module(self.settings.APP_MODULE)

By hand-modding my code to load my app outside of Zappa's lambda_handler middleware, I was able to reduce my cold start time from 7 seconds down to 1 second.

Expected Behavior

Take advantage of performance boost for code outside of Lambda handler by importing app code before lambda_handler is reached.

Actual Behavior

App code imported within Lambda handler, which wastes valuable time.

Possible Fix

I don't have one

Steps to Reproduce

  1. My Flask app is available at app.py
  2. Use zappa package to create a .zip file, deploy it manually
  3. Run Function: takes 7 seconds.
  4. Open up .zip file and add "import app" to line 2 of handler.py
  5. Deploy function manually
  6. Run function: takes 1 second.

I can repeat this process and the timing is very repeatable.

Your Environment

  • Zappa version used: 0.48.2

  • Operating System and Python version: Python 3.6

  • The output of pip freeze: my requirements.txt is: flask PyMySQL zappa aws-xray-sdk==2.4.2

  • Link to your project (optional):

  • Your zappa_settings.py: { "live": { "app_function": "app.flask_app", "aws_region": "us-east-1", "profile_name": "default", "project_name": "flask-app", "runtime": "python3.6", "s3_bucket": "zappa-380dxekze", "context_header_mappings": { "x-authorized-dealers": "authorizer.dealers", "x-authorized-groups": "authorizer.groups" } } }