AWS Serverless Application Model

  • Topics

An Overview of AWS SAM

With the speed at which the serverless development world moves, and especially the AWS serverless ecosystem, changes come so quickly that getting the serverless architecture right becomes a problem. In this post, we’ll explore the AWS Serverless Application Model (SAM), and look at the benefits that it brings to serverless development.

Serverless Development in AWS Lambda

AWS Lambda Icon Logo

In Amazon Web Services, serverless functions are provided by AWS Lambda. AWS Lambda functions are pieces of code that are executed on-demand, based on events generated by AWS services such as DynamoDB or S3. At their core, AWS Lambda functions do not speak to or account for an overarching design in your system; these functions are the cogs in the larger machine being driven by your application’s control flow pipelines. With this naive view in mind of serverless functions, AWS Lambda lends itself well to event-driven applications, and its ability to scale quickly and easily works well for both intermittent workloads and interactive systems.

Maintaining Serverless Applications

The challenges in serverless development stem from the nature of how AWS Lambda functions operate. These functions are treated as atomic units and operate in complete isolation, meaning that all resources used by the function are destroyed a brief time after function execution.

This makes building a complete picture of your serverless application challenging in every aspect, from source control to request tracing. In addition, as these functions are executing at the lowest levels of your application architecture, the complexity of their interactions has a tendency to grow in a decentralized manner.

aws lambda complex

The challenges of serverless development even extend to the way in which you organize your code. As each function can conceivably be modeled as an incredibly small web service, you’re faced with a dependency deployment problem that is not only tasked with getting the version calculus correct, but ensuring each deployed function gets its own copy of all the dependency correctly.

Each project manages its own configuration file with this information, replacing code sharing with simple file copying based on the dependency manager of the day. This, coupled with a versioning and deployment system that allows each function to have multiple versions, makes it easy to lose track of things when problems occur.

AWS SAM to the Rescue

aws sam

Recognizing the growing problems in serverless development, AWS introduced the Serverless Application Model (SAM). AWS SAM is a framework that drives development, deployment and debugging of serverless applications.

SAM establishes patterns for development, keeping all of the code for a serverless application within the same repository structure. AWS SAM uses a combination of configuration files, pattern models, and command-line tools to ease the process of serverless development. This allows developers to centralize their efforts, reducing code duplication and complexity through a powerful build and deployment system.

AWS SAM CLI

AWS SAM, as an application framework, comes with a large number of tools out-of-the-box. The framework builds upon the robust base provided by the AWS CLI to give developers all the tools they need.

The AWS SAM CLI lets you quickly invoke Lambda functions locally, execute unit tests, spin up a stub API or event system, and more. The template system SAM is built upon reduces the complexity of configuring AWS Lambda functions with their related triggers, giving you a single location from which to access all of your critical application configuration settings. Furthermore, the SAM CLI is Unix-compliant and easily integrates with Continuous Integration and Continuous Delivery (CI/CD) pipelines.

Serverless Application Model: A Deeper Dive

AWS SAM is an open-source framework for building serverless applications. It provides shorthand syntax to express functions, APIs, databases, and event source mappings. You need to build a YAML file for each application with just a few lines for each resource and model it. It transforms the SAM syntaxes in a template YAML file to CloudFormation syntax.

SAM has two major components:

AWS SAM template specification

Template specification is used to define serverless applications. It provides a simple syntax to describe the functions, APIs, permissions, configurations, and events that make up a serverless application. AWS SAM template file is a single, deployable, versioned entity for your serverless application.

Following is the YAML-formatted template fragment:

Transform: AWS::Serverless-2016-10-31

Globals:
  set of globals

Description:
  String

Metadata:
  template metadata

Parameters:
  set of parameters

Mappings:
  set of mappings

Conditions:
  set of conditions

Resources:
  set of resources

Outputs:
  set of outputs

AWS SAM command-line interface (AWS SAM CLI)

The SAM CLI is used to build serverless applications that are defined by AWS SAM templates.

  • SAM CLI provides commands that verify and ensure that AWS SAM template files are written according to the specification.
  • SAM CLI provides Lambda-like execution environments locally so that you can invoke Lambda functions locally, and step-through debug them.
  • It provides the commands to package and deploy serverless applications to the AWS cloud, and so on.

Image Source

Following are the most used commands in the SAM CLI:

  • sam init – For the first time user, this command without any parameters creates a Hello World application. You can select the language (e.g., NodeJS or Python)  in which you want to generate the code. The command generates a preconfigured AWS SAM template and example application code.
  • sam local invoke and sam local start-api – These commands create Lambda-like execution environments in local to enable the local testing and debugging, before deploying it to the AWS cloud.
  • sam logs – As functions are part of a CloudFormation stack, you can use this command to fetch logs generated by your Lambda function based on the function’s logical id. This can help you with testing and debugging your application in the cloud.
  • sam package – This command is used to bundle your application code and dependencies into a zip or jar file also known as “deployment package”. The deployment package is needed to upload your application to the S3 bucket to be used by the Lambda function.
  • sam deploy – This command is used to deploy a serverless application to the AWS cloud. It creates the AWS resources and sets permissions and other configurations that are defined in the AWS SAM template.

The Benefits of AWS SAM

AWS SAM not only creates Lambda resources but many other AWS resources through the template configuration. It has several advantages over the basic CloudFormation templates:

Single-Deployment Configuration

AWS SAM brings together all the related components and resources and operates on a single CloudFormation stack. It is deployed as a single versioned entity that shares configuration (such as memory and timeouts) between resources and deploys all related resources together.

Extension of AWS CloudFormation

AWS SAM is an extension of AWS CloudFormation. It can use a full suite of resources, intrinsic functions, and other template features available in AWS CloudFormation. In AWS SAM templates the Resources section can contain both AWS CloudFormation resources and AWS SAM resources. It brings more brevity and less configuration compared to CloudFormation for creating serverless applications.

Local Debugging and Testing

The SAM CLI provides a Lambda-like execution environment locally. The serverless application defined by SAM templates is deployed to this environment and can be tested and debugged locally. This enables the simulation of an AWS Lambda environment locally and ensures the code will run on the cloud without issues. It reduces the cost of testing and debugging code in the cloud. AWS has provided the AWS Toolkit for different IDEs, such as Visual Studio, IntelliJ, JetBrains, and others. This accelerates the feedback loop by making it possible to run and troubleshoot issues in the local that you might face in the cloud.

Deep Integration with Development Tools

AWS SAM can be used with several other AWS tools for building serverless applications. To discover new applications, you can go to the AWS Serverless Application Repository. The AWS Cloud9 IDE can be used for coding, testing, and debugging AWS SAM–based serverless applications. CodeBuild, CodeDeploy, and CodePipeline are used for continuous integration and deployment.

Build a Serverless Application using AWS SAM

Prerequisite

You need to have the SAM CLI installed in your local environment. In Linux, you can install it using Homebrew.

$ brew tap aws/tap

$ brew install aws-sam-cli

Download a Sample AWS SAM Application

Once SAM CLI is installed, you can use SAM commands to download a SAM template for a default Hello World application and example code.

Command to run:

sam init

You need to follow the on-screen steps and fill in information such as the name of the application, runtime, dependency, and template.

SAM will create a directory and generate the code based on the runtime selected and also a template.yaml file. Here’s an example:

Build Application

To build the application go into the directory where the template.yaml file is stored. Then run the below command:

sam build

It will generate output like this:

SAM CLI will transform the SAM template to CloudFormation syntaxes, build the dependencies, and put them under the build folder.

Deploy Application To AWS Lambda Service

To deploy the application to the AWS cloud, we need to package the code as a zip file and upload it to S3 from where the Lambda service will download the code and execute it.

Run this command for deploying the application:

sam deploy --guided

It will prompt several questions on the screen. Answer those and deploy it. If you press the Enter button without entering any value, it will accept the default answers. The output will be similar to this:

It will expose an https endpoint through API Gateway and that can be used to test the application. If you hit the endpoint, it will give this JSON response:

{"message": "hello world"}

Test the Application Locally

AWS SAM provides a couple of commands to run this serverless application locally. Use this commands to run:

sam local start-api

The start-api command starts up a local endpoint that replicates your REST API endpoint. It downloads an execution container that you can run your function locally in. The end result is the same output that you saw when you called your function in the AWS cloud.

You just need to have Docker setup as a prerequisite to test the application.

Once the application starts in the local environment, you can run a curl command to test it:

curl http://127.0.0.1:3000/hello

The response will be the same JSON we observed above.

Conclusion

In this article, we have looked at the AWS SAM framework in detail. It is a very widely used framework to automate the deployment of serverless applications around Lambda, API Gateway, DynamoDB, and S3 services. It is much simpler than CloudFormation scripts. If the use case is simple, prefer to use SAM over CloudFormation, unless you need the more complex CloudFormation features that SAM doesn’t offer.