AWS SAM is NUTS 🌰: Cracking into the Serverless Application Model

Llambduh's Newsletter Issue #11 - 05/05/2025

AWS SAM is NUTS 🌰: Cracking into the Serverless Application Model

Introduction

Serverless computing has become a cornerstone of modern application development, enabling developers to focus on writing code without the burden of managing infrastructure. The AWS Serverless Application Model (AWS SAM) stands out as a highly effective framework for creating, deploying, and managing serverless applications on AWS. With its comprehensive toolset and adherence to best practices, AWS SAM streamlines the entire serverless application development lifecycle. Let's delve into the fundamentals of AWS SAM and explore why it's an indispensable asset in cloud computing.

Why AWS SAM?

AWS SAM is made for developers and teams looking for an efficient and consistent approach to building serverless applications. By abstracting complex infrastructure details, AWS SAM simplifies the tasks of defining resources, deploying applications, and orchestrating updates. In the serverless paradigm, developers can prioritize writing and optimizing their code, while AWS SAM handles the backend provisioning and management. Its well structured resource definitions expedite the development process and significantly reduce the time to market, thus enabling teams to concentrate on delivering strategic business value.

Understanding Serverless Architecture

Serverless computing represents a cloud native strategy that eliminates the need for directly managing server infrastructure. The underlying cloud provider takes responsibility for the capacity management, maintenance, and automatic scaling. By adopting a pay as you go model, businesses are charged only for the compute resources consumed, which leads to substantial cost savings, especially for applications experiencing variable or unpredictable traffic. As companies grow and adapt to change, serverless architectures offer unmatched agility and reduced operational overhead, contributing to more efficient application lifecycles.

The Nuts and Bolts of AWS SAM

Built on AWS CloudFormation, AWS SAM adds a simplified syntax specifically designed for serverless resources. It allows developers to define Lambda functions, API Gateway endpoints, DynamoDB tables, and various event sources with ease. By concentrating serverless features into a unified framework, AWS SAM provides a compelling option for efficiently building, testing, and deploying scalable applications with minimal complexity.

The Building Blocks of AWS SAM

AWS SAM Template

The SAM template is the heart of AWS SAM, extending AWS CloudFormation templates with serverless centric features. It streamlines the description of Lambda functions, API Gateway setups, DynamoDB tables, and more, making it easier for developers to manage these components efficiently.

SAM Template Examples

AWS::Serverless::Function: Simplifies the Lambda function declaration with precise control over runtime, memory, and IAM roles.

MyLambdaFunction:
  Type: 'AWS::Serverless::Function'
  Properties:
    Handler: 'app.lambdaHandler'
    Runtime: 'python3.8'
    MemorySize: 128
    Timeout: 10
    Environment:
      Variables:
        TABLE_NAME: !Ref MyDynamoDBTable

AWS::Serverless::Api: Facilitates the configuration of API Gateway endpoints, improving the ease of serverless API development.

MyApi:
  Type: 'AWS::Serverless::Api'
  Properties:
    StageName: prod
    DefinitionBody:
      swagger: "2.0"
      info:
        title: "MyApi"
      paths:
        /resource:
          get:
            x-amazon-apigateway-integration:
              type: "aws_proxy"
              httpMethod: "POST"
              uri: !Sub

AWS::Serverless::SimpleTable: Eases the creation of DynamoDB tables, focusing on simplicity and efficiency.

MyDynamoDBTable:
  Type: 'AWS::Serverless::SimpleTable'

AWS::Serverless::HttpApi: Optimizes configuration for HTTP APIs in API Gateway, focusing on cost and performance.

MyHttpApi:
  Type: 'AWS::Serverless::HttpApi'
  Properties:
    StageName: beta

AWS SAM Event

AWS SAM supports a variety of event sources like Amazon S3, SNS, or DynamoDB Streams that trigger Lambda functions, enabling developers to create event driven applications effortlessly.

SAM Event Examples

S3 Event

This configuration creates a Lambda function that automatically processes images when they're uploaded to S3. The function is triggered whenever a JPEG file is added to the "uploads/" folder in the specified S3 bucket. The event filtering ensures the function only processes relevant files, improving efficiency and reducing unnecessary invocations. This pattern is ideal for workflows like image resizing, metadata extraction, or virus scanning of uploaded files.

Functions:
  ProcessS3Object:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.s3_handler
      Runtime: python3.9
      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !Ref MyS3Bucket
            Events: s3:ObjectCreated:*
            Filter:
              S3Key:
                Rules:
                  - Name: prefix
                    Value: uploads/
                  - Name: suffix
                    Value: .jpg

SNS Event

This example sets up a Lambda function that responds to specific SNS notifications. The function subscribes to the specified SNS topic and includes a filter policy that only processes messages with "critical" or "high" severity. This selective processing ensures the function focuses on high priority notifications, making it perfect for alert handling, incident response systems, or prioritized message processing workflows.

Functions:
  ProcessNotification:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.sns_handler
      Runtime: nodejs18.x
      Events:
        SNSEvent:
          Type: SNS
          Properties:
            Topic: !Ref MySnsTopic
            FilterPolicy:
              severity:
                - critical
                - high

DynamoDB Stream Event

Here, a Lambda function processes changes to a DynamoDB table in real time through its stream. The function captures new, modified, or deleted items with the "LATEST" starting position and processes them in batches of up to 100 records. With retry attempts configured, it ensures reliable processing even during temporary failures. This pattern is excellent for maintaining derived data stores, triggering notifications on data changes, or implementing event sourcing architectures.

Functions:
  ProcessDynamoDBRecords:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.dynamodb_handler
      Runtime: python3.9
      Events:
        StreamEvent:
          Type: DynamoDB
          Properties:
            Stream: !GetAtt MyDynamoDBTable.StreamArn
            StartingPosition: LATEST
            BatchSize: 100
            MaximumRetryAttempts: 3

API Gateway Event

This example defines a Lambda function that serves as a backend for a RESTful API endpoint. The function responds to GET requests at the path "/items/{id}", where {id} is a path parameter that can be used to retrieve specific information. This serverless API implementation eliminates the need for server management while providing a scalable solution for building HTTP APIs, making it ideal for building microservices, mobile backends, or public APIs.

Functions:
  ApiHandler:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.api_handler
      Runtime: nodejs18.x
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /items/{id}
            Method: GET
            RestApiId: !Ref MyApi

SQS Event

This configuration creates a Lambda function that processes messages from an SQS queue. The function processes messages in batches of up to 10, with a batching window of 60 seconds to optimize processing efficiency. This event source is perfect for implementing reliable, asynchronous processing workflows such as order processing, background tasks, or workload distribution, where tasks can be queued and processed independently of user facing components.

Functions:
  ProcessQueue:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.sqs_handler
      Runtime: python3.9
      Events:
        SQSEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt MySqsQueue.Arn
            BatchSize: 10
            MaximumBatchingWindowInSeconds: 60

AWS SAM CLI: Your Swiss Army Knife

Introduction to SAM CLI

The AWS SAM Command Line Interface (CLI) is a versatile tool that enhances the developer experience by simplifying the building, testing, and deployment of serverless applications. It integrates various tasks for a cohesive workflow, allowing for efficient application lifecycle management.

Key Features and Commands

sam init: Kickstarts a new serverless application using various runtimes and templates.

sam init --runtime python3.8 --app-template hello-world

sam build: Compiles dependencies and prepares the application for deployment.

sam build

sam local invoke: Executes Lambda functions locally for accurate testing against AWS event sources.

sam local invoke MyLambdaFunction --event event.json

sam deploy: Facilitates deployment to AWS with options for guided steps utilizing CloudFormation.

sam deploy --guided

Beyond Basics: Advanced SAM Concepts

Deployment Strategies

AWS SAM supports advanced deployment strategies such as canary releases and blue/green deployments. These strategies help minimize risks by enabling gradual traffic shifts and seamless rollbacks, ensuring smooth and controlled application updates.

MyLambdaFunction:
  Type: AWS::Serverless::Function
  Properties:
    Handler: index.handler
    Runtime: nodejs18.x
    AutoPublishAlias: live
    DeploymentPreference:
      Type: Canary10Percent5Minutes
      Alarms:
        # Alarms that trigger rollback if breached during deployment
        - !Ref AliasErrorMetricGreaterThanZeroAlarm
        - !Ref LatencyAlarm

Monitoring and Troubleshooting

AWS SAM integrates with AWS CloudWatch and AWS X-Ray for effective monitoring and debugging of serverless applications, providing insights into performance and operational readiness.

Globals:
  Function:
    Tracing: Active  # Enables X-Ray tracing

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: python3.9
      Tracing: Active
      LoggingConfig:
        LogFormat: JSON
        ApplicationLogLevel: INFO
        SystemLogLevel: WARN
      Environment:
        Variables:
          LOG_LEVEL: INFO

Security Best Practices

Security is crucial in serverless applications; AWS SAM supports best practices such as applying least privilege IAM roles, encrypting environment variables, and configuring robust API Gateway authorizations to maintain application security.

MySecureApi:
  Type: AWS::Serverless::Api
  Properties:
    StageName: prod
    Auth:
      DefaultAuthorizer: MyLambdaAuthorizer
      Authorizers:
        MyLambdaAuthorizer:
          FunctionArn: !GetAtt AuthorizerFunction.Arn
          FunctionPayloadType: TOKEN
      AddDefaultAuthorizerToCorsPreflight: false
    AccessLogSetting:
      DestinationArn: !GetAtt ApiGatewayAccessLogs.Arn
      Format: '{"requestId":"$context.requestId","ip":"$context.identity.sourceIp","requestTime":"$context.requestTime","httpMethod":"$context.httpMethod","routeKey":"$context.routeKey","status":"$context.status","protocol":"$context.protocol","responseLength":"$context.responseLength"}'
    MethodSettings:
      - ResourcePath: '/*'
        HttpMethod: '*'
        MetricsEnabled: true
        DataTraceEnabled: true
        LoggingLevel: INFO

MySecretFunction:
  Type: AWS::Serverless::Function
  Properties:
    Handler: app.handler
    Runtime: nodejs18.x
    Environment:
      Variables:
        # Reference secrets from AWS Secrets Manager
        DB_PASSWORD: '{{resolve:secretsmanager:MyDatabaseSecret:SecretString:password}}'
    Policies:
      - AWSSecretsManagerGetSecretValuePolicy:
          SecretArn: !Sub arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:MyDatabaseSecret-*

Integrations with AWS CDK

While AWS SAM is powerful independently, it also integrates well with the AWS Cloud Development Kit (CDK), offering greater abstraction and flexibility. This empowers developers to choose the correct level of detail for their infrastructure needs.

# SAM template that references resources defined by CDK
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  MyLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs18.x
      Events:
        ApiEvent:
          Type: Api
          Properties:
            RestApiId: 
              # Reference an API Gateway created by CDK
              Fn::ImportValue: CdkStack:ApiGatewayRestApiId
            Path: /lambda
            Method: GET
      Environment:
        Variables:
          # Reference a DynamoDB table created by CDK
          TABLE_NAME: 
            Fn::ImportValue: CdkStack:DynamoDBTableName

Conclusion

AWS SAM significantly reduces complexity in developing, testing, and deploying serverless applications, allowing teams to focus on business logic. By facilitating high level abstractions and integrating with AWS services, AWS SAM accelerates innovation and shortens time to market for modern cloud applications. As the serverless paradigm continues to evolve, AWS SAM remains a leader, continuously enhancing features and fostering community engagement to support building robust, secure, and scalable cloud applications.

Additional Resources

Subscribe to Llambduh and join the herd 🦙!