- Newest
- Most votes
- Most comments
CPU spikes causing 504 errors with no alerting is a common gap. To answer all three of your questions:
- Configure a CloudWatch Alarm for CPU > 80% for 5 Minutes
You can create a metric alarm that watches CPUUtilization and sends an SNS notification when the threshold is breached. The alarm changes to the ALARM state when the average CPU use of an EC2 instance exceeds a specified threshold for consecutive specified periods
CLI command to create alarm:
aws cloudwatch put-metric-alarm \
--alarm-name "High-CPU-504-Prevention" \
--alarm-description "Alarm when CPU exceeds 80% for 5 minutes" \
--metric-name CPUUtilization \
--namespace AWS/EC2 \
--statistic Average \
--period 300 \
--threshold 80 \
--comparison-operator GreaterThanThreshold \
--dimensions "Name=InstanceId,Value=i-YOUR-INSTANCE-ID" \
--evaluation-periods 1 \
--datapoints-to-alarm 1 \
--alarm-actions arn:aws:sns:us-east-1:111122223333:YourAlertTopic \
--unit Percent
This would evaluate the average CPU over a single 300-second (5-minute) period, I would suggest setting EC2 CPU thresholds around 80–85% to avoid impacting performance.
Since your 504s originate at the ALB, consider creating a companion alarm on HTTPCode_ELB_5XX_Count and TargetResponseTime to catch the downstream impact directly. This composite alarm would reduce noise, so it goes into ALARM state only when all conditions of the rule are met.
- Identify Which Process Is Causing CPU Spikes
Standard EC2 metrics only give you aggregate CPU utilization. To get process-level visibility, you need the CloudWatch Agent with procstat plugin, which provides system-level metrics on top of the standard EC2 namespace metrics for use cases like detecting CPU performance issues and resource constraints
Additionally, consider CloudWatch Anomaly Detection, which uses machine learning to automatically set baselines and detect anomalies in your telemetry data. You can create an anomaly detection alarm that triggers when CPU utilization is higher than the normal usage band for a sustained period. This is especially useful for catching unusual spikes that a static threshold might miss.
- Automate Recovery and Scale-Out
EC2 Auto Scaling: Configure dynamic scaling policies that track CPUUtilization. The autoscaler acts like a thermostat, adding or removing resources to maintain a target value (for example, 70% CPU utilization) . This directly prevents 504s by distributing load across more instances before CPU maxes out.
Alarm-triggered EC2 actions: CloudWatch alarms can directly perform EC2 actions or Auto Scaling actions when triggered For example, you can configure an alarm action that triggers a Lambda function to restart a service or add capacity.
SNS-Lambda remediation: Set your alarm to publish to an SNS topic, then subscribe a Lambda function that performs custom remediation actions [8]. This could restart your application process, flush caches, or trigger a deployment rollback.
CPU > 80% for 5 min -> SNS notification + Auto Scaling scale-out CPU > 95% for 5 min -> SNS escalation + Lambda service restart ALB 5XX count spike -> Composite alarm with CPU -> incident creation
Related artifacts:
- https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/example_cloudwatch_PutMetricAlarm_section.html
- https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Best_Practice_Recommended_Alarms_AWS_Services.html
- https://docs.aws.amazon.com/IDR/latest/userguide/idr-alarms-fit-purpose.html
- https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Alarms.html
- https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Solution-EC2-Health.html
- https://community.aws/content/2drYGJqKaIugpDkMRNLL614wWmM/max-uptime-cloudwatch-anomaly-detection
To properly configure CloudWatch alarms for high CPU usage and prevent 504 Gateway Timeout errors, here's what you need to know:
1. Configuring CPU Usage Alarms
You can create a CloudWatch alarm to monitor CPU utilization using either the AWS Management Console or AWS CLI:
Using the Console:
- Open the CloudWatch console and navigate to Alarms
- Click "Create alarm" and select the EC2 CPUUtilization metric
- Choose your instance and set the statistic to "Average"
- Set your threshold to 80% (or adjust based on your workload characteristics)
- For a 5-minute detection window, set the period to 300 seconds with 1 evaluation period, or use 60-second periods with 5 evaluation periods for more granular monitoring
- Configure an SNS topic to receive notifications
- Complete the alarm creation with a descriptive name
Using the CLI:
You can use the put-metric-alarm command. For example, to monitor multiple instances with specific tags, you could use a Metrics Insights query that triggers when CPU exceeds 80%.
Best Practice Thresholds: While 80% is a commonly recommended threshold, you should analyze your historical CPU utilization data to determine what's acceptable for your specific system. Some applications normally run at high CPU utilization without issues, while others may experience performance degradation. The key is setting the threshold based on when your application's performance actually degrades.
2. Identifying CPU Spike Causes
While CloudWatch can alert you to high CPU usage, identifying the specific process requires additional monitoring at the OS level. The CloudWatch agent can collect process-level metrics if configured to do so. You'll need to review your CloudWatch agent configuration to ensure it's collecting detailed process metrics, not just aggregate CPU statistics.
3. Automating Recovery
CloudWatch alarms can trigger automated actions beyond just notifications. You can configure alarms to trigger Auto Scaling policies, which would automatically scale out your EC2 instances when CPU thresholds are breached. This is particularly effective for handling sudden traffic spikes that cause CPU increases.
For your specific scenario with 504 errors behind a Load Balancer, consider also monitoring your Load Balancer's target response time and unhealthy host count metrics, as these can provide early warning signs before 504 errors occur.
Sources
Recommended alarms - Amazon CloudWatch
Create a CPU usage alarm - Amazon CloudWatch
Creating a Metrics Insights CloudWatch alarm - Amazon CloudWatch
Relevant content
asked 5 months ago
asked a year ago
