Skip to content

watch Option for SAM Build command #921

Open

Description

@jfuss

Describe your idea/feature/enhancement

When using sam build to build functions that will later be invoked through sam local [invoke|start-lambda|start-api], you need to run sam build before each invoke. The reason for this requirement is because the build command places artifacts (code + dependencies + updated template) into a build folder. The sam local [invoke|start-lambda|start-api] use these built templates (this has updated locations to the built function code) by default but there is no way to update the built code without running sam build again.

Proposal

For the initial implementation of sam build, the --watch option was out of scope. The proposal is to add support for this option to all customers to enable building when source code changes.

An alternative could be to make the sam local suite of commands build the function during invoke. The main concern with this is the speed at which you can now invoke (other build enhancements might be a requirement for this, speed, incremental builds, etc).

Workaround

All of the sam local command allow 'reloading' of the function code. This means for a given template, if you update the contents of a functions Code/CodeUri, SAM CLI will mount this updated content. So the current option for making interactions easier is to have two terminal windows open, one that builds and one that you local invoke with.

Activity

  1. added
    area/build
    on Jan 8, 2019
  2. added this to the milestone on Jan 8, 2019
  3. modified the milestones: , Backlog on Jan 18, 2019
  4. alxx commented on Apr 1, 2019

    @alxx

    To me this only happens using Ruby once I've added a gem into the equation, with my functions having Gemfiles in their respective directories. Then I'm forced to build using --use-container parameter, which takes a lot of time; simply running sam build doesn't work because the app doesn't find the gems.

    If I don't use gems at all, then I have live reloading; but once I need gems, everything only works by rebuilding inside a container. And since that takes about a minute, it makes SAM pretty much unusable for me. I can't build every time I make a small change, it just takes too long.

  5. AmillerSC commented on Aug 17, 2019

    @AmillerSC

    Is there any progress on this? Having to build every time for the most minor of code changes is not ideal.

  6. sliedig commented on Oct 23, 2019

    @sliedig
    Contributor

    I'd like to see a slightly different take on this proposal. Rather than having a continual build function through --watch option, only build functions that have changed since the last build. I often find myself having to rebuild functions that haven't been modified, or just making changes to the template file, making the feedback loop unnecessarily long.

  7. tamvm commented on Nov 1, 2019

    @tamvm

    To me this only happens using Ruby once I've added a gem into the equation, with my functions having Gemfiles in their respective directories. Then I'm forced to build using --use-container parameter, which takes a lot of time; simply running sam build doesn't work because the app doesn't find the gems.

    If I don't use gems at all, then I have live reloading; but once I need gems, everything only works by rebuilding inside a container. And since that takes about a minute, it makes SAM pretty much unusable for me. I can't build every time I make a small change, it just takes too long.

    Hi @alxx,

    So what is your workaround for that? Or can you share your experience on that?

    Thank you,

  8. mims92 commented on Nov 8, 2019

    @mims92

    I don't like to compare but Chalice as this feature if I'm not mistaken ;)

  9. justengland commented on Nov 14, 2019

    @justengland

    Assuming this is hard to build the watch option since this has been open for the better part of a year. It seems an easier option would be to use a docker volume to share your code rather than requiring a build, this way you do not have to have an actual watch.

  10. dgomesbr commented on Nov 18, 2019

    @dgomesbr

    For a workaround, you're able to simply delete the .aws-sam folder at the root of your project and get back invoking your function.

    ref: rm -rf .aws-sam/*at root.

  11. dz902 commented on Dec 11, 2019

    @dz902

    Lacking of a watch mechanism is eating much of my time (and laptop battery). Would love to have this feature. Especially we are so fully-heartedly dedicate ourselves to serverless thus creating lots of APIs and functions that could really use some watching.

  12. serverhorror commented on Feb 17, 2020

    @serverhorror

    For a workaround, you're able to simply delete the .aws-sam folder at the root of your project and get back invoking your function.

    ref: rm -rf .aws-sam/*at root.

    That doesn't work for me. Running in python3.8 now and it doesn't pick up the packages in requirements.txt.

  13. codecounselor commented on Mar 12, 2020

    @codecounselor

    If you're using a Node runtime you may want to consider using Webpack to build bundles for each function instead of sam build. Then you can use webpack -w to have it watch for changes which sam local picks up.

    I followed this very excellent write-up: https://dev.to/elthrasher/managing-multiple-functions-with-aws-sam-and-webpack-1581
    I found https://www.npmjs.com/package/aws-sam-webpack-plugin also but preferred the simplicity of the former setup.

    The relevant config:

    webpack.config.js

    module.exports = {
    	entry: {
    		functionA: path.join(__dirname, 'src/functionA.js'),
    		functionB: path.join(__dirname, 'src/functionB.js'),
    	},
    	output: {
    		libraryTarget: 'commonjs2',
    		path: `${__dirname}/build`,
    		filename: '[name].js',
    	},
    	mode: process.env.NODE_ENV === 'dev' ? 'development' : 'production',
    	target: "node", // Let webpack know to generate a Node.js bundle
    }

    template.yaml

      PingFunction:
        Type: AWS::Serverless::Function
        Properties:
          CodeUri: build/
          Handler: functionA.lambdaHandler
          Runtime: nodejs12.x
    1. npx webpack -w
    2. sam local start-api
  14. kamrankhanwastaken commented on Apr 14, 2020

    @kamrankhanwastaken

    I just used nodemon for this. Going to put this here in case it would make anyone else's life easier:

    npm i -g nodemon
    nodemon --exec sam build
    

    Run this in the root folder in one terminal and run sam local start-api in another. nodemon should build the application automatically on any code changes.

  15. 26 remaining items

  16. vavdoshka commented on Jul 29, 2023

    @vavdoshka

    AWS, What does it take to solve that significant UX problem?

    Thanks to everyone who contributed with their solution; I'll re-iterate on what worked for me for Python project

    # Running Locally
    
    1. Start lambda build loop (will watch for changes and rebuild)
    
    nodemon --exec "sam build --template template.yaml --use-container" -e py
    * install nodemon globally if you don't have it already `npm install -g nodemon`
    
    2. Start local api server on port 5000
    
    sam local start-api -p 5000
    
  17. S33G commented on Jul 30, 2023

    @S33G

    AWS, What does it take to solve that significant UX problem?

    Thanks to everyone who contributed with their solution; I'll re-iterate on what worked for me for Python project

    # Running Locally
    
    1. Start lambda build loop (will watch for changes and rebuild)
    
    nodemon --exec "sam build --template template.yaml --use-container" -e py
    * install nodemon globally if you don't have it already `npm install -g nodemon`
    
    2. Start local api server on port 5000
    
    sam local start-api -p 5000
    

    This appears to be a JavaScript example

    But Python would need to be handled also

  18. vavdoshka commented on Jul 30, 2023

    @vavdoshka

    AWS, What does it take to solve that significant UX problem?
    Thanks to everyone who contributed with their solution; I'll re-iterate on what worked for me for Python project

    # Running Locally
    
    1. Start lambda build loop (will watch for changes and rebuild)
    
    nodemon --exec "sam build --template template.yaml --use-container" -e py
    * install nodemon globally if you don't have it already `npm install -g nodemon`
    
    2. Start local api server on port 5000
    
    sam local start-api -p 5000
    

    This appears to be a JavaScript example

    But Python would need to be handled also

    Nope, this works in python, it watches the files with the .py extension - -e py

    After playing with it for some time, I've added a delay to avoid re-building too quickly.

    nodemon --exec "sam build --template template.yaml --use-container" -e py --delay 2.5

  19. cesar-presence commented on Nov 14, 2023

    @cesar-presence

    almost 4 years of this issue. Any news?

  20. DanielKucal commented on Dec 24, 2023

    @DanielKucal

    Here's the command I ended up with for now:

    sam build && concurrently "nodemon --on-change-only --ext ts --exec sam build" "sam local start-api"
    

    Requires npm i -g nodemon concurrently

    It runs nodemon and sam local start-api in the background simultaneously. The trick is to have the build available before creating docker image, so it's done beforehand and nodemon does it only after changes (using --on-change-only flag).

  21. paul-uz commented on Aug 23, 2024

    @paul-uz

    +1 for this feature

  22. wyatt-shein commented on Sep 19, 2024

    @wyatt-shein

    I've only been experiencing this same issue for a bit so im only vaguely familiar but id like to a propose another solution that the sam team at AWS may be able to implement more easily than creating hot reload for the .aws-sam built folder:

    Context:
    Im using node but you can do this with others like python in a similar way.
    If i have a lambda layer that manages my dependencies and some lambda functions that utilize the dependencies in that layer, I can set my folders up in the following way that allows me to use my functions successfully with hot reload and without having to run sam build.

    Article: https://aws.amazon.com/blogs/compute/working-with-aws-lambda-and-lambda-layers-in-aws-sam/
    $ tree sam-app
    sam-app
    ├── README.md
    ├── dependencies #layer example
    │ └── nodejs
    │ └── package.json
    ├── hello-world #function example
    │ ├── app.js
    │ └── tests
    │ └── unit
    └── template.yaml

    When using the nodejs folder as described in the article and the docs, as long as you have generated the node modules manually using npm i, it should work just fine to run your code locally and have hot reloading without using sam build.

    The issue with this method is that when you need to move beyond local environments to testing or production, most pipelines will utilize sam build. When sam build is run, it will generate a nodejs folder inside your nodejs folder and not generate the dependencies correctly as it would if you didnt have the nodejs folder created (discussed in previous comments).

    So what im saying is maybe the sam developers would have an easier time fixing the current issue of duplicate nodejs folders which causes the dependency generation to not work, rather than trying to fix the issue of hot reload not working for the 'sam build' built .aws-sam folder.

  23. Frostie2 commented on Mar 20, 2025

    @Frostie2

    Coming here quite late but here's an awesome workaround (unix systems only, sorry Windows users, I'm sure there's an equivalent):

    find . -not -path "./.*" | entr -r sh -c 'sam build && sam local start-api'

    Whenever we change anything in the source code it automatically rebuilds and starts the api. Works like a charm and saves me so much time having to manually rebuild. Now I don't even need to look.
    Additionally, we don't need workarounds like storing all the libraries in the function directory which can become quite a mess!

    Explanation:

    • find . finds all files in the current directory
    • -not -path "./.*" ensures we're not tracking the build and any other folders starting with "." as this can cause recursive builds.
    • We pipe all these files into entr which watches for changes on each of these files.
    • entr -r makes sure the process created by the command we specify after is killed / restarted on file changes.
    • sh -c <command> runs the command, in this case: build and start the api

    Requirements:
    Install entr using
    brew install entr

    Now whenever you save / change a file in your source code, it automatically rebuilds and starts the api! Let me know if that works for you as well. Also, I'm sure someone already posted something equivalent out there since this is old.

  24. yjo commented on Mar 24, 2025

    @yjo

    As another workaround when using TypeScript/esbuild that doesn't require re-running the SAM CLI I've added to package.json a scripts entry like:

    "watch": "esbuild --watch app.ts --bundle --platform=node --outdir=../.aws-sam/build/MyFunction --format=cjs --target=es2020 --sourcemap"
    

    And I can now npm run watch while sam local start-api is running to have SAM recreate the function container as needed. You can check the output of sam build --debug to see the arguments it passes to esbuild and tweak accordingly.

  25. dcabib commented on Sep 22, 2025

    @dcabib
    Contributor

    Hey there! 👋 Found a solid path forward for implementing --watch

    So I dug deep into the SAM CLI codebase and honestly, we're like 80% of the way there already. The infrastructure for file watching is already built and battle-tested - it's what powers sam sync --watch.

    What's already there

    The codebase has all the heavy lifting done:

    • WatchManager class that handles the file watching logic
    • HandlerObserver using watchdog to actually monitor files
    • ResourceTrigger classes that know how to detect changes in different resource types
    • All the thread safety and graceful shutdown stuff

    Basically, sam sync --watch already does 90% of what we need, just for a different purpose.

    The implementation would be pretty straightforward

    Just need to:

    1. Add the --watch flag to sam build (literally like 5 lines of code)

    2. Create a BuildWatchManager that copies the same patterns from SyncWatchManager but calls build_context.run() instead of sync operations

    3. Wire it up in the build command - if --watch is passed, start the watch manager, otherwise do the normal single build

    What it would look like

    sam build --watch                    # watches everything
    sam build MyFunction --watch         # watches just that function
    sam build --watch --use-container    # works with all existing flags

    When files change, it just rebuilds and shows you what happened. Clean, simple.

    Why this approach rocks

    • We're not reinventing anything - just reusing proven code
    • It'll work with containers, caching, parallel builds, whatever
    • No weird workarounds needed anymore
    • Same UX patterns as the rest of SAM CLI

    The effort

    Honestly not that much work. Maybe a couple hundred lines of code max, mostly copy-pasting patterns that already work. The hard stuff (file watching, change detection, threading) is already done.

    I've been working with this codebase and I'm confident this would be clean and maintainable. Happy to take a stab at implementing it if the maintainers are cool with this approach.

    Thoughts?

  26. roger-zhangg commented on Sep 22, 2025

    @roger-zhangg
    Member

    @dcabib Thanks for the solution! I appreciate the analysis of leveraging the existing sam sync --watch infrastructure.

    My main concern is the potential for recursion issues. For instance, with flags like --build-in-source or when using --cache-dir, the watcher might end up monitoring directories that contain build outputs, which could trigger infinite rebuild loops.

    I'm assuming that sam build --watch would work cleanly only when all build artifacts are contained within the .aws-sam directory (the default behavior). This way, the watcher can simply exclude .aws-sam and avoid watching its own outputs. But when build artifacts end up elsewhere, things could get tricky.

    Have you considered how to handle these edge cases?

  27. dcabib commented on Sep 22, 2025

    @dcabib
    Contributor

    @roger-zhangg I did analyze how sam sync --watch handles this, and there's already a solid reference we can reuse part of this logic. The existing CodeResourceTrigger classes have a robust exclusion system with DEFAULT_WATCH_IGNORED_RESOURCES that already excludes .aws-sam directories and node_modules.

    For the specific edge cases you mentioned:

    --build-in-source: We can extend the exclusion patterns dynamically based on the build configuration. When this flag is used, we'd exclude common build artifact patterns (.pyc, __pycache__, target/, build/, etc.) from the source directories being watched.

    Custom --cache-dir: What about detect when the cache directory falls under the base project directory and automatically add it to the exclusion list? If it's outside the project directory, no exclusion needed

    The key insight is that we don't need to prevent these flag combinations entirely - we just need to be smart about what we exclude from watching based on the build configuration. The WatchManager already accepts a watch_exclude parameter that we can populate intelligently.

    Since sam sync --watch already handles similar complexity with exclusions and hasn't had recursion issues, I'm kind of confident we can make sam build --watch equally robust using the same patterns.

    Would this approach address your concerns?

  28. dcabib commented on Sep 27, 2025

    @dcabib
    Contributor

    🎉 Issue #921 - SOLUTION IMPLEMENTED!

    Hi @roger-zhangg and AWS SAM team - I am excited to report that the 6-year-old sam build --watch request has been fully implemented and tested!

    🔍 Discovery:

    While analyzing the codebase, I discovered that sam build --watch was already implemented but had two critical bugs:

    1. Help Discoverability: The --watch option was not visible in help text
    2. Template Change Detection: BuildContext was using stale template data

    🛠️ Fixes Applied:

    • ✅ Help Visibility: Added "watch" to BUILD_STRATEGY_OPTIONS - option now appears in help
    • ✅ Template Detection: Fixed by calling build_context.set_up() before build_context.run()
    • ✅ Enhanced Template Monitoring: Improved file watching with proper callbacks

    📊 Comprehensive Testing Results:

    • ✅ Source Code Changes: Python, Node.js files → Instant auto-rebuild
    • ✅ Template Changes: Adding new functions → Auto-rebuild
    • ✅ Dependencies: requirements.txt, package.json → Auto-rebuild
    • ✅ Container Builds: Works with --use-container for complex dependencies
    • ✅ Multi-Runtime: Python, Node.js, Java, Ruby, .NET, Go
    • ✅ Performance: Debouncing, caching, parallel builds
    • ✅ Error Recovery: Continues watching after build failures

    🚀 Ready for Review:

    PR #8286: #8286

    This completely eliminates the need for:

    • ❌ Manual sam build after every code change
    • ❌ Community workarounds (nodemon, samwatch, webpack scripts)
    • ❌ Two terminal setup (build in one, run in another)

    💻 Usage:

    sam build --watch                    # Basic projects
    sam build --watch --use-container    # With dependencies  
    sam build MyFunction --watch         # Single function
    sam build --watch --cached           # With caching
    sam build --watch --parallel         # Parallel builds

    After 6 years and 25+ frustrated community comments, developers can finally enjoy seamless local development with automatic rebuilds! 🎉

    This addresses every single pain point mentioned in the thread - from @alxx Ruby gems to @AmillerSC minor changes to @anubhavmalik console.log() edits.

    Ready for review and community testing!

  29. alxx commented on Dec 6, 2025

    @alxx

    Wow, and it's only been 6 years :) now if I could only remember what AWS SAM was...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/buildarea/localtype/feature

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions