1. Introduction & use cases
AWS Lambda runs your code in response to events – an HTTP request, a file uploaded to S3, a queue message, a schedule – without you managing servers. You upload a function (Node.js, Python, Java, Go, .NET, Ruby or a container image), and AWS runs, scales and patches it. You pay per request and per millisecond of execution.
The AWS SAM (Serverless Application Model) CLI lets you define functions and APIs in a template, run them locally in Docker and deploy them with one command.
Where it is used
- Serverless REST APIs (with API Gateway or Function URLs)
- Processing S3 uploads (thumbnails, PDF text extraction)
- Scheduled jobs and automation (EventBridge)
- Queue/stream processing (SQS, Kinesis, DynamoDB streams)
2. Prerequisites
| You need | Version / notes |
|---|---|
| AWS account | With MFA on the root user and a non-root admin identity |
| AWS CLI v2 | Installed and configured – see the AWS guide |
| AWS SAM CLI | Install from the AWS docs (Windows MSI, macOS pkg/Homebrew, Linux zip) |
| Docker | Needed for sam local and some builds |
| Node.js LTS | Matching a Lambda Node.js runtime |
3. Local setup
1Install and check the SAM CLI
Follow “Installing the AWS SAM CLI” for your OS, then verify. Make sure Docker is running for local testing.
BASHsam --version docker info > /dev/null && echo "Docker OK"2Create a project from a template
Choose the Hello World example with a Node.js runtime.
BASHsam init --name hello-lambda --runtime nodejs22.x --app-template hello-world --package-type Zip cd hello-lambda
4. Create & run a project
1Look at the handler
Lambda calls the exported
handlerwith the event. For HTTP events returnstatusCode,headersand a stringbody.hello-world/app.mjsexport const handler = async (event) => { const name = event.queryStringParameters?.name ?? 'world'; return { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: `Hello, ${name}!`, stage: process.env.STAGE }), }; };2Check the SAM template
It defines the function, its runtime, memory/timeout, environment variables and the HTTP event.
template.yamlAWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Globals: Function: Timeout: 10 MemorySize: 256 Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: CodeUri: hello-world/ Handler: app.handler Runtime: nodejs22.x Architectures: [arm64] Environment: Variables: STAGE: dev Events: HelloWorld: Type: Api Properties: Path: /hello Method: get Outputs: HelloApi: Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"3Build and test locally
sam local invokeruns the function once;start-apiserves it on localhost:3000.BASHsam build sam local invoke HelloWorldFunction --event events/event.json sam local start-api curl "http://127.0.0.1:3000/hello?name=Asha"
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
Set non-secret settings as function environment variables in the template. Read secrets from SSM Parameter Store or Secrets Manager at cold start (and cache them), granting the function’s role permission to read only those parameters.
Environment:
Variables:
STAGE: prod
TABLE_NAME: !Ref OrdersTable
SECRET_ARN: arn:aws:secretsmanager:ap-south-1:123456789012:secret:app-xxxxKey dependencies
| Package / tool | Used for |
|---|---|
AWS SAM CLI | Init, local testing, build, deploy |
@aws-sdk/* v3 | Call other AWS services from the function |
API Gateway / Function URL | HTTP entry points |
CloudWatch Logs | Function logs (console.log) |
Powertools for AWS Lambda | Logging, tracing, metrics utilities |
esbuild | Bundle TypeScript/ESM functions (SAM supports it) |
Folder structure
hello-lambda/
├── hello-world/
│ ├── app.mjs # handler
│ └── package.json
├── events/event.json # sample event
├── template.yaml # SAM / CloudFormation
└── samconfig.toml # saved deploy settingsEssential commands
| Command | What it does |
|---|---|
sam build | Build the functions |
sam local invoke NAME -e event.json | Run once locally |
sam local start-api | Local HTTP API |
sam deploy --guided | First deploy (saves settings) |
sam logs -n NAME --tail | Stream CloudWatch logs |
sam delete | Remove the stack |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| IAM | Deploying identity with CloudFormation/Lambda/IAM permissions; a least-privilege execution role per function |
| Runtime | A supported Lambda runtime (Node.js LTS versions) |
| Entry point | API Gateway (HTTP/REST API) or a Function URL |
| Domain | API Gateway custom domain + regional ACM certificate |
| Monitoring | CloudWatch logs, metrics and alarms on errors/throttles |
Deployment steps
1Deploy with SAM
The guided deploy asks for stack name, region and confirms IAM role creation, then saves answers in
samconfig.toml.BASHsam build sam deploy --guided # next time simply: sam deploy2Call the deployed API
The URL is printed in the stack outputs.
BASHcurl "https://abc123.execute-api.ap-south-1.amazonaws.com/Prod/hello/?name=Asha"3Simple alternative: a Function URL
For a single function you can skip API Gateway and add a dedicated HTTPS endpoint.
template.yaml (function Properties)FunctionUrlConfig: AuthType: NONE # or AWS_IAM for private endpoints4Use a custom domain
Request an ACM certificate in the API’s region, create an API Gateway custom domain with it, map it to your API stage, and point DNS (Route 53 alias or CNAME) to the API Gateway domain name.
5Watch logs and set alarms
Tail logs while testing; create CloudWatch alarms for
ErrorsandThrottles.BASHsam logs -n HelloWorldFunction --stack-name hello-lambda --tail
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
Runtime.ImportModuleError: Cannot find module 'app'
Handler path mismatch. Handler: app.handler needs app.mjs/app.js in CodeUri exporting handler; use .mjs or "type": "module" for export syntax.
Task timed out after 3.00 seconds
Raise Timeout and check for slow external calls; reuse SDK clients and DB connections outside the handler.
AccessDeniedException calling another AWS service
Add the needed permission to the function’s execution role (SAM policy templates such as S3ReadPolicy).
API returns 502 Bad Gateway
For proxy integrations the function must return { statusCode, body } with body as a string; check logs for exceptions.
sam local fails: Docker not running
Start Docker Desktop/Engine; SAM runs functions in containers locally.
Slow first request (cold start)
Keep bundles small, use arm64, avoid heavy init, or enable provisioned concurrency for latency-critical paths.
Best practices
- One function per job; keep handlers small and stateless.
- Create clients outside the handler to reuse connections.
- Least-privilege execution roles; secrets from SSM/Secrets Manager.
- Set timeouts, memory and alarms deliberately.
- Use RDS Proxy or DynamoDB to avoid database connection storms.