+10

AWS Lambda và SQS: Cặp đôi hoàn hảo...

Mayfest2023

image.png

1. Giới thiệu AWS Lambda

1.1. Khái niệm về AWS Lambda

Chào các bạn, mình đoán rằng mình không cần phải giới thiệu nhiều về AWS (Amazon Web Services) nữa, phải không nào? Nhưng, có một thành viên trong gia đình AWS mà mình muốn giới thiệu với các bạn hôm nay, đó chính là "AWS Lambda"!

Các bạn còn nhớ những ngày tháng phải tạo và quản lý máy chủ ảo riêng của mình không? Những ngày tháng đó đã qua rồi, nhờ vào công nghệ Serverless, và AWS Lambda chính là người dẫn đầu trong lĩnh vực này.

AWS Lambda, một dịch vụ tính toán không máy chủ (Serverless), cho phép bạn chạy mã không cần phải quản lý máy chủ, tạo hoặc quản lý hạ tầng. Cứ viết code và để AWS Lambda lo lắng về mọi thứ khác!

1.2. Lợi ích của việc sử dụng AWS Lambda

Những lợi ích của việc sử dụng AWS Lambda thì "không kể xiết". Lambda tự động mở rộng ứng dụng của bạn bằng cách chạy mã đáp ứng sự kiện, đảm bảo tính an toàn và hiệu quả. Nói cách khác, bạn chỉ phải trả tiền cho thời gian tính toán bạn sử dụng. "Chất lượng đỉnh, giá cả hợp lý" là phương châm của AWS Lambda!

2. AWS Lambda kết hợp AWS SQS

2.1. Cách kích hoạt AWS Lambda bằng tin nhắn AWS SQS

Để kích hoạt AWS Lambda, chúng ta sẽ sử dụng một dịch vụ của AWS, đó chính là AWS SQS (Simple Queue Service). "Làm sao để kích hoạt AWS Lambda bằng tin nhắn AWS SQS?", các bạn thắc mắc, đúng không nào? Đơn giản lắm, các bạn à!

Đầu tiên, ta tạo một hàng đợi SQS và sau đó, khi một tin nhắn mới được gửi đến hàng đợi này, AWS Lambda sẽ được kích hoạt và xử lý tin nhắn đó. Kết hợp với AWS SDK for Node.js, bạn có thể tạo, cấu hình và kích hoạt AWS Lambda mà không cần phải chạm tới AWS Console. Thật là "siêu" phải không nào?

image.png

2.2. Cùng tạo và kích hoạt AWS Lambda với AWS SDK for Node.js nào!

Tiếp tục, mình sẽ hướng dẫn các bạn cách để tạo một hàng đợi SQS và kích hoạt AWS Lambda khi có tin nhắn mới được gửi đến hàng đợi này nhé! Đây chính là cách mà các siêu ứng dụng như Facebook, Google... thường xuyên sử dụng để xử lý các công việc một cách nhanh chóng và tiết kiệm nhất. Vậy còn chần chừ gì mà không bắt đầu nào!

Bước 1: Đầu tiên là phải login vào AWS từ terminal của bạn

Để làm được điều này, bạn cần có AWS CLI (Command Line Interface) đã được cài đặt trên máy của mình. Nếu bạn chưa có, hãy truy cập trang chủ của AWS để tải và cài đặt nó nhé.

Sau khi đã cài đặt xong, bạn chỉ cần mở terminal lên và gõ lệnh sau:

aws configure

Hệ thống sẽ yêu cầu bạn nhập Access Key ID, Secret Access Key, Default region name, và Default output format. Hãy điền thông tin tương ứng của tài khoản AWS của bạn vào đây nhé!

Bước 2: Tạo file js và cài đặt các packages cần thiết

Giờ thì đã đến lúc tạo ra chương trình của chúng ta rồi đó, nó là một file JavaScript! Ví dụ, mình sẽ tạo một file có tên là lambda_sqs.js.

Sau khi tạo xong file js, bạn cần cài đặt thêm một số packages để chương trình của chúng ta có thể chạy được. Đầu tiên là AWS SDK for Node.js, với nó, chúng ta có thể tương tác với hầu hết các dịch vụ của AWS một cách dễ dàng. Cách cài đặt thì cực kỳ đơn giản, bạn chỉ cần mở terminal và gõ lệnh sau:

npm install aws-sdk

Và đừng quên cài đặt thêm gói uuid để tạo id cho các tin nhắn của mình nữa nhé:

npm install uuid

Bước 3: Bắt tay vào code thôi!

Đầu tiên, bạn cần import các gói đã cài đặt và cấu hình SDK. Sau đó, bạn sẽ tạo một đối tượng SQS và Lambda, định nghĩa tham số cho hàng đợi SQS, tạo hàng đợi SQS và cuối cùng là tạo và kích hoạt hàm Lambda. Mình sẽ để code ở dưới cho các bạn tham khảo nhé.

// 1. Import các gói cần thiết
const AWS = require('aws-sdk');
const uuid = require('uuid');

// 2. Cấu hình SDK
AWS.config.update({ region: 'us-east-1' });

// 3. Tạo một đối tượng SQS và Lambda
const sqs = new AWS.SQS();
const lambda = new AWS.Lambda();

// 4. Định nghĩa tham số cho hàng đợi SQS
let queueParams = {
    QueueName: 'yourQueueName',
    Attributes: {
        'DelaySeconds': '60', // Tin nhắn sẽ bị trễ 60 giây trước khi được nhận
        'MessageRetentionPeriod': '86400' // Tin nhắn sẽ được giữ trong 1 ngày
    }
};

// 5. Tạo hàng đợi SQS
sqs.createQueue(queueParams, function(err, data) {
    if (err) {
        console.log("Lỗi khi tạo hàng đợi", err);
    } else {
        console.log("Tạo hàng đợi thành công, URL của hàng đợi là", data.QueueUrl);

        // 6. Kết nối nguồn sự kiện hàng đợi SQS với hàm Lambda
        let lambdaParams = {
            FunctionName: 'yourLambdaFunctionName',
            EventSource: {
                Type: 'sqs',
                UUID: uuid.v4(),
                BatchSize: 1,
                MaximumBatchingWindowInSeconds: 0,
                Enabled: true,
                Queues: [data.QueueUrl]
            }
        };

        lambda.createEventSourceMapping(lambdaParams, function(err, data) {
            if (err) {
                console.log("Lỗi khi kết nối nguồn sự kiện", err);
            } else {
                console.log("Kết nối nguồn sự kiện thành công", data);
            }
        });
    }
});

// 7. Xử lý sự kiện từ hàng đợi SQS trong hàm Lambda
exports.yourLambdaFunctionName = async (event, context) => {
    try {
        const message = event.Records[0].body; // Lấy tin nhắn từ sự kiện
        console.log("Tin nhắn từ hàng đợi SQS:", message);

        // Gọi REST API và truyền thông tin từ tin nhắn vào
        // Ví dụ:
        // const response = await axios.post('your_rest_api_endpoint', { message });
        // console.log("Kết quả từ REST API:", response.data);

        return {
            statusCode: 200,
            body: "Xử lý thành công"
        };
    } catch (error) {
        console.log("Lỗi trong quá trình xử lý:", error);
        return {
            statusCode: 500,
            body: "Lỗi xử lý"
        };
    }
};

Bước 4: Chạy code và tận hưởng thành quả

Giờ thì đã đến lúc thưởng thức thành quả của công việc chúng ta đã làm rồi đó! Các bạn chỉ cần mở terminal, điều hướng đến thư mục chứa file lambda_sqs.js và gõ lệnh sau:

node lambda_sqs.js

Ok xong. Đến đây, mình tin rằng các bạn đã có thêm nhiều kiến thức mới về cách làm việc với AWS Lambda và SQS rồi chứ? Tất nhiên đây chỉ là một ví dụ siêu đơn giản theo phong cách hello world để chúng ta cùng nhau hiểu Lambda mà thôi.

Bonus: Vậy làm sao để kiểm tra xem có bao nhiêu sqs và lambda đang tồn tại trong aws của chúng ta. Tất nhiên là một đứa cuồng commnad line thì mình sẽ ko cần vào web aws console mà vẫn có thể kiểm tra được:

Bằng cách sử dụng AWS Command Line Interface (CLI) để kiểm tra và quản lý hàng đợi SQS và hàm Lambda từ terminal. Dưới đây là các lệnh CLI cơ bản để kiểm tra thông tin hàng đợi SQS và hàm Lambda:

1. Kiểm tra danh sách hàng đợi SQS:

aws sqs list-queues

Lệnh trên sẽ liệt kê tất cả các hàng đợi SQS trong tài khoản AWS của bạn.

2. Lấy chi tiết về một hàng đợi SQS cụ thể:

aws sqs get-queue-attributes --queue-url <queue-url> --attribute-names All

Thay <queue-url> bằng URL của hàng đợi SQS bạn muốn kiểm tra. Lệnh trên sẽ trả về tất cả các thuộc tính của hàng đợi, bao gồm DelaySeconds, MessageRetentionPeriod và nhiều thuộc tính khác.

3. Kiểm tra danh sách các hàm Lambda:

aws lambda list-functions

Lệnh trên sẽ liệt kê tất cả các hàm Lambda trong tài khoản AWS của bạn.

4. Lấy chi tiết về một hàm Lambda cụ thể:

aws lambda get-function --function-name <function-name>

Thay <function-name> bằng tên của hàm Lambda bạn muốn kiểm tra. Lệnh trên sẽ trả về thông tin chi tiết về hàm Lambda, bao gồm cấu hình, ARN và nhiều thông tin khác.

Lưu ý rằng để sử dụng AWS CLI, bạn cần cài đặt CLI và cấu hình nó với thông tin đăng nhập và quyền truy cập AWS của bạn. Bạn cũng cần cung cấp thông tin xác thực (access key và secret key) khi sử dụng CLI như mình đã hướng dẫn ở trên nhé.

3. Phương pháp xử lý tin nhắn trong hàm Lambda: đồng thời và tuần tự

3.1 Xử lý đồng thời

Trong trường hợp này, mỗi khi có một tin nhắn mới đến hàng đợi, AWS Lambda sẽ tự động kích hoạt và xử lý tin nhắn. Điều này nghĩa là, nếu có nhiều tin nhắn đến cùng một lúc, chúng sẽ được xử lý đồng thời, chứ không phải lần lượt một. Đây là cách mà Lambda hoạt động theo mặc định.

let sqsParams = {
  QueueUrl: queueUrl,
  MaxNumberOfMessages: 10, // Lấy ra tối đa 10 tin nhắn cùng lúc từ hàng đợi
};

sqs.receiveMessage(sqsParams, function(err, data) {
  if (err) {
    console.log("Lỗi khi nhận tin nhắn từ hàng đợi", err);
  } else {
    // Xử lý các tin nhắn
    data.Messages.forEach(function(message) {
      console.log("Đang xử lý tin nhắn:", message.Body);
      // Hàm xử lý tin nhắn ở đây
    });
  }
});

3.2 Xử lý tuần tự

Đối lập với cách xử lý đồng thời, cách xử lý tuần tự sẽ xử lý một tin nhắn tại một thời điểm. Điều này đảm bảo rằng mỗi tin nhắn đều được xử lý một cách cẩn thận và không có "đụng hàng". Mặc dù cách xử lý này có thể mất thêm thời gian, nhưng nó lại đảm bảo rằng mỗi tin nhắn đều được xử lý một cách đúng đắn.

let sqsParams = {
  QueueUrl: queueUrl,
  MaxNumberOfMessages: 1, // Lấy ra chỉ một tin nhắn từ hàng đợi
};

sqs.receiveMessage(sqsParams, function(err, data) {
  if (err) {
    console.log("Lỗi khi nhận tin nhắn từ hàng đợi", err);
  } else {
    // Xử lý tin nhắn
    console.log("Đang xử lý tin nhắn:", data.Messages[0].Body);
    // Hàm xử lý tin nhắn ở đây
  }
});

4. Số lượng instance của Lambda và cách quản lý

4.1. Cơ chế tạo instance của AWS Lambda

Từ lúc bạn tạo một hàm Lambda, AWS Lambda sẽ tạo ra một hoặc nhiều instance để chạy hàm của bạn. Một instance ở đây có thể hiểu là một máy ảo, một container, hoặc bất kỳ thứ gì khác mà AWS Lambda sử dụng để chạy mã của bạn. Mỗi instance có thể chạy một hoặc nhiều lần hàm của bạn.

4.2. Quản lý số lượng instance

Vậy, làm thế nào để AWS Lambda quyết định khi nào nên tạo ra thêm instance, và khi nào nên giảm bớt instance? Cái này hoàn toàn tự động, các bạn không cần phải lo lắng. AWS Lambda sẽ tự động điều chỉnh số lượng instance để đáp ứng tải công việc và giúp bạn tiết kiệm tài nguyên.

Nếu một hàm Lambda của bạn không được gọi trong một thời gian dài, AWS Lambda có thể quyết định không còn cần tới các instance đang chạy hàm đó và tự động "thanh lý" chúng. Nếu sau đó hàm của bạn lại được gọi, AWS Lambda sẽ tạo ra một instance mới.

Trong trường hợp tải công việc tăng lên đột ngột, AWS Lambda sẽ tạo thêm instance để đảm bảo rằng tất cả các yêu cầu đều được xử lý một cách nhanh chóng. Mặc dù có thể có một vài giây chậm trễ khi tạo ra instance mới, nhưng chúng ta có thể chấp nhận được độ trễ này khi so sánh với lợi ích của việc tự động điều chỉnh số lượng instance.

Còn về việc có thể setting số lượng instance của lambda hay không, thì mình xin trả lời là không. AWS Lambda quản lý hoàn toàn và quyết định số lượng instance dựa trên tải công việc, chúng ta không có khả năng chỉ định trực tiếp số lượng instance.

5. Cách mà AWS scale Lambda

AWS Lambda được thiết kế để tự động mở rộng hoặc thu hẹp dựa trên yêu cầu của ứng dụng. Khi ứng dụng cần thêm tài nguyên để xử lý các yêu cầu, AWS Lambda tự động tạo thêm các bản sao (hoặc "instances") của chức năng Lambda. Mỗi bản sao này sau đó xử lý một phần nhỏ của tổng số yêu cầu.

Đầu tiên, Lambda sẽ bắt đầu bằng một bản sao duy nhất của chức năng. Khi tải trọng tăng lên, Lambda sẽ tăng số lượng các bản sao để đáp ứng yêu cầu. Mỗi bản sao sẽ xử lý một phần nhỏ của tổng số yêu cầu, giúp cân nhắc tải trọng công việc.

Cũng cần lưu ý rằng việc mở rộng này không phải lúc nào cũng diễn ra ngay lập tức. AWS Lambda sử dụng một thuật toán để dự đoán tải trọng công việc trong tương lai và quyết định số lượng bản sao cần thêm.

image.png

6. Lợi ích của việc sử dụng AWS Lambda

  1. Khả năng mở rộng tự động: Như đã nói ở trên, Lambda tự động mở rộng hoặc thu hẹp dựa trên yêu cầu, giúp ứng dụng luôn đáp ứng được yêu cầu người dùng mà không cần phải lo lắng về việc quản lý cơ sở hạ tầng.

  2. Thanh toán theo sử dụng: Với AWS Lambda, bạn chỉ phải trả cho thời gian mà mã của bạn đang chạy, không phải trả cho thời gian rảnh.

  3. Được tích hợp với nhiều dịch vụ AWS khác: Lambda có thể kết hợp với hàng đống dịch vụ AWS khác như Amazon S3, DynamoDB, API Gateway, và nhiều hơn nữa, giúp bạn tận dụng tối đa hệ sinh thái AWS.

7. Nhược điểm khi sử dụng AWS Lambda

  1. Thời gian 'lạnh': Có một khoảng thời gian 'lạnh' khi chức năng Lambda được kích hoạt sau một khoảng thời gian không hoạt động. Trong thời gian này, chức năng có thể mất thêm thời gian để trả lời.

  2. Giới hạn về tài nguyên: Lambda có một số giới hạn về tài nguyên, như thời gian chạy tối đa cho một chức năng là 15 phút, và kích thước tối đa của một gói là 50 MB.

image.png

8. Tổng kết

Vậy là chúng ta đã tìm hiểu qua về AWS Lambda và cách nó hoạt động với AWS SQS. Việc sử dụng AWS Lambda kết hợp với SQS có thể giúp bạn xây dựng các ứng dụng mạnh mẽ và mở rộng, nhưng cũng cần phải lưu ý về những giới hạn và thách thức mà nó mang lại. Hy vọng rằng thông tin trong bài viết này có thể giúp bạn hiểu rõ hơn về cách sử dụng các dịch vụ này.


ENGLISH VERSION

1. Introduction to AWS Lambda

1.1. Understanding AWS Lambda

Hello everyone, I guess I don't need to introduce AWS (Amazon Web Services) much anymore, right? But there's a member in the AWS family that I want to introduce to you today, and that is "AWS Lambda"!

Do you remember the days when we had to create and manage our own virtual servers? Those days are gone, thanks to Serverless technology, and AWS Lambda is the leader in this field.

AWS Lambda, a serverless computing service, allows you to run code without the need to manage servers, create or manage infrastructure. Just write your code and let AWS Lambda take care of everything else!

1.2. Benefits of using AWS Lambda

The benefits of using AWS Lambda are countless. Lambda automatically scales your applications by running code in response to events, ensuring safety and efficiency. In other words, you only pay for the compute time you consume. "Top quality at a reasonable price" is the motto of AWS Lambda!

2. AWS Lambda and AWS SQS Integration

2.1. Triggering AWS Lambda with AWS SQS messages

To trigger AWS Lambda, we will use a service provided by AWS, which is AWS SQS (Simple Queue Service). "How to trigger AWS Lambda with AWS SQS messages?" you might wonder. It's very simple, my friends!

First, we create an SQS queue, and then when a new message is sent to this queue, AWS Lambda will be triggered and process that message. By using the AWS SDK for Node.js, you can create, configure, and trigger AWS Lambda without having to touch the AWS Console. It's awesome, right?

image.png

2.2. Let's create and trigger AWS Lambda with AWS SDK for Node.js!

Next, I will guide you on how to create an SQS queue and trigger AWS Lambda when a new message is sent to this queue! This is the approach that super applications like Facebook, Google, etc., often use to process tasks quickly and efficiently. So, why wait any longer? Let's get started!

Step 1: First, log in to AWS from your terminal

To do this, you need to have AWS CLI (Command Line Interface) installed on your machine. If you don't have it yet, visit the AWS homepage to download and install it.

Once installed, simply open your terminal and enter the following command:

aws configure

The system will ask you to enter the Access Key ID, Secret Access Key, Default region name, and Default output format. Please enter the corresponding information of your AWS account here!

Step 2: Create a JavaScript file and install necessary packages

Now it's time to create our program, which is a JavaScript file! For example, I will create a file named lambda_sqs.js.

After creating the JavaScript file, you need to install some packages for our program to run. First, install the AWS SDK for Node.js, which allows us to interact with most AWS services easily. The installation process is very simple, just open the terminal and enter the following command:

npm install aws-sdk

And don't forget to install the uuid package to generate IDs for your messages:

npm install uuid

Step 3: Let's get coding!

First, you need to import the required packages and configure the SDK. Then, you will create an SQS object and a Lambda object, define parameters for the SQS queue, create the SQS queue, and finally create and activate the Lambda function. I'll provide the code below for your reference.

// 1. Import the necessary packages
const AWS = require('aws-sdk');
const uuid = require('uuid');

// 2. Configure the SDK
AWS.config.update({ region: 'us-east-1' });

// 3. Create an SQS object and a Lambda object
const sqs = new AWS.SQS();
const lambda = new AWS.Lambda();

// 4. Define parameters for the SQS queue
let queueParams = {
    QueueName: 'yourQueueName',
    Attributes: {
        'DelaySeconds': '60', // Messages will be delayed for 60 seconds before being received
        'MessageRetentionPeriod': '86400' // Messages will be retained for 1 day
    }
};

// 5. Create the SQS queue
sqs.createQueue(queueParams, function(err, data) {
    if (err) {
        console.log("Error creating queue", err);
    } else {
        console.log("Queue created successfully, the URL of the queue is", data.QueueUrl);

        // 6. Connect the SQS queue event source to the Lambda function
        let lambdaParams = {
            FunctionName: 'yourLambdaFunctionName',
            EventSource: {
                Type: 'sqs',
                UUID: uuid.v4(),
                BatchSize: 1,
                MaximumBatchingWindowInSeconds: 0,
                Enabled: true,
                Queues: [data.QueueUrl]
            }
        };

        lambda.createEventSourceMapping(lambdaParams, function(err, data) {
            if (err) {
                console.log("Error connecting event source", err);
            } else {
                console.log("Event source connected successfully", data);
            }
        });
    }
});

// 7. Handle events from the SQS queue in the Lambda function
exports.yourLambdaFunctionName = async (event, context) => {
    try {
        const message = event.Records[0].body; // Get the message from the event
        console.log("Message from SQS queue:", message);

        // Call the REST API and pass the information from the message
        // Example:
        // const response = await axios.post('your_rest_api_endpoint', { message });
        // console.log("Result from REST API:", response.data);

        return {
            statusCode: 200,
            body: "Processing successful"
        };
    } catch (error) {
        console.log("Error during processing:", error);
        return {
            statusCode: 500,
            body: "Processing error"
        };
    }
};

Step 4: Run the code and enjoy the results

Now it's time to enjoy the fruits of our work! You just need to open a terminal, navigate to the directory containing the lambda_sqs.js file, and run the following command:

node lambda_sqs.js

Done. By now, I believe you have gained more knowledge about working with AWS Lambda and SQS, haven't you? Of course, this is just a super simple example in the hello world style to help us understand Lambda together.

Bonus: So how can we check how many SQS queues and Lambdas are currently existing in our AWS? As an enthusiastic command-line lover, I won't need to go to the AWS web console but can still check using the AWS Command Line Interface (CLI):

Below are basic CLI commands to check information about SQS queues and Lambda functions:

1. Check the list of SQS queues:

aws sqs list-queues

The above command will list all the SQS queues in your AWS account.

2. Get details of a specific SQS queue:

aws sqs get-queue-attributes --queue-url <queue-url> --attribute-names All

Replace <queue-url> with the URL of the SQS queue you want to check. The command will return all the attributes of the queue, including DelaySeconds, MessageRetentionPeriod, and more.

3. Check the list of Lambda functions:

aws lambda list-functions

The above command will list all the Lambda functions in your AWS account.

4. Get details of a specific Lambda function:

aws lambda get-function --function-name <function-name>

Replace <function-name> with the name of the Lambda function you want to check. The command will return detailed information about the Lambda function, including configuration, ARN, and more.

Note that to use the AWS CLI, you need to install the CLI and configure it with your AWS login information and access permissions. You also need to provide authentication information (access key and secret key) when using the CLI as I instructed above.

3. Message Processing in Lambda: Concurrent and Sequential

3.1 Concurrent Processing

In this case, whenever a new message arrives in the queue, AWS Lambda will automatically trigger and process the message. This means that if multiple messages arrive at the same time, they will be processed concurrently, not one by one. This is how Lambda operates by default.

let sqsParams = {
  QueueUrl: queueUrl,
  MaxNumberOfMessages: 10, // Retrieve up to 10 messages at a time from the queue
};

sqs.receiveMessage(sqsParams, function(err, data) {
  if (err) {
    console.log("Error receiving messages from the queue", err);
  } else {
    // Process the messages
    data.Messages.forEach(function(message) {
      console.log("Processing message:", message.Body);
      // Message processing logic here
    });
  }
});

3.2 Sequential Processing

In contrast to concurrent processing, sequential processing handles one message at a time. This ensures that each message is processed carefully and there are no collisions. Although this processing approach may take more time, it guarantees that each message is processed correctly.

let sqsParams = {
  QueueUrl: queueUrl,
  MaxNumberOfMessages: 1, // Retrieve only one message from the queue
};

sqs.receiveMessage(sqsParams, function(err, data) {
  if (err) {
    console.log("Error receiving messages from the queue", err);
  } else {
    // Process the message
    console.log("Processing message:", data.Messages[0].Body);
    // Message processing logic here
  }
});

4. Number of Lambda Instances and Management

4.1. Mechanism of AWS Lambda Instance Creation

When you create a Lambda function, AWS Lambda will create one or more instances to run your function. An instance here can be understood as a virtual machine, a container, or any other resource that AWS Lambda uses to execute your code. Each instance can run your function one or more times.

4.2. Managing the Number of Instances

So, how does AWS Lambda decide when to create additional instances and when to reduce them? This is entirely automatic, and you don't have to worry about it. AWS Lambda automatically adjusts the number of instances to meet the workload demand and help you save resources.

If a Lambda function is not called for a long period, AWS Lambda may decide that the running instances for that function are no longer needed and automatically "dispose" them. If your function is called again later, AWS Lambda will create a new instance.

In cases where the workload suddenly increases, AWS Lambda will create additional instances to ensure that all requests are processed quickly. Although there may be a slight delay in creating new instances, we can accept this delay compared to the benefits of automatic instance adjustment.

Regarding the ability to set the number of Lambda instances directly, the answer is no. AWS Lambda manages and determines the number of instances based on workload demand, and we don't have the ability to directly specify the number of instances.

5. How AWS Scales Lambda

AWS Lambda is designed to automatically scale up or down based on application demand. When the application needs additional resources to handle requests, AWS Lambda automatically creates copies (or "instances") of the Lambda function. Each copy then handles a small portion of the total requests.

Initially, Lambda starts with a single copy of the function. As the workload increases, Lambda increases the number of copies to handle the requests. Each copy processes a small portion of the total requests, helping distribute the workload.

It's also worth noting that scaling doesn't always happen immediately. AWS Lambda uses an algorithm to predict future workload and determines the number of copies to be added.

image.png

6. Benefits of Using AWS Lambda

  1. Automatic Scaling: As mentioned above, Lambda automatically scales up or down based on demand, ensuring that your application can handle user requests without the need for infrastructure management.

  2. Pay-per-Use: With AWS Lambda, you only pay for the compute time your code actually uses, rather than paying for idle time.

  3. Integration with Other AWS Services: Lambda can be integrated with a variety of other AWS services such as Amazon S3, DynamoDB, API Gateway, and more, allowing you to leverage the full power of the AWS ecosystem.

7. Drawbacks of Using AWS Lambda

  1. Cold Start Time: There is a "cold start" time when a Lambda function is activated after a period of inactivity. During this time, the function may take additional time to respond.

  2. Resource Limits: Lambda has certain resource limits, such as a maximum runtime of 15 minutes for a function and a maximum package size of 50 MB.

image.png

8. Conclusion

So, we have learned about AWS Lambda and how it works with AWS SQS. Using AWS Lambda in combination with SQS can help you build powerful and scalable applications, but it's important to be aware of the limitations and challenges it brings. I hope the information in this article helps you understand more about how to use these services.


日本語バジョン

1. AWS Lambda の紹介

1.1. AWS Lambda の概要

皆さん、AWS(Amazon Web Services)についてはもう十分に知っていると思いますよね?でも、今日はAWSの家族の中で、皆さんに紹介したいメンバーがいます。それが「AWS Lambda」です!

以前、自分自身の仮想サーバーを作成して管理しなければならなかった日々を覚えていますか?それらの日々は過去のものです。サーバーレステクノロジーとAWS Lambdaのおかげで、それらの日々は過去のものになりました。

AWS Lambdaは、サーバーレスなコンピューティングサービスであり、サーバーの管理やインフラの作成や管理をする必要がなく、コードを書くだけでAWS Lambdaが他のすべてのことを処理してくれます!

1.2. AWS Lambda の利点

AWS Lambdaの利点は「数え切れないほどたくさん」あります。Lambdaはイベントに応じてコードを実行してアプリケーションを自動的にスケーリングし、安全性と効率性を確保します。つまり、使用した計算時間だけ支払う必要があります。「品質は最高で価格は合理的」というのがAWS Lambdaのモットーです!

2. AWS Lambda と AWS SQS の組み合わせ

2.1. AWS Lambda を AWS SQS メッセージでトリガーする方法

AWS Lambdaをトリガーするために、AWSのサービスであるAWS SQS(Simple Queue Service)を使用します。「どのようにしてAWS LambdaをAWS SQSメッセージでトリガーするのですか?」と皆さんは疑問に思うかもしれませんね。とても簡単ですよ!

まず、SQSキューを作成し、このキューに新しいメッセージが送信されると、AWS Lambdaがトリガーされ、そのメッセージを処理します。AWS SDK for Node.jsと組み合わせることで、AWS LambdaをAWSコンソールにアクセスせずに作成、構成、およびトリガーすることができます。これは本当に良かったね!

image.png

2.2. AWS SDK for Node.js を使用して AWS Lambda を作成およびトリガーしましょう!

次に、SQSキューを作成し、このキューに新しいメッセージが送信されたときにAWS Lambdaを作成およびトリガーする方法を説明します。これはFacebookやGoogleなどのスーパーアプリケーションが最も頻繁に使用している方法で、タスクを素早くかつ効率的に処理します。それでは、遅れることなく始めましょう!

ステップ1:まず、ターミナルからAWSにログインする必要があります

これを行うためには、自分のマシンにAWS CLI(Command Line Interface)がインストールされている必要があります。まだインストールしていない場合は、AWSの公式サイトにアクセスしてダウンロードしてインストールしてください。

インストールが完了したら、ターミナルを開き、次のコマンドを入力します:

aws configure

システムは、Access Key ID、Secret Access Key、Default region name、およびDefault output formatの入力を求めるでしょう。AWSアカウントの該当する情報を入力してください!

ステップ2:JavaScriptファイルを作成し、必要なパッケージをインストールします

さあ、プログラムを作成しましょう。それはJavaScriptファイルです!例えば、私は「lambda_sqs.js」という名前のファイルを作成します。

ファイルが作成されたら、プログラムが実行されるために必要ないくつかのパッケージをインストールする必要があります。まずはAWS SDK for Node.jsです。これを使用すると、AWSのほとんどのサービスと簡単にやり取りすることができます。インストール方法は非常に簡単で、ターミナルを開いて次のコマンドを入力するだけです:

npm install aws-sdk

そして、メッセージにIDを付けるためにuuidパッケージもインストールすることを忘れないでください:

npm install uuid

ステップ3: コーディングしましょう!

まず、インストール済みのパッケージをインポートし、SDKを設定します。次に、SQSオブジェクトとLambdaオブジェクトを作成し、SQSキューのパラメータを定義し、SQSキューを作成し、最後にLambda関数を作成して有効化します。以下にコードを示します。

// 1. 必要なパッケージをインポート
const AWS = require('aws-sdk');
const uuid = require('uuid');

// 2. SDKの設定
AWS.config.update({ region: 'us-east-1' });

// 3. SQSオブジェクトとLambdaオブジェクトを作成
const sqs = new AWS.SQS();
const lambda = new AWS.Lambda();

// 4. SQSキューのパラメータを定義
let queueParams = {
    QueueName: 'yourQueueName',
    Attributes: {
        'DelaySeconds': '60', // メッセージが受信されるまでの遅延時間:60秒
        'MessageRetentionPeriod': '86400' // メッセージの保持期間:1日
    }
};

// 5. SQSキューを作成
sqs.createQueue(queueParams, function(err, data) {
    if (err) {
        console.log("キューの作成エラー", err);
    } else {
        console.log("キューの作成に成功しました。キューのURLは", data.QueueUrl, "です。");

        // 6. SQSキューとLambda関数のイベントソースを接続
        let lambdaParams = {
            FunctionName: 'yourLambdaFunctionName',
            EventSource: {
                Type: 'sqs',
                UUID: uuid.v4(),
                BatchSize: 1,
                MaximumBatchingWindowInSeconds: 0,
                Enabled: true,
                Queues: [data.QueueUrl]
            }
        };

        lambda.createEventSourceMapping(lambdaParams, function(err, data) {
            if (err) {
                console.log("イベントソースの接続エラー", err);
            } else {
                console.log("イベントソースの接続に成功しました。", data);
            }
        });
    }
});

// 7. Lambda関数内でSQSキューのイベントを処理
exports.yourLambdaFunctionName = async (event, context) => {
    try {
        const message = event.Records[0].body; // イベントからメッセージを取得
        console.log("SQSキューからのメッセージ:", message);

        // メッセージを使用してREST APIを呼び出す例:
        // const response = await axios.post('your_rest_api_endpoint', { message });
        // console.log("REST APIの結果:", response.data);

        return {
            statusCode: 200,
            body: "処理が成功しました。"
        };
    } catch (error) {
        console.log("処理中にエラーが発生しました:",

 error);
        return {
            statusCode: 500,
            body: "処理エラー"
        };
    }
};

ステップ4: コードを実行して結果を楽しみましょう

それでは、私たちが行った作業の結果を楽しむ時がきました!ターミナルを開き、lambda_sqs.js ファイルがあるディレクトリに移動し、次のコマンドを入力してください。

node lambda_sqs.js

以上です。 ここまでで、AWS LambdaとSQSの操作方法について新たな知識を得ることができたと思います。もちろん、これは hello world スタイルの非常にシンプルな例ですが、Lambdaの理解を深めるために一緒に行いました。

ボーナス: AWS CLIを使用して、AWSコンソールにアクセスせずに、SQSキューやLambda関数の存在を確認する方法について説明します。

ターミナルでAWS Command Line Interface (CLI) を使用して、SQSキューやLambda関数の情報を確認および管理することができます。以下は、SQSキューやLambda関数の情報を確認するための基本的なCLIコマンドです。

1. SQSキューリストの確認:

aws sqs list-queues

上記のコマンドは、AWSアカウント内のすべてのSQSキューを一覧表示します。

2. 特定のSQSキューの詳細の取得:

aws sqs get-queue-attributes --queue-url <queue-url> --attribute-names All

<queue-url> を確認したいSQSキューのURLに置き換えてください。上記のコマンドは、キューのすべての属性(DelaySeconds、MessageRetentionPeriodなど)を返します。

3. Lambda関数リストの確認:

aws lambda list-functions

上記のコマンドは、AWSアカウント内のすべてのLambda関数を一覧表示します。

4. 特定のLambda関数の詳細の取得:

aws lambda get-function --function-name <function-name>

<function-name> を確認したいLambda関数の名前に置き換えてください。上記のコマンドは、Lambda関数の詳細情報(設定、ARNなど)を返します。

AWS CLIを使用するには、CLIをインストールし、AWSのログイン情報とアクセス権限を設定する必要があります。また、CLIの使用時には認証情報(アクセスキーとシークレットキー)を提供する必要があります。上記で説明したようにCLIを使用する準備が整っていることを前提としています。

3. メッセージの処理方法:同時処理と順次処理

3.1 同時処理

この場合、キューに新しいメッセージが到着するたびに、AWS Lambdaは自動的にトリガーされ、メッセージを処理します。つまり、複数のメッセージが同時に到着した場合、それらは順番に処理されるのではなく、同時に処理されます。これがLambdaのデフォルトの動作方法です。

let sqsParams = {
  QueueUrl: queueUrl,
  MaxNumberOfMessages: 10, // キューから同時に取得する最大メッセージ数は10
};

sqs.receiveMessage(sqsParams, function(err, data) {
  if (err) {
    console.log("キューからメッセージを受信する際のエラー", err);
  } else {
    // メッセージを処理する
    data.Messages.forEach(function(message) {
      console.log("メッセージを処理しています:", message.Body);
      // メッセージの処理関数はここに記述します
    });
  }
});

3.2 順次処理

同時処理とは対照的に、順次処理では一度に1つのメッセージが処理されます。これにより、各メッセージが丁寧に処理され、"競合"が発生しないことが保証されます。この処理方法では、若干の追加時間がかかるかもしれませんが、各メッセージが正しく処理されることが保証されます。

let sqsParams = {
  QueueUrl: queueUrl,
  MaxNumberOfMessages: 1, // キューから1つだけメッセージを取得する
};

sqs.receiveMessage(sqsParams, function(err, data) {
  if (err) {
    console.log("キューからメッセージを受信する際のエラー", err);
  } else {
    // メッセージを処理する
    console.log("メッセージを処理しています:", data.Messages[0].Body);
    // メッセージの処理関数はここに記述します
  }
});

4. Lambda のインスタンス数と管理方法

4.1. AWS Lambda のインスタンス生成メカニズム

Lambda関数を作成すると、AWS Lambdaは関数を実行するために1つまたは複数の「インスタンス」を作成します。ここでのインスタンスは、AWS Lambdaがコードを実行するために使用する仮想マシン、コンテナ、または他のリソースのことです。各インスタンスは、関数を1回または複数回実行することができます。

4.2. インスタンス数の管理

AWS Lambdaは、インスタンス数をいつ追加するか、いつ減らすかを自動的に決定しますので、心配する必要はありません。AWS Lambdaは、作業負荷に応じてインスタンス数を自動的に調整し、リソースを節約します。

Lambda関数が長時間呼び出されない場合、AWS Lambdaはその関数を実行しているインスタンスが不要であると判断し、自動的に「解放」します。その後、関数が再び呼び出されると、AWS Lambdaは新しいインスタンスを作成します。

作業負荷が急増した場合、AWS Lambdaは追加のインスタンスを作成して、すべてのリクエストが迅速に処理されるようにします。新しいインスタンスを作成する際にわずかな遅延が発生するかもしれませんが、これはインスタンス数を自動的に調整するメリットと比較して受け入れられる遅延です。

Lambdaのインスタンス数を設定できるかどうかについては、直接指定することはできません。AWS Lambdaは、作業負荷に基づいてインスタンス数を完全に管理および決定します。

5. AWS Lambda のスケーリング方法

AWS Lambdaは、アプリケーションの要求に応じて自動的にスケーリングまたは縮小するように設計されています。アプリケーションが要求に応じてリソースを追加する必要がある場合、AWS LambdaはLambda関数のコピー(または「インスタンス」)を自動的に作成します。これらの各コピーは、総リクエストの一部を処理します。

最初に、Lambdaは関数の単一のコピーから開始します。負荷が増加すると、Lambdaは要求に応じてコピーの数を増やします。各コピーは、総リクエストの一部を処理するため、負荷を均等に分散します。

また、この拡張は即座に行われるわけではありません。AWS Lambdaは、将来の作業負荷を予測し、追加するコピーの数を決定するためのアルゴリズムを使用します。

image.png

6. AWS Lambda の利点

  1. 自動的なスケーリング: 先述の通り、Lambdaは要求に応じて自動的にスケーリングまたは縮小するため、アプリケーションは常にユーザー要求に応えることができます。インフラストラクチャの管理について心配する必要はありません。

  2. 使用料金は使用量に基づく: AWS Lambdaでは、コードが実行されている時間だけを支払うため、アイドル時間に対して支払いが発生しません。

  3. 他のAWSサービスとの統合: Lambdaは、Amazon S3、DynamoDB、API Gatewayなど、さまざまなAWSサービスと統合できるため、AWSエコシステムを最大限に活用することができます。

7. AWS Lambda のデメリット

  1. "Cold Start"時間: Lambda関数が非アクティブな期間の後にトリガーされた場合、一定の"クールダウン"時間が発生します。この時間には、関数が応答するまでの追加の時間がかかる場合があります。

  2. リソースの制限: Lambdaにはいくつかのリソース制限があります。たとえば、関数の最大実行時間は15分、パッケージの最大サイズは50MBなどです。

image.png

8. まとめ

以上で、AWS LambdaとAWS SQSの動作と組み合わせについて学びました。AWS LambdaとSQSを組み合わせて使用することで、強力でスケーラブルなアプリケーションを構築することができますが、その制約と課題にも注意する必要があります。この記事の情報がこれらのサービスの使用方法についての理解を深めるのに役立つことを願っています。

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí