Alarme Dynamo Throttle Events – Discord
December 22, 2024

Alarme Dynamo Throttle Events – Discord

This setting monitors certain metrics in DynamoDB tables and sends notifications to the Discord channel when throttling events are detected.




Step One – Lambda Configuration

General sampling:

Running time:

Environment variables:

Resource based – policy statement (important for alerts to be able to trigger lambdas)

Resource based policy configuration: (Establish alarm ARN to trigger lambda)

Required permissions:

Lambda code:

import json
import boto3
import requests
import os
from datetime import datetime, timedelta

# Configurações do Discord Webhook
DISCORD_WEBHOOK_URL = os.environ['DISCORD_WEBHOOK_URL']

# Cliente boto3 para o CloudWatch
cloudwatch = boto3.client('cloudwatch')

def send_discord_notification(message):
    data = {
        "content": message
    }
    response = requests.post(DISCORD_WEBHOOK_URL, json=data)
    if response.status_code != 204:
        raise ValueError(f"Falha ao enviar notificação para o Discord: {response.status_code}, {response.text}")

def lambda_handler(event, context):
#    print("Evento recebido:", json.dumps(event))
    print(event) 
    # Métricas a serem monitoradas
    metrics_to_monitor = [
        'WriteThrottleEvents',
        'ReadThrottleEvents'
    ]

    # Nome da tabela DynamoDB a ser monitorada
    table_name = os.environ['TABLE_NAME']
    print(f"Tabela a ser monitorada: {table_name}")

    for metric_name in metrics_to_monitor:
        print(f"Verificando métrica: {metric_name}")

        response = cloudwatch.get_metric_statistics(
            Namespace='AWS/DynamoDB',
            MetricName=metric_name,
            Dimensions=[
                {
                    'Name': 'TableName',
                    'Value': table_name
                }
            ],
            StartTime=datetime.utcnow() - timedelta(minutes=5),
            EndTime=datetime.utcnow(),
            Period=60,
            Statistics=['Sum']
        )

        print(f"Resposta da CloudWatch: {response}")

        data_points = response.get('Datapoints', [])
        if data_points:
            for point in data_points:
                print(f"Ponto de dados: {point}")
                if point['Sum'] > 0:
                    message = f"Evento de throttle ({metric_name}) detectado na tabela {table_name} com {int(point['Sum'])} eventos."
                    print(f"Enviando mensagem para o Discord: {message}")
                    try:
                        send_discord_notification(message)
                    except Exception as e:
                        print(f"Erro ao enviar notificação para o Discord: {e}")
                    else:
                        print("Notificação enviada com sucesso.")
                else:
                    print(f"Nenhum evento de throttle detectado para {metric_name}.")
        else:
            print(f"Nenhum ponto de dados encontrado para {metric_name}.")

    print("Processo de verificação concluído.")

    return {
        'statusCode': 200,
        'body': json.dumps('Notificações enviadas se algum evento de throttle for detectado.')
    }
Enter full screen mode

Exit full screen mode

Download Lambda code [dynamo-throttle-events.zip]
https://github.com/aldeiacloud/DynamoThrottleEvents/raw/refs/heads/main/ecbb053f-e092-4059-b39d-f8f184166e76.zip


  1. Main function (lambda_handler):

    • Receive events and context when triggered.
    • Define the metrics to monitor: Write throttling events e Read throttling events.
    • Get the name of the DynamoDB table to monitor from an environment variable.
    • For each metric, query CloudWatch for statistics on throttling events over the past 5 minutes.
    • Analyze the returned data points:
      • If there are throttling events (sum greater than 0), please send a notification with details to Discord.
      • Otherwise, it means that no throttling event was detected.
    • End the verification process and return a success status.

Notifications are sent to Discord only when the function detects a throttling event in a monitored metric for the specified DynamoDB table.





Step Two – CloudWatch Alarm Configuration

General sampling:

Table name/statistics/period:

situation:

Operation Lambda:


Once completed, now when an alert triggers a limit on reading or writing to the table configured in the alert and lambda variables, it will send it to the discord literal group.

After enforcing the limit, we are able to receive the event on Discord:

2024-12-22 02:34:50

Leave a Reply

Your email address will not be published. Required fields are marked *