AWS SAM and local serverless development
SAM templates and the transform behind them, local testing and its limits, sam sync for development, and gradual Lambda deployments with alarms.
CloudFormation templates and stacksLambda functions and the execution modelAPI Gateway and function URLs
AWS SAM and local serverless development
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- SAM is CloudFormation plus a transform. Short serverless resource types expand into ordinary resources at deploy time.
- Keep the handler logic testable as a plain function with sample events. That is the fastest feedback and needs no AWS.
- sam local runs your function in a container, so it needs Docker or a compatible tool, and it does not reproduce IAM or real service behaviour.
- Test integrations in a real development stack. sam sync and sam remote invoke make that loop short.
- sam sync bypasses some of the care of a full deployment and is meant for development stacks only.
- AutoPublishAlias with a DeploymentPreference shifts traffic gradually and rolls back on alarms.
The slow loop
You change one line of a Lambda function, zip it, upload it, send a test event, open the logs, and find a typo. Meanwhile the function’s role, trigger and queue were set up by hand and live only in your memory.
AWS SAM (Serverless Application Model) tackles both: a shorter template for serverless resources, and a CLI that builds, tests and deploys them.
The template is shorthand
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Resources:
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 180
Worker:
Type: AWS::Serverless::Function
Properties:
Runtime: nodejs24.x
Handler: index.handler
CodeUri: src/
Timeout: 30
Events:
Orders:
Type: SQS
Properties:
Queue: !GetAtt OrdersQueue.Arn
FunctionResponseTypes: [ReportBatchItemFailures]
The Transform line tells CloudFormation to expand the serverless types before deploying. I ran that expansion locally with the open source translator (aws-sam-translator 1.103.0), with a placeholder code location:
OrdersQueue AWS::SQS::Queue
Worker AWS::Lambda::Function
WorkerRole AWS::IAM::Role
WorkerOrders AWS::Lambda::EventSourceMapping
WorkerRole got the basic execution and SQS queue execution managed policies. Everything else in a SAM template is plain CloudFormation, so you can mix in any resource. For extra permissions, policy templates such as SQSPollerPolicy scope access to a named resource.
Three levels of testing
1. The function, on its own. A handler takes an event and returns a value, so call it. This is my handler for the queue above:
export const handler = async (event) => {
const batchItemFailures = [];
for (const record of event.Records) {
try {
const order = JSON.parse(record.body);
if (!order.orderId) throw new Error("missing orderId");
} catch (err) {
batchItemFailures.push({ itemIdentifier: record.messageId });
}
}
return { batchItemFailures };
};
Fed one good record, one without an ID and one that isn’t JSON, under plain Node, it returned:
{"batchItemFailures":[{"itemIdentifier":"m2"},{"itemIdentifier":"m3"}]}
Partial batch handling verified in milliseconds, with no cloud and no container. Keep business logic out of the handler and this level covers most bugs.
2. A local runtime. sam local invoke runs the function in a container that resembles Lambda, sam local start-api serves your HTTP routes, and sam local generate-event produces sample events. It needs Docker or a compatible tool. It tells you about packaging, the runtime and environment variables. It tells you nothing about IAM, quotas, timeouts against real dependencies or how events actually arrive.
3. The cloud. Emulation stops being cheap exactly where the bugs get expensive. Give each developer a stack. sam sync --watch pushes changes as you save, using a fast path for code, and sam remote invoke calls the deployed function. AWS is explicit that sync is for development stacks only.
Releasing
sam build then sam deploy packages and deploys through a change set. For risky functions, add:
AutoPublishAlias: live
DeploymentPreference:
Type: Canary10Percent5Minutes
Alarms: [!Ref WorkerErrorsAlarm]
Each deployment publishes a new version and CodeDeploy shifts the alias: 10 percent first, the rest after five minutes, back again if the alarm fires. Optional pre-traffic and post-traffic functions run checks.
SAM or CDK? SAM is a small declarative step up from YAML for serverless apps. CDK is a programming model for anything. The SAM CLI can also test a synthesized CDK app locally.
Environments and repeatability
The SAM CLI reads samconfig.toml, which stores options such as stack name, Region and parameter values per named environment. With dev and prod sections in the repository, sam deploy --config-env prod means the same thing on every machine and in CI. Keep secrets out of that file; pass names of secrets and let the function read them at run time.
Each developer’s stack should have its own names. Avoid hard-coded queue, table or function names in the template, so two copies can live side by side in one account, and read resource names from environment variables that the template fills with !Ref. That also makes the handler easy to test, because the test sets the variable.
Clean up development stacks you no longer use. They are cheap while idle, but they accumulate log groups, buckets and permissions that nobody is watching. sam delete removes the stack; retained resources stay behind and need their own decision.
What to test where
Put many cases on the plain handler: malformed input, duplicates, a dependency that throws. Put a few in the cloud: the role really can read the queue, the event arrives in the shape you assumed, the timeout and memory settings hold under a realistic batch. Save real events from a development run, with personal data removed, and reuse them as fixtures. A hand-written event that is subtly wrong will happily pass forever.
About the video
The embed is Be A Better Dev’s “AWS SAM Tutorial (with a Lambda Example!)”, January 2021, 19 minutes. Its chapters cover the project architecture, environment setup, the template, building, deploying, verifying, testing the API and running SAM locally. The runtime versions and CLI prompts have moved on, and it predates sam sync. I judged it from chapters and description only, since transcripts couldn’t be fetched. English was judged from the “English (US) original” audio track. A local testing video is in deeper.
What was run: cfn-lint passed the template, the transform expansion is real translator output, and the handler result is from Node with a hand-made event. The SAM CLI itself wasn’t installed and there is no Docker here, so every sam command comes from the AWS docs, checked 2026-11-29.
Where this fits
You can build and test one stack. Next, the machinery that ships it on every commit: delivery pipelines.
Check yourself
Your function works with sam local invoke and fails with AccessDenied when deployed. Why did local testing miss it?
Locally the code runs with your own credentials, or none, not with the function's execution role. Permissions are only proven in the cloud.
What does a nine-line AWS::Serverless::Function with an SQS event create?
At least a Lambda function, an execution role with basic execution and queue polling policies, and an event source mapping. The transform writes what you did not.
A teammate wants to use sam sync in the production pipeline because it is faster. What is the problem?
sam sync is meant for development. It can update code directly through service APIs, creating drift from the stack. Production should use sam deploy or a pipeline, with change sets.
How do you release a Lambda change to 10 percent of traffic first?
Set AutoPublishAlias so each deployment publishes a version behind an alias, add a DeploymentPreference such as Canary10Percent5Minutes, and list CloudWatch alarms that should trigger rollback.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.