By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
(For AWS Solutions Architect – Associate & Real-World Production)
You’re a cloud engineer at a fintech startup. Your team deploys a new payment processing microservice to ECS Fargate. Two days later, the service starts throttling under load, but no one notices—until customers complain. Your CTO asks: "Why didn’t we get an alert?"
CloudWatch is your eyes and ears in AWS. It collects metrics (CPU, latency, errors), stores logs (application, API, system), and triggers alarms (e.g., "CPU > 80% for 5 minutes → send SNS alert"). Without it, you’re flying blind. With it, you can: - Detect issues before users do (e.g., high latency, failed Lambda invocations).- Debug production problems (e.g., "Why did this API call fail at 2:17 AM?").- Optimize costs (e.g., "This EC2 instance is 90% idle—downsize it").- Automate responses (e.g., "If DynamoDB throttles, trigger a Lambda to scale up").
Ignoring CloudWatch is like driving a car without a dashboard. You won’t know you’re running out of gas until the engine sputters.
us-east-1
eu-west-1
CloudWatch Logs Agent
/aws/lambda/my-function
OK
ALARM
INSUFFICIENT_DATA
filter @message like /ERROR/
stopped
CloudWatchFullAccess
EC2FullAccess
aws configure
The agent collects custom metrics (e.g., memory, disk) and logs from your instance.
SSH into your EC2 instance: bash ssh -i "your-key.pem" ec2-user@<EC2_PUBLIC_IP> (Replace ec2-user with ubuntu for Ubuntu instances.)
bash ssh -i "your-key.pem" ec2-user@<EC2_PUBLIC_IP>
ec2-user
ubuntu
Download and install the agent: bash wget https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm sudo rpm -U ./amazon-cloudwatch-agent.rpm
bash wget https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm sudo rpm -U ./amazon-cloudwatch-agent.rpm
Create a config file for the agent: bash sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -s (This downloads a default config. We’ll customize it next.)
bash sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -s
Edit the config file (/opt/aws/amazon-cloudwatch-agent/bin/config.json): json { "metrics": { "metrics_collected": { "mem": { "measurement": ["mem_used_percent"], "metrics_collection_interval": 60 }, "disk": { "measurement": ["used_percent"], "metrics_collection_interval": 60, "resources": ["/"] } } }, "logs": { "logs_collected": { "files": { "collect_list": [ { "file_path": "/var/log/messages", "log_group_name": "ec2-instance-logs", "log_stream_name": "{instance_id}-messages" } ] } } } } (This collects memory/disk metrics and /var/log/messages logs.)
/opt/aws/amazon-cloudwatch-agent/bin/config.json
json { "metrics": { "metrics_collected": { "mem": { "measurement": ["mem_used_percent"], "metrics_collection_interval": 60 }, "disk": { "measurement": ["used_percent"], "metrics_collection_interval": 60, "resources": ["/"] } } }, "logs": { "logs_collected": { "files": { "collect_list": [ { "file_path": "/var/log/messages", "log_group_name": "ec2-instance-logs", "log_stream_name": "{instance_id}-messages" } ] } } } }
/var/log/messages
Start the agent: bash sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a start
bash sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a start
Verify the agent is running: bash sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status (Output should show status: running.)
bash sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status
status: running
mem_used_percent
disk_used_percent
EC2-Monitoring
CPUUtilization
Static
Greater than 80
5 minutes
1
Create new topic
SNS topic name: HighCPUAlert
Email: [email protected]
EC2-High-CPU
Create the alarm.
Test the alarm:
bash sudo yum install -y stress stress --cpu 2 --timeout 300
ec2-instance-logs
Click "Logs Insights" → Run query: sql fields @timestamp, @message | filter @message like /error|fail|warn/i | sort @timestamp desc | limit 20 (This shows the last 20 error/warning messages.)
sql fields @timestamp, @message | filter @message like /error|fail|warn/i | sort @timestamp desc | limit 20
Save the query for future debugging.
EC2-High-CPU-Remediation
Rule with an event pattern
AWS events or EventBridge partner events
Event pattern: json { "source": ["aws.cloudwatch"], "detail-type": ["CloudWatch Alarm State Change"], "resources": ["arn:aws:cloudwatch:us-east-1:123456789012:alarm:EC2-High-CPU"], "detail": { "state": { "value": ["ALARM"] } } } (Replace 123456789012 with your AWS account ID.)
json { "source": ["aws.cloudwatch"], "detail-type": ["CloudWatch Alarm State Change"], "resources": ["arn:aws:cloudwatch:us-east-1:123456789012:alarm:EC2-High-CPU"], "detail": { "state": { "value": ["ALARM"] } } }
123456789012
Select target: Lambda function → Create new function: ```python import boto3
Lambda function
def lambda_handler(event, context): ec2 = boto3.client('ec2') instance_id = event['detail']['trigger']['Dimensions'][0]['value']
# Reboot the instance (or take other actions) ec2.reboot_instances(InstanceIds=[instance_id]) return { 'statusCode': 200, 'body': f'Rebooted instance {instance_id}' }
`` 7. Deploy the Lambda function and attach an IAM role withec2:RebootInstances` permissions.8. Create the rule.
`` 7. Deploy the Lambda function and attach an IAM role with
Now, when CPU > 80%, the alarm triggers → EventBridge invokes Lambda → Lambda reboots the instance.
cloudwatch:PutMetricData
logs:PutLogEvents
bash aws logs put-retention-policy --log-group-name "ec2-instance-logs" --retention-in-days 30
filters
CPUUtilization + MemoryUtilization
Environment=prod
Team=backend
aws cloudwatch set-alarm-state --alarm-name "EC2-High-CPU" --state-value ALARM --state-reason "Testing"
ERROR
FAIL
timeout
throttle
aws cloudwatch get-metric-statistics
aws cloudwatch set-alarm-state
❌ CloudTrail (audit logs), X-Ray (distributed tracing).
"How do you monitor memory usage on an EC2 instance?"
❌ AWS doesn’t collect memory metrics by default.
"You need to trigger a Lambda when an EC2 instance’s CPU > 90%. What’s the most cost-effective way?"
❌ Polling the metric with a Lambda (inefficient).
"How do you retain CloudWatch logs for 1 year for compliance?"
aws logs put-retention-policy
"You need to monitor a Lambda function’s errors and latency. What’s the most cost-effective solution?"- ✅ Enable CloudWatch Lambda Insights (pre-built dashboards for Lambda).- ✅ Create a CloudWatch Alarm for Errors > 0 and Duration > 1s.- ❌ X-Ray (more expensive, better for distributed tracing).
Errors > 0
Duration > 1s
You have a Lambda function that processes orders. You want to: 1. Count how many times it fails (and alert if > 5 failures in 5 minutes).2. Log the error details for debugging.
Write the CloudWatch Alarm and Logs Insights query to achieve this.
Create a CloudWatch Alarm: bash aws cloudwatch put-metric-alarm \ --alarm-name "Lambda-OrderProcessor-Errors" \ --metric-name "Errors" \ --namespace "AWS/Lambda" \ --statistic "Sum" \ --period 300 \ --threshold 5 \ --comparison-operator "GreaterThanThreshold" \ --evaluation-periods 1 \ --alarm-actions "arn:aws:sns:us-east-1:123456789012:LambdaErrorAlerts" \ --dimensions "Name=FunctionName,Value=OrderProcessor" (Replace 123456789012 with your account ID.)
bash aws cloudwatch put-metric-alarm \ --alarm-name "Lambda-OrderProcessor-Errors" \ --metric-name "Errors" \ --namespace "AWS/Lambda" \ --statistic "Sum" \ --period 300 \ --threshold 5 \ --comparison-operator "GreaterThanThreshold" \ --evaluation-periods 1 \ --alarm-actions "arn:aws:sns:us-east-1:123456789012:LambdaErrorAlerts" \ --dimensions "Name=FunctionName,Value=OrderProcessor"
Logs Insights Query (to debug errors): sql fields @timestamp, @message, @logStream | filter @message like /ERROR|Task timed out|Unhandled exception/i | sort @timestamp desc | limit 50
sql fields @timestamp, @message, @logStream | filter @message like /ERROR|Task timed out|Unhandled exception/i | sort @timestamp desc | limit 50
Why it works:- The alarm triggers if the Lambda’s Errors metric exceeds 5 in 5 minutes.- The Logs Insights query filters for error messages in the Lambda logs.
Errors
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.