Blog

Case studies, strategies, and ideas shaping modern technology.

Enriched CloudWatch Slow Query Alerting via AWS Lambda

Enriched CloudWatch Slow Query Alerting via AWS Lambda

When a database query runs slowly, knowing that a problem exists is only part of the challenge. Engineers also need enough context to understand what is happening and decide what needs attention.

Mesoform had already implemented monitoring for MongoDB slow queries, but the initial alerts only indicated that a slow query had occurred. To understand what was behind the alert, developers had to switch to the AWS Management Console and manually search CloudWatch logs.

We addressed this by adding an event-driven enrichment layer using Amazon EventBridge and AWS Lambda. The Lambda retrieves the relevant log data, extracts the important query details and sends an enriched alert directly to Slack.

The result is a more useful alert that gives engineers the information they need without requiring a manual log search.


Challenge

The existing monitoring setup used standard AWS CloudWatch components:

  • MongoDB writes slow query information as JSON to stdout.
  • Container Insights forwards the logs to a dedicated CloudWatch Log Group.
  • A CloudWatch Log Metric Filter identifies slow queries and increments the developmentMongoSlowQueries metric.
  • A CloudWatch alarm triggers when the metric exceeds zero within a 5-minute window.

The problem was that CloudWatch alarms based on log metrics are numeric. They can report that a threshold has been exceeded, but they cannot pass the contents of the matching log entry into the notification.

As a result, a Slack alert could tell developers that three slow queries had occurred, but not:

  • Which query was responsible
  • Which database or collection was affected
  • How long the query took
  • What parameters were involved
  • What the query plan looked like

Engineers therefore had to switch to CloudWatch Logs Insights and manually investigate the underlying logs before they could assess the issue.

box

Solution

Rather than replacing the existing CloudWatch alarm, we added an enrichment layer between the alarm and the Slack notification.

 

How it works

1. CloudWatch detects the slow query

When the slow query alarm enters the ALARM state, Amazon EventBridge captures the state change using the aws_cloudwatch_event_rule.mongo_slow_query_alarm_state_change rule.

2. EventBridge triggers Lambda

EventBridge invokes a dedicated Lambda function, mongo_slow_query_alarm_enricher.

3. Lambda retrieves the relevant logs

Because the alarm itself does not contain the original log data, the Lambda calls logs:FilterLogEvents against the MongoDB log group.

It searches a 5-minute lookback window using the same matching pattern as the metric filter to identify the relevant log entries.

4. The query information is extracted

The Lambda parses the log entries, including nested stringified JSON, and extracts the key details:

  • Affected database and collection
  • Query execution time in milliseconds
  • Query plan summary, including index scans and COLLSCAN
  • Command parameters such as filter, skip and limit

5. An enriched alert is sent to Slack

The Lambda creates a custom notification payload using the AWS Chatbot schema and publishes it to an AWS KMS server-side encrypted SNS topic.

AWS Chatbot then delivers the formatted diagnostic alert to Slack.

This allows us to retain the existing CloudWatch monitoring while adding the context that was missing from the original notification.

aws lock

Working Across AWS Accounts and Environments

The solution introduced additional IAM and KMS considerations because it needed to operate across multiple AWS environments.

When encryption keys are involved, the Lambda function requires additional permissions. Any permission issues can be identified by checking the errors reported by the function in CloudTrail or the deployment pipeline.

 

Cross-account KMS permissions

The existing SNS topic was trusted by CloudWatch through the cloudwatch.amazonaws.com service principal. However, the enrichment Lambda operates using an IAM execution role across an account boundary.

Cross-account KMS access therefore required permissions in both:

  • The KMS key resource policy
  • The Lambda execution role's identity-based IAM policy

During implementation, we encountered a series of AccessDenied errors involving permissions such as:

  • kms:GenerateDataKey
  • kms:Decrypt
  • kms:DescribeKey
  • kms:GetKeyRotationStatus
  • kms:ListResourceTags

To identify the required permissions, we traced the relevant terraform-provider-aws source code and checked the AWS API calls made by the resources involved against the active IAM grants. This allowed us to identify the specific permissions required for the Lambda function to operate successfully across accounts.

 

Results

The enriched alerting pipeline turned a simple numeric CloudWatch alarm into a notification containing useful diagnostic context.

 

Less manual investigation

Engineers can see the relevant query information directly in Slack rather than switching to the AWS Console and searching CloudWatch logs.

 

Faster triage

Alerts now include:

  • Affected database and collection
  • Query execution time
  • Query plan information
  • Query command parameters

This provides immediate context for investigating whether a slow query is related to a background operation, an unindexed query or another database issue.

 

Secure multi-account delivery

The pipeline uses SSE-KMS encryption and scoped IAM permissions while supporting all environments without Terraform deployments overwriting permissions belonging to another stage.

Instead of simply reporting that a threshold has been crossed, the alert gives engineers the relevant information to begin investigating immediately.

 

No sensitive information is logged or captured

The solution currently does not include Data Loss Prevention (DLP) controls for environments where query data may contain sensitive information.

Because MongoDB queries use JSON-based query structures, query parameters included in logs or notifications could potentially contain user information such as email addresses or user IDs. The implementation therefore requires appropriate review of the data exposed through query logs before being used in sensitive-data environments.

This should be considered when assessing whether the solution is suitable for environments where sensitive or personally identifiable information may be present.

green lock

 

Conclusion

Standard cloud monitoring tools frequently force a trade-off between simple setup and useful detail. By building a lightweight, event-driven serverless pipeline around CloudWatch, we successfully bypassed native alerting constraints to make critical telemetry available at the point of action.

Data Loss Prevention (DLP) is an area for further consideration, particularly for environments where query data may contain sensitive information. We plan to explore this in a future article, looking at how DLP controls can be introduced to help identify and protect sensitive data within enriched alerts.


Elevate Your Cloud Observability with Mesoform Ltd

Struggling with ambiguous cloud alerts, time-consuming incident investigation, or complex multi-account AWS environments? Mesoform Ltd specialises in DevOps engineering, infrastructure as code (Terraform), and cloud observability solutions.

Whether you need to improve incident response, build secure serverless workflows, or optimise your database monitoring, we can help you build scalable, developer-friendly cloud infrastructure.

Contact Mesoform Ltd Today to modernise your AWS monitoring and give your engineering teams the context they need to respond faster.