Jonatan Matajonmatum.com
conceptsnotesexperimentsessays
© 2026 Jonatan Mata. All rights reserved.v2.1.1
Concepts

AWS SAM

AWS open-source framework for building serverless applications with simplified CloudFormation syntax, CLI for local development, and integrated deployment.

evergreen#aws#sam#serverless#cloudformation#cli#local-development

What it is

AWS SAM (Serverless Application Model) is an open-source framework that simplifies defining, building, and deploying serverless applications. It extends AWS CloudFormation with high-level resources specifically designed for serverless architectures, providing more concise and expressive syntax for defining Lambda functions, APIs, databases, and event flows.

SAM transforms declarative YAML templates into complete CloudFormation stacks, automatically generating resources like IAM roles, security policies, and API Gateway configurations. The framework includes a robust CLI that enables local development, testing, and deployment with a workflow optimized for rapid iteration.

Unlike other Infrastructure as Code frameworks, SAM is specifically optimized for common serverless patterns, significantly reducing the boilerplate needed to configure event-driven applications and REST APIs.

SAM template anatomy

A typical SAM template defines serverless resources with simplified syntax:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
 
Globals:
  Function:
    Runtime: nodejs20.x
    Timeout: 30
    Environment:
      Variables:
        NODE_ENV: production
 
Parameters:
  Environment:
    Type: String
    Default: dev
    AllowedValues: [dev, staging, prod]
 
Resources:
  # REST API with multiple endpoints
  UserApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref Environment
      Cors:
        AllowMethods: "'GET,POST,PUT,DELETE'"
        AllowHeaders: "'Content-Type,Authorization'"
        AllowOrigin: "'*'"
 
  # Lambda function with HTTP events
  GetUsersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/handlers/users/
      Handler: get.handler
      Events:
        GetUsers:
          Type: Api
          Properties:
            RestApiId: !Ref UserApi
            Path: /users
            Method: get
 
  # Function with DynamoDB Stream event
  ProcessUserChanges:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/handlers/streams/
      Handler: userChanges.handler
      Events:
        UserStream:
          Type: DynamoDB
          Properties:
            Stream: !GetAtt UsersTable.StreamArn
            StartingPosition: TRIM_HORIZON
            BatchSize: 10
 
  # DynamoDB table with stream enabled
  UsersTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub "${Environment}-users"
      AttributeDefinitions:
        - AttributeName: userId
          AttributeType: S
      KeySchema:
        - AttributeName: userId
          KeyType: HASH
      BillingMode: PAY_PER_REQUEST
      StreamSpecification:
        StreamViewType: NEW_AND_OLD_IMAGES
 
Outputs:
  ApiEndpoint:
    Description: "API Gateway endpoint URL"
    Value: !Sub "https://${UserApi}.execute-api.${AWS::Region}.amazonaws.com/${Environment}/"
    Export:
      Name: !Sub "${AWS::StackName}-ApiEndpoint"

Development workflow with SAM CLI

SAM CLI provides a complete toolset for the development lifecycle:

Initialization and structure

# Create project from template
sam init --runtime nodejs20.x --name my-serverless-app
 
# Generated structure
my-serverless-app/
├── template.yaml          # Infrastructure definition
├── src/
│   └── handlers/          # Lambda function code
├── events/                # Test events
└── tests/                 # Unit and integration tests

Local development

# Build application
sam build
 
# Invoke specific function locally
sam local invoke GetUsersFunction --event events/get-users.json
 
# Start local API Gateway
sam local start-api --port 3000
 
# Start local Lambda for debugging
sam local start-lambda --debug-port 5858

Deployment and synchronization

# Guided deployment (first time)
sam deploy --guided
 
# Quick deployment
sam deploy
 
# SAM Accelerate for rapid iteration
sam sync --watch --stack-name my-app-dev

SAM Accelerate: ultra-fast iteration

SAM Accelerate enables real-time synchronization during development, reducing feedback time from minutes to seconds:

# Watch mode with automatic sync
sam sync --watch --stack-name my-app-dev
 
# Selective sync by resources
sam sync --code --stack-name my-app-dev
 
# Sync with hot-reload for specific function
sam sync --watch --code --resource-id GetUsersFunction

Accelerate detects code changes and updates only modified functions, avoiding complete CloudFormation stack redeployments.

SAM vs CDK: decision framework

CriteriaSAMCDKRecommendation
Project complexityPure serverless appsMixed/complex infrastructureSAM for simple APIs, CDK for hybrid architectures
Team experienceOps/DevOps with YAMLDevelopers with TypeScript/PythonAlign with existing expertise
Local developmentNative sam localThird-party toolsSAM for frequent local testing
Code reusabilityYAML templatesProgrammatic constructsCDK for reusable components
Deployment timeFast with AccelerateSlower, large stacksSAM for rapid iteration
EcosystemAWS serverless specificAll AWS + communityCDK for broad integration
DebuggingLimited to serverlessFull debuggingBased on debugging needs

When to choose SAM

  • 100% serverless applications (Lambda + API Gateway + DynamoDB)
  • Teams with YAML/CloudFormation experience
  • Need for frequent local development
  • Projects with rapid iteration cycles
  • Simple event-driven architectures

When to choose CDK

  • Mixed infrastructure (serverless + containers + databases)
  • Teams with strong programming background
  • Need for complex template logic
  • Component reuse across projects
  • Integration with existing non-serverless systems

Advanced patterns with SAM

Nested stacks for modularity

Resources:
  AuthStack:
    Type: AWS::Serverless::Application
    Properties:
      Location: ./auth/template.yaml
      Parameters:
        Environment: !Ref Environment
 
  ApiStack:
    Type: AWS::Serverless::Application
    Properties:
      Location: ./api/template.yaml
      Parameters:
        AuthStackName: !Ref AuthStack

Layers for shared dependencies

Resources:
  SharedLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: shared-dependencies
      ContentUri: layers/shared/
      CompatibleRuntimes:
        - nodejs20.x
    Metadata:
      BuildMethod: nodejs20.x
 
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Layers:
        - !Ref SharedLayer

Why it matters

SAM represents the optimal balance between simplicity and power for teams building serverless applications on AWS. While pure CloudFormation requires hundreds of lines to configure a simple API, SAM significantly reduces boilerplate while maintaining full AWS ecosystem power.

For organizations adopting event-driven architectures, SAM eliminates local development friction — a critical problem in serverless where debugging traditionally requires costly deployments. The ability to run sam local start-api and have a complete local API replica in seconds fundamentally changes development velocity.

The framework also solves the "configuration explosion" problem typical in mature serverless projects, where each Lambda function requires specific IAM roles, security policies, and event configurations. SAM automatically generates these configurations following AWS best practices, reducing error surface and improving security posture.

References

  • AWS Serverless Application Model — AWS, 2024. Complete official framework documentation.
  • SAM CLI Command Reference — AWS, 2024. Detailed reference for all CLI commands.
  • AWS Serverless Application Repository — AWS, 2024. Repository of pre-built SAM applications.
  • AWS SAM Policy Templates — AWS, 2024. IAM policy templates for common use cases.
  • AWS SAM GitHub Repository — AWS, 2024. Official repository with specifications and examples.
  • Accelerating Serverless Development with AWS SAM Accelerate — AWS Compute Blog, 2021. Technical analysis of fast synchronization capabilities.

Related content

  • Serverless

    Cloud computing model where the provider manages infrastructure automatically, allowing code execution without provisioning or managing servers, paying only for actual usage.

  • AWS Lambda

    AWS serverless compute service that runs code in response to events without provisioning or managing servers, automatically scaling from zero to thousands of concurrent executions.

  • AWS CloudFormation

    AWS native service for defining and provisioning infrastructure as code using YAML or JSON templates, with state management and automatic rollback.

  • CI/CD

    Continuous Integration and Continuous Delivery/Deployment — practices that automate code integration, testing, and delivery to production. Foundation of modern software engineering.

  • Infrastructure as Code

    Practice of defining and managing infrastructure through versioned configuration files instead of manual processes. Foundation of modern operations automation.

  • Serverless Lab

    Personal lab for serverless architecture experiments: prototypes, patterns, and learnings about event-driven applications on AWS.

Concepts