AWS Tutorial menu

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

  1. An event happens, such as a file upload to S3, an HTTP request, or a schedule (every night at 2 am)
  2. Lambda starts your function and passes the event data to it
  3. Your function runs and returns a result
  4. 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

python
def lambda_handler(event, context):
    name = event.get("name", "student")
    return {
        "statusCode": 200,
        "body": f"Assalam o Alaikum, {name}! Welcome to Workownix."
    }
  • lambda_handler is the handler, the function Lambda calls
  • event holds the input data, as a Python dictionary
  • context holds information about the run, such as the time left

Click Test, create a test event {"name": "Ayesha"}, and run it:

Output
{
  "statusCode": 200,
  "body": "Assalam o Alaikum, Ayesha! Welcome to Workownix."
}

Calling It from the CLI

Example

bash
aws lambda invoke --function-name greet-student \
  --cli-binary-format raw-in-base64-out \
  --payload '{"name": "Ali"}' response.json
cat response.json
Output
{"statusCode": 200, "body": "Assalam o Alaikum, Ali! Welcome to Workownix."}

Triggers

A trigger is what starts your function. Popular triggers:

TriggerExample use
API Gateway or Function URLBuild a small REST API
S3Make a thumbnail when an image is uploaded
EventBridge scheduleSend a daily report at 9 am
DynamoDB StreamsReact when a new order is saved
SQS queueProcess jobs one by one

Example: Reacting to an S3 Upload

This function logs the name of every file uploaded to a bucket:

Example

python
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:

Output
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

SettingDetail
Maximum run time15 minutes per call
MemoryFrom 128 MB up to about 10 GB; more memory also gives more CPU
BillingNumber 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?

Learn AWS with a teacher

Join the CIT (Computer Information Technology) course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp