Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

Posted on Oct 11, 2023

Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

RabbitMQ is a popular message broker that can send and receive messages between different systems. One use case for RabbitMQ is as an event source for AWS Lambda, allowing Lambda functions to be triggered by letters sent to RabbitMQ queues.

This article will examine how to use Terraform to configure RabbitMQ as an event source for Lambda and view metrics on CloudWatch. We are using TotalReady, and Unacked metrics of RabbitMQ as custom metrics.

RabbitMQ also provides metrics that can be used to monitor the system’s health. The metrics we are looking into:

      1. Ready Metric indicates the number of messages that are currently ready to be consumed by consumers.

      1. Total The Metric indicates the total number of messages in the queue.

      1. Unacked The metric shows the number of messages that have been delivered to a consumer but has not been acknowledged yet.

    By using these metrics in CloudWatch, developers can monitor the health of the RabbitMQ queue and automatically scale the system up or down as needed.

    Read more about How to host a static website on AWS S3?

    For example, if the Ready metric starts to grow, it may indicate insufficient consumers to handle the load. In this case, an auto-scaling policy can be triggered to add more instances of the consumer component to handle the additional load.

    Prerequisite:

        1. AWS account with access to the required AWS services.

        1. You already have Terraform installed on your system.

        1. You already have your RabbitMQ server and queue endpoints.

      The endpoints of the queue will be like this: https://ihflktln:***@shark.rmq.cloudamqp.com/api/queues/ihflktln


      When a developer configures RabbitMQ as an event source for Lambda, it creates a trigger that monitors a specific message queue. When a message arrives on that queue, Lambda executes the code associated with the trigger automatically.

      So, we will ingest TotalReady, and Unacked metrics to the CloudWatch on QueueMetrics Namespace using a lambda function. Furthermore, the lambda function is as follows:

      import requests
      import boto3
      import os
      
      def put_metrics_to_cloudwatch(total, ready, unacked):
          client = boto3.client('cloudwatch')
          client.put_metric_data(
              Namespace='QueueMetrics',
              MetricData=[
                  {
                      'MetricName': 'TotalMessages',
                      'Value': total,
                      'Unit': 'Count'
                  },
                  {
                      'MetricName': 'ReadyMessages',
                      'Value': ready,
                      'Unit': 'Count'
                  },
                  {
                      'MetricName': 'UnackedMessages',
                      'Value': unacked,
                      'Unit': 'Count'
                  }
              ]
          )  
      def lambda_handler(event, context):
          endpoint = os.environ['RABBITMQ_ENDPOINT']
          response = requests.get(endpoint)
          data = response.json()
          print(data)
          total = data[0]['messages']
          ready = data[0]['messages_ready']
          unacked = data[0]['messages_unacknowledged']
          print("Total messages:", total)
          print("Ready messages:", ready)
          print("Unacked messages:", unacked)
          put_metrics_to_cloudwatch(total, ready, unacked)
          return {'total':total, 'ready':ready, 'unacked':unacked}

      Terraform to Create and Manage Resources

      Once we have our Lambda function and RabbitMQ queue set up, we can use Terraform. To create and manage the resources. The Terraform configuration file will look something like this:

      #lambda.tf
      locals {
        function_name = var.lambda_function_name != null ? var.lambda_function_name : "RabbitMQ-${var.env}-lamd-metric-ingestor"
        lambda_tags = {
          Name = local.function_name
          Env  = var.env
        }
      }
      module "lambda_function" {
        source        = "terraform-aws-modules/lambda/aws"
        version       = "3.2.0"
        function_name = local.function_name
        description   = local.function_name
        handler       = "index.lambda_handler"
        runtime       = "python3.8"
        attach_policy_json = true
        policy_json = <<EOF
      {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "logs:CreateLogGroup",
              "logs:CreateLogStream",
              "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
          },
          {
            "Effect": "Allow",
            "Action": [
              "cloudwatch:PutMetricData",
              "events:PutTargets"
            ],
            "Resource": "*"
          }
        ]
      }
      EOF
        source_path = [
          {
            path             = "./src",
            pip_requirements = true
          }
        ]
        timeout = 60
        publish = true
        tags    = merge(local.lambda_tags, var.tags)
      
        environment_variables = {
          RABBITMQ_ENDPOINT = var.rabbitmq_endpoint
        }
      }
      resource "aws_cloudwatch_event_rule" "lambda_function" {
        name        = local.function_name
        description = "Sparrow cron rule fires every minute"
        schedule_expression = "cron(*/1 * * * ? *)"
      }
      
      resource "aws_cloudwatch_event_target" "lambda_function" {
        rule = aws_cloudwatch_event_rule.lambda_function.name
        target_id = "lambda_function"
        arn = module.lambda_function.lambda_function_arn
      }
      resource "aws_lambda_permission" "allow_cw_to_call_lambda_function" {
        statement_id = "AllowExecutionFromCloudWatch"
        action = "lambda:InvokeFunction"
        function_name = module.lambda_function.lambda_function_name
        principal = "events.amazonaws.com"
        source_arn = aws_cloudwatch_event_rule.lambda_function.arn
      }

      And we have another file called vars.tf, which is used to declare variables in Terraform. These variables pass values into the configuration and provide dynamic values to the resources being created, as shown below.

      #vars.tf
      variable "env" {
        type        = string
        description = "Env to create resources on"
        default     = "dev"
      }
      variable "tags" {
        type        = map(string)
        description = "Tags"
        default     = {}
      }
      variable "lambda_function_name" {
        type        = string
        description = "(optional) Lambda function name"
        default     = null
      }
      variable "rabbitmq_endpoint" {
        type        = string
        description = "RabbitMQ endpoints"
        default = "https://ihflktln:***@shark.rmq.cloudamqp.com/api/queues/ihflktln"
      }

      The provider.tf the File is used to configure the providers that Terraform will use to interact with external services, as shown below:

      provider "aws" {
        region = "ap-southeast-1"
        access_key = "your_access_key"
        secret_key = "your_secret_key"
      }

      Then, we added a scheduled CloudWatch event rule that triggers this Lambda every 1 minute, which is set up like in the above Lambda.tf File:

      resource "aws_cloudwatch_event_rule" "lambda_function" {
        name        = local.function_name
        description = "Sparrow cron rule fires every minute"
        schedule_expression = "cron(*/1 * * * ? *)"
      }

      Once all of the Terraform configuration files are created, we can use Terraform command to provision the resources. This can be done by running the terraform apply Command In the command line. Once terraform provisions your infrastructure, you can see on the console you will have your lambda function.

      Screenshot of Lambda Function Created by terraform

       

      Fig: Lambda Function Created by terraform

      And also your RabbitMQ matrices TotalReady, and unacked are ingested by the lambda function.

      Screenshot of AWS CloudWatch, where we can see the ingested metrics by Lambda function on QueueMetrics namespace.

       

      Fig: AWS CloudWatch, where we can see the ingested metrics by Lambda function on QueueMetrics namespace.

      Screenshot of CloudWatch Custom metrics from our RabbitMQ

       

      Fig: CloudWatch Custom metrics from our RabbitMQ

      Congratulations!!! You were successful in ingesting all required RabbitMQ metrics into Cloudwatch.

      Overall, by configuring RabbitMQ as an event source for Lambda and using metrics in CloudWatch to monitor the health of the queue, developers can create a robust and scalable distributed system that can handle various events and messages.

      Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda
      Tej pandey

      Latest Blogs

      New AWS Announcement for October 2023

      New AWS Announcement for October 2023


      New AWS Announcement for October 2023

      Adex International

      Nov 08, 2023

      Sustainability in the AWS Well-Architected Framework: A Comprehensive Guide

      Sustainability in the AWS Well-Architected Framework: A Comprehensive Guide


      Sustainability in the AWS Well-Architected Framework: A Comprehensive Guide

      Adex International

      Oct 19, 2023

      AWS New Announcement Sept 2023

      AWS New Announcement Sept 2023


      AWS New Announcement Sept 2023

      Adex International

      Oct 17, 2023

      Migrate Gitlab PostgreSQL Database to Custom Location Using Ansible

      Migrate Gitlab PostgreSQL Database to Custom Location Using Ansible


      Migrate Gitlab PostgreSQL Database to Custom Location Using Ansible

      Saugat Tiwari

      Oct 11, 2023

      Mastering DevOps: Your Ultimate Guide to DevOps Managed Services

      Mastering DevOps: Your Ultimate Guide to DevOps Managed Services


      Mastering DevOps: Your Ultimate Guide to DevOps Managed Services

      Biswash Giri

      Oct 11, 2023

      Discover the Benefits of Security as a Service (SECaaS) for your Business

      Discover the Benefits of Security as a Service (SECaaS) for your Business


      Discover the Benefits of Security as a Service (SECaaS) for your Business

      Saugat Tiwari

      Oct 11, 2023

      Port Forwarding Using AWS System Manager Session Manager

      Port Forwarding Using AWS System Manager Session Manager


      Port Forwarding Using AWS System Manager Session Manager

      Saugat Tiwari

      Oct 11, 2023

      Maximizing Directory Services with LDAP: Creating OUs, Groups, and Users for Improved Authentication and Access Control

      Maximizing Directory Services with LDAP: Creating OUs, Groups, and Users for Improved Authentication and Access Control


      Maximizing Directory Services with LDAP: Creating OUs, Groups, and Users for Improved Authentication and Access Control

      Biswash Giri

      Oct 11, 2023

      AWS Migration Tools: A Comprehensive Guide

      AWS Migration Tools: A Comprehensive Guide

      IntroductionAWS migration tools are a comprehensive set of services and utilities provided by Amazon...


      AWS Migration Tools: A Comprehensive Guide

      Binaya Puri

      Oct 11, 2023

      Difference Between AWS Cloudwatch and Cloudtrail

      Difference Between AWS Cloudwatch and Cloudtrail

      AWS CloudWatch and AWS CloudTrails are sometimes difficult to distinguish. This article seeks to d...


      Difference Between AWS Cloudwatch and Cloudtrail

      Sabin Joshi

      Oct 11, 2023

      New AWS Announcements for June 2023 - Adex

      New AWS Announcements for June 2023 - Adex


      New AWS Announcements for June 2023 - Adex

      Ravi Gupta

      Oct 11, 2023

      Top 7 Applications Of Cloud Computing In Various Field

      Top 7 Applications Of Cloud Computing In Various Field


      Top 7 Applications Of Cloud Computing In Various Field

      Susmita Karki Chhetri

      Oct 11, 2023

      Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

      Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda


      Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

      Tej pandey

      Oct 11, 2023

      7 Types of Security in Cloud Computing?

      7 Types of Security in Cloud Computing?


      7 Types of Security in Cloud Computing?

      Mukesh Awasthi

      Oct 11, 2023

      Cost-effective Use cases & Benefits of Amazon S3

      Cost-effective Use cases & Benefits of Amazon S3


      Cost-effective Use cases & Benefits of Amazon S3

      Nischal Gautam

      Oct 11, 2023

      IT Outsourcing: Everything You Need To Know

      IT Outsourcing: Everything You Need To Know

      The world has changed, and as technology advances, so does the world of work. Gone are the day...


      IT Outsourcing: Everything You Need To Know

      Roshan Raman Giri

      Oct 11, 2023

      Getting Started with Amazon Redshift in 6 Simple Steps

      Getting Started with Amazon Redshift in 6 Simple Steps


      Getting Started with Amazon Redshift in 6 Simple Steps

      Tej pandey

      Oct 11, 2023

      How to Host Static Websites on AWS S3?

      How to Host Static Websites on AWS S3?

      How to Host Static Websites on AWS S3? Hosting a Static Website on AWS S3 has a lot of benefits....


      How to Host Static Websites on AWS S3?

      Ravi Gupta

      Oct 11, 2023

      The Importance of Managed Cloud Security for Businesses

      The Importance of Managed Cloud Security for Businesses


      The Importance of Managed Cloud Security for Businesses

      Roshan Raman Giri

      Oct 11, 2023

      How To Use Amazon S3 For Personal Backup?

      How To Use Amazon S3 For Personal Backup?


      How To Use Amazon S3 For Personal Backup?

      Tej pandey

      Oct 11, 2023

      Major AWS Updates &Announcements of 2023 - March

      Major AWS Updates &Announcements of 2023 - March


      Major AWS Updates &Announcements of 2023 - March

      Roshan Raman Giri

      Oct 11, 2023

      How To Insert Data Into a DynamoDB Table with Boto3

      How To Insert Data Into a DynamoDB Table with Boto3

      DynamoDB is used for many use cases, including web and mobile applications, gaming, ad tech,...


      How To Insert Data Into a DynamoDB Table with Boto3

      Binaya Puri

      Oct 11, 2023

      How to Install and Upgrade the AWS CDK CLI

      How to Install and Upgrade the AWS CDK CLI


      How to Install and Upgrade the AWS CDK CLI

      Nischal Gautam

      Oct 11, 2023

      Ultimate Guide on Creating Terraform Modules

      Ultimate Guide on Creating Terraform Modules


      Ultimate Guide on Creating Terraform Modules

      Tej pandey

      Oct 11, 2023

      What is serverless computing?

      What is serverless computing?


      What is serverless computing?

      Tej pandey

      Oct 11, 2023

      AWS Well-Architected Framework Security Pillar

      AWS Well-Architected Framework Security Pillar

      The Amazon Well-Architected Framework is a set of recommendations and practice guidelines for develo...


      AWS Well-Architected Framework Security Pillar

      Binaya Puri

      Oct 11, 2023

      Amazon FSx for Lustre, Windows, and NetApp ONTAP

      Amazon FSx for Lustre, Windows, and NetApp ONTAP

      Amazon FSx for Lustre, Windows, and NetApp ONTAPAmazon FSx is known for its fully managed, hig...


      Amazon FSx for Lustre, Windows, and NetApp ONTAP

      Ravi Gupta

      Oct 11, 2023

      How to Choose the Right Cloud Service Provider?

      How to Choose the Right Cloud Service Provider?


      How to Choose the Right Cloud Service Provider?

      Tej pandey

      Oct 11, 2023

      25 New AWS Services Updates from AWS Re:Invent 2022

      25 New AWS Services Updates from AWS Re:Invent 2022


      25 New AWS Services Updates from AWS Re:Invent 2022

      Susmita Karki Chhetri

      Oct 11, 2023

      AWS Managed Hosting Services And Dedicated Hosting Benefits

      AWS Managed Hosting Services And Dedicated Hosting Benefits


      AWS Managed Hosting Services And Dedicated Hosting Benefits

      Tej pandey

      Oct 11, 2023

      What is Serverless Security? Risk & Best Practices

      What is Serverless Security? Risk & Best Practices

      Serverless computing  is a rising topic right now in the cloud tech industry. As per a Datad...


      What is Serverless Security? Risk & Best Practices

      Anup Giri

      Oct 11, 2023

      Difference Between Cloud Computing and Cybersecurity

      Difference Between Cloud Computing and Cybersecurity


      Difference Between Cloud Computing and Cybersecurity

      Mukesh Awasthi

      Oct 11, 2023

      DevOps for Developers: How It Helps Streamline the Development Process

      DevOps for Developers: How It Helps Streamline the Development Process

      As per a survey done by Puppet, firms with DevOps practice have increased recovery speeds by 24 ti...


      DevOps for Developers: How It Helps Streamline the Development Process

      Roshan Raman Giri

      Oct 11, 2023

      New AWS Announcements for August 2023

      New AWS Announcements for August 2023


      New AWS Announcements for August 2023

      Rohan Jha

      Oct 11, 2023

      The FinOps Chronicles

      The FinOps Chronicles


      The FinOps Chronicles

      Anup Giri

      Oct 11, 2023

      AWS Auto scale Instance-Based on RabbitMQ Custom Metrics

      AWS Auto scale Instance-Based on RabbitMQ Custom Metrics


      AWS Auto scale Instance-Based on RabbitMQ Custom Metrics

      Anup Giri

      Oct 11, 2023

      Overcome Merge Hell with Trunk based development and Continuous Integration

      Overcome Merge Hell with Trunk based development and Continuous Integration


      Overcome Merge Hell with Trunk based development and Continuous Integration

      Rohan Jha

      Oct 11, 2023

      What's the difference between CapEX Vs OpEX in Cloud Computing?

      What's the difference between CapEX Vs OpEX in Cloud Computing?


      What's the difference between CapEX Vs OpEX in Cloud Computing?

      Tej pandey

      Oct 11, 2023

      How Does Your Organization Keep Cloud Costs Under Control?

      How Does Your Organization Keep Cloud Costs Under Control?


      How Does Your Organization Keep Cloud Costs Under Control?

      Susmita Karki Chhetri

      Oct 11, 2023

      Microsoft Azure vs AWS vs Google Cloud Comparison

      Microsoft Azure vs AWS vs Google Cloud Comparison


      Microsoft Azure vs AWS vs Google Cloud Comparison

      Mukesh Awasthi

      Oct 11, 2023

      What are the Benefits of Amazon S3 Glacier?

      What are the Benefits of Amazon S3 Glacier?


      What are the Benefits of Amazon S3 Glacier?

      Anup Giri

      Oct 11, 2023

      Leverage Azure Migrate to Discover and Assess Your AWS Instances for Smooth Migration to Azure

      Leverage Azure Migrate to Discover and Assess Your AWS Instances for Smooth Migration to Azure


      Leverage Azure Migrate to Discover and Assess Your AWS Instances for Smooth Migration to Azure

      Rohan Jha

      Oct 11, 2023