AWS Lambda Serverless Functions
AWS Lambda runs your code only when it is needed, without you managing any server.
What is Serverless?
There are still servers, but you never see them. You upload a small piece of code called a function. AWS runs it when an event happens, and stops it when it is done.
Benefits:
- No servers to update or patch
- Scales automatically from zero to thousands of requests
- You pay only for the time your code runs, measured in milliseconds
- A generous always-free allowance of requests every month
How Lambda Works
- An event happens, such as a file upload to S3, an HTTP request, or a schedule (every night at 2 am)
- Lambda starts your function and passes the event data to it
- Your function runs and returns a result
- Lambda keeps the environment warm for a while, then shuts it down
Lambda supports Python, Node.js, Java, .NET, Ruby, Go and custom runtimes.
Your First Function
In the console: Lambda then Create function, choose Author from scratch, name it greet-student, and select a Python runtime. Replace the code with:
Example
def lambda_handler(event, context):
name = event.get("name", "student")
return {
"statusCode": 200,
"body": f"Assalam o Alaikum, {name}! Welcome to Workownix."
}lambda_handleris the handler, the function Lambda callseventholds the input data, as a Python dictionarycontextholds information about the run, such as the time left
Click Test, create a test event {"name": "Ayesha"}, and run it:
{
"statusCode": 200,
"body": "Assalam o Alaikum, Ayesha! Welcome to Workownix."
}Calling It from the CLI
Example
aws lambda invoke --function-name greet-student \
--cli-binary-format raw-in-base64-out \
--payload '{"name": "Ali"}' response.json
cat response.json{"statusCode": 200, "body": "Assalam o Alaikum, Ali! Welcome to Workownix."}Triggers
A trigger is what starts your function. Popular triggers:
| Trigger | Example use |
|---|---|
| API Gateway or Function URL | Build a small REST API |
| S3 | Make a thumbnail when an image is uploaded |
| EventBridge schedule | Send a daily report at 9 am |
| DynamoDB Streams | React when a new order is saved |
| SQS queue | Process jobs one by one |
Example: Reacting to an S3 Upload
This function logs the name of every file uploaded to a bucket:
Example
def lambda_handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = record["s3"]["object"]["key"]
print(f"New file uploaded: {key} in {bucket}")
return {"processed": len(event["Records"])}Output in CloudWatch Logs after uploading fees-october.pdf:
New file uploaded: fees-october.pdf in ali-shop-images
Everything you print goes to Amazon CloudWatch Logs, which is where you look when debugging.
Permissions
Every Lambda function has an execution role (an IAM role). If your function reads from S3 or writes to DynamoDB, add those permissions to its role. Without them, the function gets an "AccessDenied" error.
Limits and Pricing
| Setting | Detail |
|---|---|
| Maximum run time | 15 minutes per call |
| Memory | From 128 MB up to about 10 GB; more memory also gives more CPU |
| Billing | Number of requests plus duration multiplied by memory |
Lambda is ideal for short tasks that happen now and then. For an app that runs all day with heavy, constant load, an EC2 instance or container may be cheaper.
Cold Starts
When a function has not run for a while, the first call takes a little longer because AWS must prepare a fresh environment. This is called a cold start. Keeping your code and libraries small makes cold starts shorter.
Exercise
Exercise
What is the maximum time a single AWS Lambda function call can run?
