Getting Started with AWS Lambda. A Complete Guide with Node.js Examples

22 Mar 2024  Amiya pattanaik  7 mins read.

Introduction:

In recent years, serverless computing has gained significant traction in the world of cloud computing, offering developers a way to build and deploy applications without worrying about managing servers. AWS Lambda, a serverless compute service provided by Amazon Web Services (AWS), allows developers to run code without provisioning or managing servers, paying only for the compute time consumed. In this guide, we’ll explore AWS Lambda and demonstrate how to get started with Node.js, one of the supported programming languages.

Understanding AWS Lambda

  1. What is AWS Lambda?: - AWS Lambda is a serverless compute service offered by Amazon Web Services (AWS) that allows developers to run code without provisioning or managing servers. Developers can upload their code and Lambda automatically scales and manages the infrastructure required to run it.

  2. Key features and benefits of AWS Lambda: - Key features such as automatic scaling, pay-per-use pricing, support for multiple programming languages, event-driven architecture, seamless integration with other AWS services, and reduced operational overhead are major key features.

  3. Use cases for AWS Lambda: - Some of the most common use cases such as real-time file processing, data transformation, backend services for web and mobile applications, IoT device management, scheduled tasks, and more.

  4. Pricing model and considerations: - The pricing model is based on the number of requests and the compute time consumed, with a generous free tier for new users, cost optimization strategies such as optimizing code execution time and resource allocation are few considerations.

Setting Up AWS Lambda

  1. Sign in to the AWS Management Console:
    • If you do not have an AWS account, complete the following steps to create one.
    • To sign up for an AWS account
      • Open https://portal.aws.amazon.com/billing/signup.
      • Follow the online instructions.

    Please note that part of the sign-up procedure involves receiving a phone call and entering a verification code on the phone keypad.

    When you sign up for an AWS account, an AWS account root user is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to an administrative user, and use only the root user to perform tasks that require root user access.

    AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to https://aws.amazon.com/ and choosing My Account.

  2. Navigate to the Lambda service: - To create and manage Lambda functions, you can use the AWS Management Console. Once you Sign in to your AWS account then navigate to the Lambda service.

  3. Region selection and IAM role setup: - Make sure you are selecting the appropriate AWS region based on the target audience or requirements, and ensure you have the IAM roles to grant necessary permissions to Lambda functions.

Creating a Lambda Function:

  1. Click on “Create function” button.

  2. Choose authoring options (Blueprints, Runtime, Function name, etc.).

  3. Configure triggers (API Gateway, S3, CloudWatch Events, etc.).

  4. Write or upload your code (Node.js in this case).

  5. Configure function settings (Memory, Timeout, VPC, etc.).

Writing Your First Lambda Function in Node.js

Use cases and scenarios using Node.js for AWS Lambda functions.

  • Example 1: Processing S3 Events.
  const AWS = require('aws-sdk');

  exports.handler = async (event) => {
    const s3Event = event.Records[0].s3;
    const bucketName = s3Event.bucket.name;
    const objectKey = decodeURIComponent(s3Event.object.key.replace(/\+/g, ' '));

    console.log(`New object detected in bucket: ${bucketName}, Key: ${objectKey}`);

    // Perform processing on the uploaded object
    // Example: Generate thumbnails, analyze content, etc.

    return 'S3 event processed successfully';
};

This Lambda function is triggered by an event in an Amazon S3 bucket. It extracts information about the bucket and the object that triggered the event, performs processing (e.g., generating thumbnails, analyzing content), and returns a success message.

To test the Lambda function triggered by an S3 event, you can simulate an S3 event using the AWS CLI or the AWS Lambda console.

# Simulate an S3 event

aws lambda invoke --function-name YourLambdaFunctionName --payload '{ "Records": [ { "s3": { "bucket": { "name": "your-bucket-name" },  "object": { "key": "your-object-key" } } } ] }' output.json

# Replace YourLambdaFunctionName, your-bucket-name, and your-object-key with the appropriate values.
  • Example 2: Handling API Gateway Requests
exports.handler = async (event) => {
  const requestBody = JSON.parse(event.body);
  const name = requestBody.name;

  return {
      statusCode: 200,
      body: JSON.stringify({ message: `Hello, ${name}!` })
    };
};

This Lambda function is integrated with API Gateway and handles HTTP requests. It parses the JSON request body, extracts the name, and returns a personalized greeting in the response.

You can test the Lambda function integrated with API Gateway by sending an HTTP request to the API endpoint using tools like cURL or Postman.

# Send a POST request to the API Gateway endpoint

curl -X POST -H "Content-Type: application/json" -d '{"name": "John"}' https://your-api-gateway-endpoint.execute-api.us-east-1.amazonaws.com/prod/your-resource-name

# Replace https://your-api-gateway-endpoint.execute-api.us-east-1.amazonaws.com/prod/your-resource-name with the actual API Gateway endpoint.
  • Example 3: Scheduled Tasks with CloudWatch Events
exports.handler = async (event) => {
  console.log('Scheduled task executed:', new Date().toISOString());

  // Perform scheduled tasks, such as data backups, cleanup, etc.

  return 'Scheduled task completed successfully';
};

This Lambda function is triggered by a scheduled CloudWatch Events rule. It executes periodic tasks, such as data backups or cleanup operations, and logs the execution timestamp.

You can manually trigger the Lambda function associated with a CloudWatch Events rule from the AWS Lambda console.

  • Example 4: Integrating with DynamoDB
const AWS = require('aws-sdk');

exports.handler = async (event) => {
    const dynamodb = new AWS.DynamoDB.DocumentClient();

    // Example: Retrieve data from DynamoDB
    const params = {
        TableName: 'MyTable',
        Key: {
            id: 'example_id'
        }
    };

    try {
        const data = await dynamodb.get(params).promise();
        console.log('Retrieved data from DynamoDB:', data.Item);
        return data.Item;
    } catch (error) {
        console.error('Error retrieving data from DynamoDB:', error);
        throw new Error('Failed to retrieve data from DynamoDB');
    }
};

You can test the Lambda function interacting with DynamoDB by invoking it manually with a sample event containing necessary data.

# Invoke the Lambda function with a test event
aws lambda invoke --function-name YourLambdaFunctionName --payload '{"key": "example_id"}' output.json

# Replace YourLambdaFunctionName with the actual name of your Lambda function.

These examples demonstrate various methods to test or invoke Lambda functions, depending on the trigger or integration mechanism used. Adjust the commands and parameters as needed based on your specific setup and requirements.

Conclusion

AWS Lambda revolutionizes the way developers build and deploy applications, offering a serverless computing environment that scales seamlessly and reduces operational overhead.

These examples illustrate the versatility of AWS Lambda with Node.js, showcasing how you can build serverless applications that respond to various events, handle HTTP requests, execute scheduled tasks, and integrate with AWS services like S3 and DynamoDB seamlessly from setting up your first function to integrating with other AWS services and implementing best practices for performance and reliability. With this knowledge, you’re well-equipped to leverage the power of serverless computing for your projects on AWS. Happy coding!

Please visit my other cloud computing related writings on this website. Enjoy your reading!

We encourage our readers to treat each other respectfully and constructively. Thank you for taking the time to read this blog post to the end. We look forward to your contributions. Let’s make something great together! What do you think? Please vote and post your comments.

Amiya Pattanaik
Amiya Pattanaik

Amiya is a Product Engineering Director focus on Product Development, Quality Engineering & User Experience. He writes his experiences here.