Sub topic 1
What Serverless Means and How Lambda Is Billed
Prerequisites
Assume you know basic Python, JSON, HTTP, and IAM (AWS Identity and Access Management) policies. You also need an AWS account and permission to create Lambda functions.
The serverless model
Serverless means AWS manages the servers, operating system, scaling, and much of the patching. You provide a function and its configuration. AWS runs the function when an event arrives, such as an HTTP request or a message.
You still use servers, but you do not manage them directly. Lambda usually charges for the number of requests and the time your code runs. Memory is also important because choosing more memory gives the function more CPU and often reduces its runtime.
| Choice | Main effect |
|---|---|
| More memory | More CPU and a higher price per millisecond |
| Longer runtime | Higher duration cost |
| More requests | Higher request cost |
Writing a handler
A handler is the function Lambda calls. It receives event, which contains input from the event source, and context, which contains invocation information such as the request ID and remaining time. For an HTTP integration, return a status code and a string body.
import json
import os
def handler(event, context):
name = event.get("name", "world")
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"message": f"Hello, {name}"}),
}Configuring and securing a function
Set memory and timeout according to measured workload. A timeout limits how long one invocation can run. Store deployment-specific values, such as table names, in environment variables rather than in source code.
Lambda runs with an execution role. An execution role is an IAM role that Lambda assumes during execution. Its attached policies should allow only the actions and resources the function needs, such as dynamodb:PutItem on one table. Do not give a function administrator access merely to make an early test work.
Exercise
Why can increasing memory sometimes lower the total cost of an invocation?
Show answer
More memory also provides more CPU, so the function may finish much faster even though each millisecond costs more.