What is AWS Lambda?
AWS Lambda is a serverless compute service. That means:
You don’t need to create or manage any server.
You just write your code.
AWS will run your code only when it’s needed (event-based).
You pay only for the compute time you use.
💡 Real-World Example: Save Product Data to DynamoDB
Let’s say you are building a small inventory system where each time someone adds a product, you want to store it in DynamoDB.
Here’s how we’ll do it using Lambda:
🛠️ Step-by-Step Guide
✅ Step 1: Create a DynamoDB Table
Go to AWS Console → DynamoDB → Create Table:
Table name: ProductsTable
Partition key: product_id (String)
✅ Step 2: Create a Lambda Function
In AWS Console:
Go to Lambda
Click Create Function
Select Author from Scratch
Runtime: Python 3.12 (or latest)
Name: AddProductFunction
Now paste the following code:
python
Copy
Edit
import json
import boto3
DynamoDB connection
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('ProductsTable')
def lambda_handler(event, context):
# Read data from the incoming event
product = json.loads(event['body'])
# Insert into DynamoDB
table.put_item(Item={
'product_id': product['id'],
'name': product['name'],
'category': product['category']
})
return {
'statusCode': 200,
'body': json.dumps('Product added successfully!')
}
✅ Step 3: Test the Lambda
Click on Test and use this sample event:
json
Copy
Edit
{
"body": "{\"id\": \"101\", \"name\": \"Pen\", \"category\": \"Stationery\"}"
}
✅ After running it, check your DynamoDB table — you’ll see the new product saved!
🔄 Behind the Scenes – What Just Happened?
The event['body'] contains the product details in JSON.
Lambda reads the body, parses it.
Uses boto3 (AWS SDK) to connect to DynamoDB.
Saves the product using put_item.
Returns success response.
🌐 Where Can This Be Used?
Inventory Management
User Registrations
IoT Data Storage
Image Metadata Saving (when combined with S3)
🎯 Final Thoughts
AWS Lambda allows developers to focus purely on logic, not infrastructure. Whether you're building a quick backend for a hackathon or a full microservice, Lambda scales automatically, handles failures, and reduces cost.
Top comments (0)