# AWS Lambda Tutorial: Creating Your First Serverless Function

- Canonical: https://33rdsquare.com/aws-lambda-tutorial-creating-your-first-lambda-function/
- Published: 2024-09-03
- Author: Jordan Brown
- Categories: [Artificial Intelligence & Machine Learning & ChatGPT](https://33rdsquare.com/category/tech/ai/)

---

If you‘re new to cloud computing, AWS Lambda is a great place to start. Lambda lets you run code without provisioning or managing servers, making it easy to build scalable applications and automate tasks in the cloud. In this beginner-friendly tutorial, we‘ll walk through creating your first AWS Lambda function step-by-step.

## What is AWS Lambda?

First, let‘s cover some basics. AWS (Amazon Web Services) is the leading cloud platform, providing on-demand access to compute power, storage, and other IT resources over the internet on a pay-as-you-go basis. Rather than buying and maintaining your own data centers and servers, you can leverage AWS to build and run applications more efficiently.

AWS offers over 200 services, but one of the most popular is AWS Lambda. Lambda is a serverless compute service that lets you run code without provisioning or managing any underlying infrastructure. Just upload your code as a "Lambda function" and AWS takes care of everything required to run and scale your code with high availability.

The beauty of serverless computing is it allows you to focus solely on your code, not the infrastructure. There are no servers to manage, no operating systems to choose, no software to install or keep up-to-date. And you only pay for the compute time your code actually consumes—down to the millisecond. This is in contrast to traditional servers like EC2 instances that keep running (and charging you) even when not actively serving requests.

Lambda supports a variety of programming languages, including Node.js, Python, Ruby, Java, Go, C#, and others. Functions have access to compute resources like CPU, memory, networking and can integrate with many other AWS services and APIs to build full-featured applications.

## Lambda Use Cases and Benefits

So what can you do with Lambda? The use cases are endless. Lambda is commonly used for:

- Data processing and ETL jobs
- Serverless websites and backends
- Chatbots and voice assistants
- IOT backends
- Streaming data processing
- Machine learning model training and inference
- Automated backups and maintenance tasks
- And much more

Some key benefits of using Lambda:

- No servers to manage – AWS handles all the infrastructure
- Automatic scaling – Lambda scales precisely with the size of the workload
- Pay-per-use pricing – only charged for compute time used
- Integrated security – AWS Identity and Access Management (IAM) for resource access control

Okay, enough background. Let‘s get our hands dirty and create our first Lambda function!

## Creating Your First Lambda Function

For this tutorial, we‘ll create a simple "Hello World" style Lambda function that takes in a name parameter and returns a greeting. We‘ll use Python, but the same general steps apply for other languages.

### Step 1: Create a new Lambda function

1. Log in to the AWS Management Console and navigate to the Lambda page
 2. Click "Create function"
 3. Choose "Author from scratch"
 4. Enter a name for your function, e.g. "helloWorldFunction"
 5. Select Python 3.9 as the runtime
 6. Under "Change default execution role", select "Create a new role from AWS policy templates" and name it "helloWorldRole"
 7. Click "Create function"

Congrats, you just created your first Lambda function! AWS generates some sample code to get you started.

### Step 2: Update the function code

Next, replace the sample code with the following in the code editor:

```
import json

def lambda_handler(event, context):
    name = event[‘name‘]
    message = f"Hello, {name}! Welcome to AWS Lambda!"

    return {
        ‘statusCode‘: 200,
        ‘body‘: json.dumps(message)
    }
```

This function takes in an event object, extracts a ‘name‘ parameter, and returns a greeting message. Lambda uses the `lambda_handler` as the entry point to your function.

### Step 3: Configure a test event

Before we test our function, we need to configure a test event that mimics the data that would be passed to the function when invoked.

1. Click the "Test" tab in the top right
2. Select "Create new test event"
3. Choose the "hello-world" template
4. Name the event "helloWorldTest"
5. Replace the JSON with: ``` { "name": "John" } ```
6. Click "Save changes"

### Step 4: Test the Lambda function

Now let‘s test our function!

1. Make sure "helloWorldTest" is selected in the drop down
2. Click the "Test" button
3. Expand the execution result in the console below

You should see a successful response that looks like:

```
{
  "statusCode": 200,
  "body": "\"Hello, John! Welcome to AWS Lambda!\""
}
```

And with that, you‘ve created, configured and tested your first Lambda function!

## Connecting Lambda to Other AWS Services

Lambda really shines when integrated with other AWS services. Let‘s look at a couple common examples.

### Example 1: S3 Event Trigger

A popular use case is using Lambda to process files uploaded to an S3 bucket. We can configure an S3 event to automatically trigger our Lambda function whenever a new file is added.

1. Create a new S3 bucket (or use an existing one)
2. In the Lambda console, open your function and scroll to "Function overview"
3. Click "Add trigger"
4. Select "S3" from the dropdown
5. Configure the bucket and event type (e.g. "All object create events")
6. Click "Add"

Now whenever a file is uploaded to that S3 bucket, Lambda will automatically run your function, passing in details about the new S3 object in the event parameter. You can then use the AWS SDK in your function code to retrieve and process the file contents from S3.

### Example 2: DynamoDB Integration

Lambda is also commonly used in conjunction with DynamoDB, a fully managed NoSQL database service. With the AWS SDK, Lambda can easily read and write data to DynamoDB tables.

First, make sure your Lambda function has permission to access DynamoDB:

1. Open the IAM console
2. Find the IAM role you created earlier for your function (e.g. "helloWorldRole")
3. Attach the "AmazonDynamoDBFullAccess" permission policy

Then add code to your function to interact with DynamoDB:

```
import boto3

def lambda_handler(event, context):

    dynamodb = boto3.resource(‘dynamodb‘)
    table = dynamodb.Table(‘MyTable‘)

    item = {
        ‘id‘: ‘1‘,
        ‘name‘: ‘John Doe‘
    }

    table.put_item(Item=item)

    return {
        ‘statusCode‘: 200,
        ‘body‘: json.dumps(‘Successfully wrote to DynamoDB‘)
    }
```

This code snippet creates a DynamoDB client using the AWS SDK (boto3), and puts a new item into a table called "MyTable".

Of course, there are many other AWS services you can integrate with Lambda, like API Gateway, Step Functions, Kinesis, and more. The general pattern is similar: grant the necessary IAM permissions and use the AWS SDK to interact with the service in your function code.

## Scheduled Lambda Functions with EventBridge

Another handy feature is triggering Lambda functions on a schedule, which is useful for things like nightly ETL jobs, sending reports, or cleaning up old data. We can use AWS EventBridge (formerly known as CloudWatch Events) to configure a scheduled event that runs our function on a recurring basis.

1. Open the EventBridge console
2. Click "Create rule"
3. Name the rule, e.g. "scheduledHelloWorld"
4. Under "Rule type", select "Schedule"
5. Enter a cron expression for the schedule, e.g. `cron(0 9 * * ? *)` to run at 9am UTC every day
6. Under "Select targets", choose "Lambda function" and select your function
7. Click "Create"

Now your Lambda function will automatically run on the specified schedule!

## Lambda Best Practices and Limitations

To get the most out of Lambda, there are some best practices and limitations to be aware of:

- Write stateless, idempotent functions – because Lambda can scale up and down rapidly, it‘s important that your code doesn‘t rely on in-memory state that persists across invocations
- Minimize function code size – large deployment packages can increase cold start times
- Use environment variables for configuration – rather than hardcoding config in your code
- Set appropriate memory/timeout settings – more allocated memory can also improve CPU performance
- Monitor and log Lambda functions – AWS CloudWatch provides metrics and logs to help troubleshoot issues
- Be aware of Lambda service quotas – default quotas include 1000 concurrent executions per account per region

Also keep in mind Lambda has some limits, such as:

- Maximum execution time of 15 minutes per invocation
- Maximum deployment package size of 250 MB (zipped)
- Minimum memory allocation of 128 MB / maximum of 10,240 MB
- Limited local storage in `/tmp` directory (512 MB)

See the Lambda Quotas docs for full details and how to request increases.

## Lambda Pricing

Lambda offers a very generous free tier, which includes 1 million free requests per month and 400,000 GB-seconds of compute time. After that, Lambda charges based on the number of requests and the duration of your function.

If your Lambda function uses 512 MB of memory and runs for 100ms, and you make 1 million requests in a month, that would cost about $0.63 total ($0.20 per 1M requests + $0.00001667 per GB-second). Compare that to even the smallest EC2 instance which would cost over $8 per month to run 24/7, even while idle. So Lambda can provide significant cost savings, especially for workloads with unpredictable or bursty traffic.

Of course, heavy Lambda usage with long-running or high-memory functions can rack up larger bills. It‘s good practice to monitor your Lambda costs and set up a budget alert in AWS to notify you if you exceed a certain spending threshold.

## Conclusion

Congratulations, you now have a solid foundation for getting started with AWS Lambda! In this tutorial we covered the basics of serverless, created a Lambda function, tested it, and explored integrating with other AWS services and setting up scheduled invocations.

Lambda has a wide range of use cases and can enable you to build powerful, scalable applications without worrying about managing servers. It‘s a great fit for event-driven, inconsistent workloads or as "glue" connecting various AWS services.

I encourage you to think about how Lambda could enhance your own projects or automate existing workloads. Some next steps:

- Take the free Lambda tutorials and courses on AWS
- Explore the Lambda docs and try out other runtimes and features
- Integrate Lambda into a project and test its scalability and performance
- Consider using a framework like Serverless or SAM to simplify Lambda development
- Learn about other related services like AWS Step Functions and Amazon API Gateway

Hope this helped demystify AWS Lambda and happy coding! Let me know if you have any other questions.

---

Source: [AWS Lambda Tutorial: Creating Your First Serverless Function](https://33rdsquare.com/aws-lambda-tutorial-creating-your-first-lambda-function/)
