
Today, we are going to explore the world of serverless computing with a beginner-friendly AWS Lambda Tutorial. When I first stumbled across AWS Lambda back in 2018, I was skeptical. Coming from a traditional server-based architecture background, the idea of running code without worrying about servers seemed almost magical—and too good to be true. Fast-forward to today, and I can’t imagine building certain applications any other way.
Serverless computing has absolutely revolutionized how we deploy and scale applications. Despite the name, servers still exist (of course), but AWS handles all the infrastructure management, scaling, and maintenance. This lets us developers focus entirely on writing code that delivers business value. That’s the real game-changer.
Lambda is AWS’s cornerstone serverless compute service. It lets you run code without provisioning or managing servers. You upload your code package, and Lambda handles EVERYTHING else – from execution to scaling to high availability. You only pay for the compute time you actually consume, not a penny more!
Why AWS Lambda Matters: Benefits and Use Cases
The Benefits Are Game-Changing
- Zero Server Management: No patching, no updates, no maintenance. Ever.
- Automatic Scaling: Lambda instantaneously scales with your workload.
- Pay-Per-Use Pricing: Only pay for what you use, down to the millisecond.
- Built-in Fault Tolerance: Lambda automatically replicates your functions across availability zones.
- Seamless Integration: Hooks flawlessly into other AWS Cloud services like S3, DynamoDB, or API Gateway.
I remember managing a fleet of EC2 instances before Lambda – constantly worrying about capacity planning, load balancing, and those dreaded 3 AM alerts when servers crashed. Lambda eliminates ALL of these headaches! 🙌
Real-World Use Cases
Lambda excels at numerous workloads, but these are the ones I’ve personally had the most success with:
- API Backends: Creating scalable REST APIs without server management
- Real-time Data Processing: Processing streams of data from Kinesis, DynamoDB, or S3
- Scheduled Tasks: Running maintenance jobs without dedicated servers
- File Processing: Processing uploads, generating thumbnails, or data transformation
- Event-Driven Architecture: React immediately to events (like a message in an SQS queue).
For API backends specifically (which we’ll focus on today), Lambda paired with API Gateway creates a powerful, scalable solution that handles everything from authentication to request validation to business logic.
Getting Started: Your First Lambda Function
Prerequisites
Before we dive in, make sure you have:
- An AWS account
- Basic Python knowledge
- AWS CLI installed (for the CLI deployment section)
- An hour of uninterrupted focus (trust me, it’s worth it)
Tip 💡: If you are new to AWS, I highly recommend the AWS Learning Roadmap
Creating a Lambda Function via AWS Console
Let’s start with the console approach – it’s more visual and great for beginners:
- Log into the AWS Management Console and search for “Lambda”
- Click “Create function”
- Select “Author from scratch”
- Enter basic configuration:
- Function name:
hello-world-api
- Runtime: Python 3.12 (or the latest available)
- Architecture: x86_64
- Permissions: Create a new role with basic Lambda permissions
- Function name:
- Click “Create function”
You’ll be taken to the function configuration page. In the code source section, you’ll see a default lambda_function.py
file. Replace its contents with:
def lambda_handler(event, context):
name = event.get('queryStringParameters', {}).get('name', 'World')
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': f'{{"message": "Hello, {name}!"}}'
}
Code language: JavaScript (javascript)
This function will return a greeting message, using a name from the query string if provided, or defaulting to “World”.
Click “Deploy” to save your changes.
Testing Your Function in the Console
- Click the “Test” tab
- Create a new test event
- Name your test (e.g., “TestAPI”)
- Replace the default JSON with:
{
"queryStringParameters": {
"name": "AWS Beginner"
}
}
Code language: JSON / JSON with Comments (json)
- Click “Test”
You should see a response like:
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": "{\"message\": \"Hello, AWS Beginner!\"}"
}
Code language: JSON / JSON with Comments (json)
Congratulations! You’ve created and tested your first Lambda function! 🎉
Creating a Lambda Function via AWS CLI
The console is great, but as you grow more experienced, you’ll likely want to automate deployments. Here’s how to create the same function using the AWS CLI:
- Create a directory for your project:
mkdir hello-lambda-api && cd hello-lambda-api
- Now, create your Lambda function code:
cat > lambda_function.py << 'EOF'
#Same code as shown previously in the AWS console step
Code language: PHP (php)
- Zip the function:
zip -r function.zip lambda_function.py
Code language: CSS (css)
- Create an execution role (save the ARN from the output):
aws iam create-role \
--role-name lambda-basic-execution \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}'
Code language: PHP (php)
- Attach the AWSLambdaBasicExecutionRole policy:
aws iam attach-role-policy \
--role-name lambda-basic-execution \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- Create the Lambda function (wait about 10 seconds after creating the role):
aws lambda create-function \
--function-name hello-world-api-cli \
--zip-file fileb://function.zip \
--handler lambda_function.lambda_handler \
--runtime python3.12 \
--role <ROLE_ARN_FROM_STEP_4>
Code language: HTML, XML (xml)
- Test the function:
aws lambda invoke \
--function-name hello-world-api-cli \
--cli-binary-format raw-in-base64-out \
--payload '{"queryStringParameters":{"name":"CLI User"}}' \
response.json
Code language: JavaScript (javascript)
- Check the response:
cat response.json
Code language: CSS (css)
You should see an output similar to what we got in the console test.
Creating an API Endpoint
Let’s connect our Lambda function to the outside world with API Gateway:
Note: We will only cover console-based steps for this section, as this usually needs to be done less frequently. Please refer to the API Gateway documentation if you are interested in using CLI instead.
Via Console
- Go to the API Gateway console
- Find the button saying “Create API” and click on that.
- Select “REST API” and click “Build”
- Choose “New API” and name it “HelloWorldAPI”
- Now, click on the option saying “Create API”
- After that, Click “Resources” > “Create Resource”
- Enter “hello” as the resource name and click “Create Resource”
- With the new resource selected, click “Methods” > “Create Method”
- Select “GET” from the dropdown and click the checkmark
- Configure the method:
- Integration type: Lambda Function
- Lambda Function: hello-world-api
- Use Default Timeout: checked
- In the URL query string parameters section, add a URL Query String Parameter named “name”
- Complete the creation of the method by clicking “Create method”
- Now, let’s hit the top-right “Deploy API” button
- Create a new stage called “prod” and click “Deploy”
- Copy the Invoke URL – this is your API endpoint!
Test your API by navigating to: https://[your-api-id].execute-api.[region].amazonaws.com/prod/hello?name=YourName
Troubleshooting Tips
Here are some of the most common lambda issues and how to fix them:
1. Timeout Errors
Lambda functions have a default timeout of 3 seconds. If your function takes longer, increase the timeout in the Configuration tab.
2. Permission Issues
Lambda needs permission to access other AWS services. Check your execution role if you’re getting access denied errors.
3. Cold Start Latency
Your first invocation might be slow. This is normal! Lambda needs to initialize your function. For latency-sensitive applications, consider provisioned concurrency.
4. Deployment Package Size
There’s a 50MB limit for direct uploads, 250MB unzipped. If you’re using large dependencies, consider layers or optimize your package.
5. API Gateway Integration
If your API returns a 502 error, check your Lambda response format. API Gateway expects specific formatting (which we’ve used in our example).
Limitations and Things to Be Aware Of
Lambda is powerful but not perfect. Here are some limitations I’ve personally encountered:
- Maximum Execution Duration: 15 minutes per invocation. Long-running processes need to be redesigned.
- Memory Allocation: 128MB to 10GB. CPU scales with memory.
- Concurrent Executions: Default limit of 1,000 concurrent executions per region.
- Cold Starts: This can be problematic for latency-sensitive applications.
- Statelessness: Functions should be stateless. Don’t rely on the execution environment persisting between invocations.
I learned about statelessness the hard way when I tried to use the Lambda /tmp directory to cache data between invocations. It worked in testing but failed unpredictably in production when AWS recycled the execution environment. Always design for statelessness!
Next Steps and Advanced Concepts
Once you’re comfortable with basic Lambda functions, explore these advanced concepts:
- Lambda Layers: Reuse code across functions
- Step Functions: Orchestrate multiple Lambda functions
- EventBridge: Create event-driven architectures
- SAM/CloudFormation: Infrastructure as code for Lambda
- CI/CD Pipelines: Automate deployments
Read our post on managing and deploying lambdas effortlessly with AWS SAM, along with GitHub Actions automation
Conclusion: The Serverless Journey
Looking back at my serverless journey, Lambda has fundamentally changed how I approach building applications. What once required complex infrastructure now needs just a few lines of code and configuration.
Is Lambda perfect? Absolutely not. Does it solve many traditional infrastructure headaches? Absolutely yes.
My biggest piece of advice: start small, experiment, and gradually migrate non-critical workloads. You’ll quickly see where Lambda shines for your specific use cases.
Remember, serverless isn’t just about technology – it’s a mindset shift. Embrace event-driven architecture, design for statelessness, and think in terms of functions rather than applications.
What could you build with Lambda today? How would removing infrastructure management change your development process? The possibilities are limitless, and the learning curve is gentler than you might think.
Happy serverless coding! 🚀
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
Leave a Reply