Using AWS SAM-CLI requires rebuild every time I update the code

Viewed 2639

I am using SAM CLI to develop an API Gateway Lambda proxy integration. According to the docs, I should be able to use sam local start-api to test my endpoint locally. The start-api command allows for "hot reloading" as described in the AWS SAM documentation. However, I am not seeing this behavior.

My template.yaml file looks like:

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: python3.9-v1

When I run:

> sam build && sam local start-api

I can see that the endpoint is working:

Mounting HelloWorldFunction at http://127.0.0.1:3000/hello
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically.

However, when I make changes to the lambda_handler function inside of ./hello_world/app.py, the response to curl http://localhost:3000 remains the same. No hot reloading occurs.

The only solution I have found was to run sam build for each code change. This dramatically slows down development time -- because of some dependencies inside of requirements.txt, I have to wait 1-2 minutes for the build for each code change. I could just work on the file in the .aws-sam/build directory -- as suggested here -- but this seems like a bad solution because I would have to maintain two copies of the handler simultaneously.

3 Answers

A great solution to this problem is to use the skip-pull-image flag so that Docker will reuse the Lambda runtime. Essentially run:

sam local start-api -t template.yaml --skip-pull-image

This got hot reloading working for me.

I used to find it quite annoying to be running two terminals and having to repeatedly build. Hence I ended up writing a boilerplate that bundles my source code and dependencies into a dist directory, runs sam local start-api in parallel, and watches for changes to update the dist directory.

Here's the repo: https://github.com/zishanneno/aws-typescript-lambda-boilerplate

Developing and debugging with this is much faster compared to building manually on every little code update.

Related