Lambda & Serverless
Duration: 50 min
AWS Lambda lets you run code without provisioning or managing servers. You upload code, set triggers, and Lambda automatically scales. This module covers Lambda functions, triggers, API Gateway, and the Serverless Application Model (SAM).
Lambda Basics
AWS Lambda is a serverless compute service. You write functions in Python, Node.js, Java, Go, or other languages. Lambda automatically scales from zero to thousands of concurrent executions.
You pay only for compute time consumed, measured in milliseconds. There's a generous free tier: 1 million requests and 400,000 GB-seconds per month.
Lambda Triggers
Lambda functions are triggered by events from other AWS services:
API Gateway triggers Lambda when HTTP requests arrive.
S3 triggers Lambda when objects are uploaded or deleted.
DynamoDB Streams trigger Lambda when data changes.
SNS triggers Lambda when messages are published.
CloudWatch Events trigger Lambda on a schedule (cron).
SQS triggers Lambda when messages arrive in a queue.
API Gateway
API Gateway creates REST or WebSocket APIs that trigger Lambda functions. It handles authentication, rate limiting, and request/response transformation.
Hands-On: Create Lambda Function
Create a simple Lambda function:
cat > lambda_function.py << 'EOF'
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}
EOFPackage and deploy:
zip lambda.zip lambda_function.py
aws lambda create-function --function-name my-function \
--runtime python3.11 --role arn:aws:iam::ACCOUNT:role/lambda-role \
--handler lambda_function.lambda_handler --zip-file fileb://lambda.zipInvoke the function:
aws lambda invoke --function-name my-function response.json
cat response.jsonCreate an API Gateway trigger:
aws apigateway create-rest-api --name my-api
aws apigateway create-resource --rest-api-id api-id --parent-id root-id \
--path-part hello
aws apigateway put-method --rest-api-id api-id --resource-id resource-id \
--http-method GET --authorization-type NONEPython Boto3 Example
import boto3
import json
lambda_client = boto3.client('lambda')
# Create function
response = lambda_client.create_function(
FunctionName='my-function',
Runtime='python3.11',
Role='arn:aws:iam::ACCOUNT:role/lambda-role',
Handler='lambda_function.lambda_handler',
Code={'ZipFile': b'function code here'}
)
# Invoke function
response = lambda_client.invoke(
FunctionName='my-function',
InvocationType='RequestResponse',
Payload=json.dumps({'key': 'value'})
)
print(json.loads(response['Payload'].read()))
# Update function code
lambda_client.update_function_code(
FunctionName='my-function',
ZipFile=b'new function code'
)Serverless Application Model (SAM)
SAM is a framework for building serverless applications. Define your Lambda functions, API Gateway, and other resources in a YAML template:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: my-function
Runtime: python3.11
Handler: lambda_function.lambda_handler
CodeUri: .
Events:
ApiEvent:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /hello
Method: GET
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: prodDeploy with SAM:
sam build
sam deploy --guidedTerraform Example
resource "aws_lambda_function" "my_function" {
filename = "lambda.zip"
function_name = "my-function"
role = aws_iam_role.lambda_role.arn
handler = "lambda_function.lambda_handler"
runtime = "python3.11"
}
resource "aws_apigatewayv2_api" "my_api" {
name = "my-api"
protocol_type = "HTTP"
}
resource "aws_apigatewayv2_integration" "lambda_integration" {
api_id = aws_apigatewayv2_api.my_api.id
integration_type = "AWS_PROXY"
integration_method = "POST"
payload_format_version = "2.0"
target = aws_lambda_function.my_function.arn
}Quiz 1
❓ What is AWS Lambda?
Quiz 2
❓ What is a Lambda trigger?
Quiz 3
❓ What is API Gateway?
Quiz 4
❓ How is Lambda pricing calculated?
Quiz 5
❓ What is SAM?