Building Serverless Applications with AWS Lambda and Node.js
Serverless computing has revolutionized how we build and deploy applications. With AWS Lambda, you can run code without provisioning servers, and you only pay for the compute time you consume.
Why Serverless?
After managing servers for years, the appeal of serverless is clear:
- No server management - AWS handles all infrastructure
- Auto-scaling - Scales automatically with demand
- Pay-per-use - Only pay for actual execution time
- High availability - Built-in fault tolerance
Your First Lambda Function
Let's create a simple Lambda function with Node.js:
// handler.js
export const handler = async (event) => {
const { name } = JSON.parse(event.body)
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: `Hello, ${name}!`,
timestamp: new Date().toISOString()
})
}
}Infrastructure as Code with Terraform
I always use Terraform to manage Lambda functions. Here's a complete example:
# lambda.tf
resource "aws_lambda_function" "api" {
filename = "lambda.zip"
function_name = "my-api-function"
role = aws_iam_role.lambda_role.arn
handler = "handler.handler"
runtime = "nodejs20.x"
memory_size = 256
timeout = 30
environment {
variables = {
NODE_ENV = "production"
DB_HOST = var.database_host
}
}
}Best Practices
1. Keep Functions Small
Each function should do one thing. This makes them easier to test and debug.
2. Minimize Cold Starts
// Initialize outside the handler
import { DynamoDB } from '@aws-sdk/client-dynamodb'
const dynamodb = new DynamoDB({ region: 'us-east-1' })
export const handler = async (event) => {
// dynamodb is reused across invocations
const result = await dynamodb.getItem({...})
return result
}3. Use Environment Variables
Never hardcode secrets. Use environment variables or AWS Secrets Manager.
4. Implement Proper Error Handling
export const handler = async (event) => {
try {
const result = await processRequest(event)
return {
statusCode: 200,
body: JSON.stringify(result)
}
} catch (error) {
console.error('Error:', error)
return {
statusCode: error.statusCode || 500,
body: JSON.stringify({
error: error.message || 'Internal server error'
})
}
}
}Conclusion
Serverless with AWS Lambda is a powerful way to build scalable applications. Combined with Terraform for infrastructure management, you can create robust, maintainable systems that scale automatically and cost only what you use.