Intermediate · Serverless, monitoring and cost control · topic 21 of 50 · 30 min
Monitoring with CloudWatch, CloudTrail and Config
Explanation
Why monitoring matters
Your users will find problems before you do unless you watch your systems. Observability means being able to answer "what is happening inside right now, and why?" from the data your system gives out. That data comes in three main kinds: metrics (numbers over time, like CPU percent), logs (text records of events, like an error message) and traces (the path of one request through many services).
CloudWatch metrics
A metric is a series of numbered datapoints over time. Each metric lives in a namespace, a group name such as AWS/EC2, AWS/Lambda or your own FoodApp. Dimensions are name and value pairs that say which resource the number belongs to, for example InstanceId=i-0abc or FunctionName=hello-api. A statistic summarises the datapoints in each period: Average, Sum, Minimum, Maximum, SampleCount, or a percentile such as p99.
EC2 sends basic metrics every 5 minutes for free (standard monitoring). Detailed monitoring sends them every 1 minute for an extra charge. Note that EC2 does not report memory use or disk space used by default, because AWS cannot see inside your operating system. Install the CloudWatch agent to send those.
Custom metrics are numbers you send yourself, such as orders placed per minute. Standard resolution is 1 minute; high-resolution metrics can go down to 1 second. Each custom metric has a monthly cost, so check the pricing page before sending hundreds of them.
aws cloudwatch put-metric-data --namespace FoodApp \
--metric-name OrdersPlaced --unit Count --value 1 \
--dimensions City=PuneCloudWatch Logs
Logs are organised into log groups (usually one per application or function, like /aws/lambda/hello-api). Inside a group, each source writes to its own log stream, and each line is a log event. By default a log group keeps data forever, which slowly grows your bill. Set a retention period, such as 30 days for dev and 1 year for production, or whatever your rules require.
CloudWatch Logs Insights lets you search and count log lines with a small query language. The first query finds the latest errors; the second uses the REPORT lines Lambda writes after each run to show duration and memory per 5 minutes.
fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 20
filter @type = "REPORT"
| stats avg(@duration), max(@duration), max(@maxMemoryUsed / 1000 / 1000) as maxMemoryMB by bin(5m)Alarms
An alarm watches one metric (or a math expression) and is in one of three states: OK, ALARM or INSUFFICIENT_DATA. You set the statistic, the period (how long each datapoint covers), the threshold, and the comparison, such as GreaterThanThreshold.
Evaluation periods (N) is how many recent periods the alarm looks at. Datapoints to alarm (M) is how many of those must breach the threshold. "2 out of 3" ignores a single spike but still catches a real problem. Worked example: period 5 minutes, threshold 80% CPU, M = 2, N = 3. Recent datapoints 85, 70, 90: two breach, so the alarm goes to ALARM. With 85, 70, 60 only one breaches, so it stays OK.
You also choose how to treat missing data: as missing, as not breaching, as breaching, or ignore it. When the state changes, the alarm can notify an SNS topic (email, SMS, chat), run an Auto Scaling policy, or stop, reboot or recover an EC2 instance.
aws cloudwatch put-metric-alarm --alarm-name web-high-cpu \
--namespace AWS/EC2 --metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-0abc1234def567890 \
--statistic Average --period 300 \
--evaluation-periods 3 --datapoints-to-alarm 2 \
--threshold 80 --comparison-operator GreaterThanThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:ap-south-1:111122223333:ops-alertsDashboards
A CloudWatch dashboard puts graphs, numbers and alarm states on one screen. Build one per service with the few numbers that matter: requests, errors, latency (p99) and saturation such as CPU or queue length. Keep it simple enough that a tired engineer understands it at 2 am.
CloudTrail, CloudWatch and Config: who, what and how
| Service | Answers | Example |
|---|---|---|
| CloudWatch | How is it performing right now? Is something broken? | CPU is 95%; error count jumped; alarm fired |
| CloudTrail | Who did what, when, from where? (API audit trail) | User asha deleted bucket invoices-2025 at 14:02 from IP 203.0.113.9 |
| AWS Config | How was this resource configured over time? Is it compliant? | This security group allowed port 22 from anywhere between Monday and Wednesday |
CloudTrail keeps 90 days of management events in its event history at no charge. To keep them longer, or to record data events such as S3 object reads, create a trail that delivers to an S3 bucket (extra charges apply). AWS Config uses rules, such as one that flags public S3 buckets, to check resources against your standards.
X-Ray: tracing requests
AWS X-Ray follows one request through API Gateway, Lambda, DynamoDB and other services, and shows a map of where the time went. AWS now recommends instrumenting new code with OpenTelemetry (the AWS Distro for OpenTelemetry); check the current docs before you start.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Monitoring with CloudWatch, CloudTrail and Config · 1/7
This lesson covers watching your systems on AWS: metrics, logs, alarms and audit trails.
Prefer a video by a teacher? Find free videos on “aws cloudwatch alarms logs insights cloudtrail tutorial” on YouTube ↗
In real life: Hospital appointment booking in Hyderabad
A hospital group runs appointment booking on API Gateway and Lambda. One Monday morning an alarm on 5xx errors ("3 out of 5 one-minute periods above 2%") posts to the team's chat through SNS. A Logs Insights query filtered on ERROR shows timeouts calling the SMS provider. The team raises the function timeout and adds a queue so SMS sending retries in the background. Later that week a new security group rule appears; CloudTrail shows which IAM user added it and from which IP, and AWS Config shows the exact rule before and after.
fields @timestamp, @message
| filter @message like /Timeout/
| stats count() as timeouts by bin(1m)Practice (0/3 done)
Someone deleted an S3 bucket last night. Which service tells you which IAM user did it?
Write evaluate_alarm(datapoints, threshold, m, n, comparison="GreaterThanThreshold"). Look only at the last n datapoints. Count how many breach the threshold using the comparison, which is one of "GreaterThanThreshold", "GreaterThanOrEqualToThreshold", "LessThanThreshold" or "LessThanOrEqualToThreshold". A None datapoint is missing data and counts as not breaching. Return "ALARM" if at least m breach, otherwise "OK".
In your own AWS account (stay in the free tier), set up basic monitoring for a Lambda function or a t-series EC2 instance: an SNS topic with your email, an alarm, a log retention setting and a small dashboard. Then trigger the alarm on purpose and write down what happened.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Cost control in practiceServerless, monitoring and cost control · same module
- Logging, threat detection and incident responseCloud security and compliance
- Monitoring and observability: metrics, logs and tracesDevOps: Git, Docker, Kubernetes and CI/CD · Monitoring and logging
- Portfolio projects that get interviewsCertifications and cloud careers
- Logging and monitoringBackend Development · Performance and reliability
- Logging and monitoring in the cloudCyber Security: from zero to SOC analyst · Cloud security basics
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Your EC2 dashboard shows CPU but no memory use. Why?
Answer: EC2 cannot see inside the OS; install the CloudWatch agent
The hypervisor sees CPU, network and disk I/O, but not memory used inside the OS. The CloudWatch agent sends it as a custom metric.
An alarm has period 60 s, 5 evaluation periods and 3 datapoints to alarm. What does it need to fire?
Answer: 3 of the last 5 one-minute datapoints breaching
M out of N: 3 of the last 5 periods must breach, not necessarily in a row.
What is the default retention of a new CloudWatch Logs log group?
Answer: Never expire
Logs are kept forever unless you set a retention period, which is why forgotten log groups slowly grow the bill.
An auditor asks how a security group was configured last Tuesday. Which service answers best?
Answer: AWS Config
AWS Config records the configuration history of resources and can check them against rules.
In CloudWatch, what is a dimension?
Answer: A name and value pair that identifies which resource a metric belongs to
For example InstanceId=i-0abc tells CloudWatch which instance a CPUUtilization datapoint is for.
Which AWS service blocks an IP address that sends 2,000 login requests in five minutes?Related
Answer: AWS WAF with a rate-based rule
A WAF rate-based rule counts requests per IP and blocks those over the limit.
Your app looks healthy from its own metrics, but users cannot reach it because the TLS certificate expired. What would have caught this?Related
Answer: A black-box synthetic check from outside
Black-box checks test the service the way a user does, so they see certificate and DNS problems.
Which Route 53 record lets your domain point straight at a CloudFront distribution?Related
Answer: An alias record
An alias record maps the name to an AWS resource such as CloudFront; MX is for mail, TXT for text values and PTR for reverse lookups.
Which signal shows the path of ONE request through several services with timings?Related
Answer: A trace
A trace follows one request across services and shows how long each step took.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Serverless, monitoring and cost control” before its exam: Cost control in practice.
- Module 5 exam: Serverless, monitoring and cost control · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Microsoft Azure essentials. 50 topics left in the course before the final exam.
← Previous: Event-driven design: API Gateway, SQS, SNS, EventBridge and Step Functions