โ๏ธ Amazon CloudWatch
The central monitoring and observability service for AWS. CloudWatch collects metrics, stores logs, creates dashboards, fires alarms, and helps you visualize and understand everything happening in your AWS account.
๐ Covers: Metrics ยท Logs ยท Logs Insights ยท Dashboards ยท Alarms ยท EMF ยท Synthetics ยท ServiceLensWhat is Amazon CloudWatch? โ The Big Picture
Imagine you have a car. You have a dashboard showing speed, fuel level, engine temperature, and warning lights. Amazon CloudWatch is that dashboard for your AWS applications.
When you run apps on AWS (Lambda, EC2, API Gateway, RDS, etc.), those services automatically send data to CloudWatch. You can also send your own custom data. CloudWatch stores it, lets you visualize it, and alerts you when something goes wrong.
CloudWatch Metrics โ Numbers Over Time
A metric is a number that changes over time. It's the most basic unit of monitoring. Examples:
- Lambda error count over the last hour: 15 errors
- EC2 CPU utilization: 73%
- API Gateway request latency: 230ms average
- RDS database connections: 150 active connections
AWS services automatically publish metrics to CloudWatch. You never have to do anything โ they just appear.
๐๏ธ Key Metric Concepts You MUST Know
AWS/Lambda, AWS/EC2, AWS/ApiGateway, AWS/RDS. Your custom metrics go in a namespace you name, like MyApp/OrderService. Namespaces keep metrics organized and prevent naming collisions.FunctionName=my-order-function. This lets you view metrics for one specific Lambda function instead of all Lambda functions. Without dimensions, you'd only see aggregate data for the entire service.StorageResolution: 1 parameter).๐ Metric Retention โ How Long Does CloudWatch Keep Data?
| Resolution | Retention Period | Example Use |
|---|---|---|
| 1-second (High Resolution) | 3 hours | Very short-lived detailed view |
| 1-minute (Standard) | 15 days | Day-to-day monitoring |
| 5-minute | 63 days | Month-long trend analysis |
| 1-hour | 15 months | Long-term capacity planning |
After a period passes, CloudWatch automatically rolls up data to lower resolution. Your 1-minute data from 20 days ago is summarized into 5-minute data.
โ๏ธ Custom Metrics โ Sending Your Own Data
AWS services send their metrics automatically. But your application code doesn't โ you need to send custom metrics yourself. This is how you track business KPIs (Key Performance Indicators) like "orders placed per minute" or "payment failures".
Three Ways to Send Custom Metrics:
1. AWS SDK โ PutMetricData
Call the CloudWatch API directly from your code. Works anywhere (Lambda, EC2, on-prem). Simple but requires an extra API call during execution.
2. Unified CloudWatch Agent
Install an agent on EC2 or on-prem servers. Automatically collects system-level metrics (memory, disk, process count) that AWS doesn't collect by default.
3. Embedded Metric Format (EMF)
Write structured JSON logs โ CloudWatch automatically extracts metrics. Best for Lambda (no extra API calls). Explained in detail later.
๐ Metric Math โ Calculations Between Metrics
Sometimes one metric isn't enough. You need to calculate something from multiple metrics. For example, error rate = (errors / total requests) ร 100. Metric Math lets you do this directly in CloudWatch without writing code.
Metric Math:
(m1/m2)*100 where m1 = Lambda/Errors and m2 = Lambda/Invocations.Create an alarm on this calculated metric. If > 5%, trigger the alarm.
CloudWatch Logs โ Storing and Searching Text Output
Logs are text records of what your application did. Every time your Lambda function runs, it can print messages. Those messages go to CloudWatch Logs. Without logs, when something breaks you have no idea what happened.
๐๏ธ Log Structure โ From Groups to Events
/aws/lambda/my-function) and API Gateway. You set the retention policy at the log group level (how long to keep logs). Default: never expire (you pay forever). Best practice: set retention to 7, 30, 90 days etc. to control costs.2024/01/15/[$LATEST]abc123def456). Multiple invocations in the same environment share the same stream. For EC2: each instance gets its own stream.2024-01-15T14:32:07Z ERROR Payment service unavailable.๐ Metric Filters โ Extract Numbers from Log Text
Metric Filters let you search log text for patterns and convert matches into CloudWatch Metrics. This is powerful because many applications log error counts, latency values, etc. as text โ and you want to alarm on them.
ERROR: payment failed.Create a Metric Filter with pattern
ERROR on the log group. Every time CloudWatch sees this pattern, it increments a counter metric called PaymentErrors.Now create a CloudWatch Alarm on
PaymentErrors > 10 in 5 minutes.Result: You get alerted when payment errors spike, even though you never called PutMetricData.
๐ฆ Log Retention โ Control Costs
By default, CloudWatch Logs never expire. This can become expensive. Always set retention policies:
7 Days
Dev/test environments
30 Days
Most production apps
90 Days
Security/compliance
1-7 Years
Regulatory requirements
For long-term archival (cheaper), export logs to S3 and use Athena to query them.
CloudWatch Logs Insights โ Query Your Logs Like a Database
CloudWatch Logs Insights is a query tool. Instead of scrolling through thousands of log lines manually, you write a query and it finds what you need in seconds. Think of it like SQL for your logs.
๐ Query Syntax โ Logs Insights Language
The query language uses pipe-separated commands (similar to Unix pipes). Each command filters or transforms the results:
๐ Key Logs Insights Commands
| Command | What it does | Example |
|---|---|---|
| fields | Select which fields to show | fields @timestamp, @message |
| filter | Keep only matching lines | filter level = "ERROR" |
| stats | Aggregate (count, avg, sum, min, max) | stats count() by errorType |
| sort | Order results | sort @timestamp desc |
| limit | Limit number of results | limit 100 |
| parse | Extract values from log text | parse @message "user=* latency=*" as userId, latency |
| like /regex/ | Regex pattern matching | filter @message like /timeout/ |
CloudWatch Dashboards โ Visual Monitoring
Dashboards are visual displays of your CloudWatch data. Think of a mission control room with multiple screens. You can put any metrics or alarms on a dashboard and share it with your team.
๐ What Can You Put on a Dashboard?
๐ Line Charts
Show metric trends over time. E.g., CPU usage over the last 24 hours.
๐ Bar Charts
Compare values across dimensions. E.g., error count per Lambda function.
๐ข Number Widgets
Show the current value of a metric. E.g., "Active DB Connections: 127".
๐ Alarm Status
Show whether alarms are OK, ALARM, or INSUFFICIENT_DATA.
๐ Text Widgets
Add notes, links, or documentation to the dashboard.
๐ Logs Insights Query
Embed a live Logs Insights query result directly on the dashboard.
๐ Sharing Dashboards
CloudWatch Dashboards can be shared outside your AWS account:
- Shared Dashboards: Make a dashboard publicly accessible with a URL. Anyone with the link can view (read-only) without an AWS account. Great for sharing metrics with managers or stakeholders.
- Account-level sharing: Share with specific AWS accounts in your organization.
- Cross-account/Cross-region: View metrics from multiple accounts and regions in one dashboard.
CloudWatch Alarms โ Automated Alerting and Actions
An Alarm monitors a single metric and takes action when that metric crosses a threshold you define. This is how you get notified when something breaks โ and even auto-fix it.
๐ฆ The Three Alarm States
โ OK
The metric is within the threshold you defined. Everything is fine.
Example: CPU is 45%, alarm threshold is > 80%
๐จ ALARM
The metric has exceeded the threshold. Time to act!
Example: CPU has been > 80% for 5 consecutive minutes
โ INSUFFICIENT_DATA
Not enough data points to evaluate. Common for new alarms or metrics that don't fire often.
Example: Alarm just created, no data yet
โ๏ธ Alarm Configuration โ Key Settings
๐ฌ Alarm Actions โ What Happens When Alarm Triggers?
When an alarm goes to ALARM state (or back to OK state), you can automatically:
๐ข Send SNS Notification
SNS (Simple Notification Service) then delivers the alert to:
- Email addresses
- SMS messages
- Lambda functions (for automated remediation)
- SQS queues
- HTTP endpoints (Slack, PagerDuty, etc.)
๐ Auto Scaling Action
Trigger EC2 Auto Scaling to add or remove instances. Example: CPU > 70% โ scale out (add more EC2 instances). CPU < 30% โ scale in (remove instances). This is how AWS auto-scaling works behind the scenes.
๐ฅ๏ธ EC2 Action
Directly act on the EC2 instance: Stop, Terminate, Reboot, or Recover. Example: "If status check fails twice in a row โ reboot the instance".
๐ง Systems Manager Action
Create an OpsItem in Systems Manager OpsCenter for incident tracking and automated runbooks.
๐ Composite Alarms โ AND/OR Logic
A regular alarm watches one metric. A Composite Alarm combines multiple alarms using AND/OR logic. This reduces "alarm noise" (getting paged when only one of many metrics spikes).
Solution: Create a Composite Alarm:
Alert ONLY IF (
CPU > 80% AND Error Rate > 5% AND Response Time > 2 seconds).Now you only get paged when the application is actually in trouble, not just during a temporary CPU spike from a batch job.
Embedded Metric Format (EMF) โ Metrics From Logs
EMF is a way to create CloudWatch Metrics by writing structured JSON logs. You don't call the CloudWatch API directly โ instead you write a specially formatted JSON log, and CloudWatch automatically extracts and creates metrics from it.
๐ค Why Use EMF Instead of PutMetricData?
๐ Regular PutMetricData API
- Makes a separate HTTP API call to CloudWatch
- Adds latency to your Lambda function execution
- Two separate systems: logs AND metrics
- Logging and metric publishing are separate operations
๐ Embedded Metric Format (EMF)
- Just write a JSON log line โ no extra API call!
- CloudWatch processes it asynchronously in background
- One operation = both a log entry AND a metric
- Same data is searchable as logs AND graphable as metric
๐ EMF JSON Format
When CloudWatch receives this log, it:
- Stores the entire JSON as a log event (searchable with Logs Insights)
- Automatically extracts
ProcessingTimeandOrdersProcessedas CloudWatch Metrics in namespaceMyApp/OrderService
Lambda Powertools โ EMF Made Easy
Writing EMF JSON manually is tedious. AWS Lambda Powertools is a library that makes structured logging and EMF very easy with just a few lines of code:
CloudWatch Synthetics โ Test Your APIs 24/7
CloudWatch Synthetics lets you create canaries โ automated scripts that run on a schedule and mimic what a real user would do. They test your APIs, websites, and workflows even when no one is actually using them.
๐ฏ What Can Canaries Test?
๐ API Endpoint Monitoring
Make HTTP GET/POST requests to your API. Check the response code (expect 200), check the response body contains expected data, check the response time is below a threshold.
๐ฅ๏ธ Website/UI Monitoring
Use headless Chrome to load a web page, click buttons, fill forms (like a login or checkout flow). Check that each step works correctly and within time limits.
๐ก Availability Monitoring
Continuously verify that an endpoint is reachable and responding. Alert the team before users even notice a problem.
โฑ๏ธ Performance Baselines
Track how long your API takes to respond over time. Detect performance regressions after deployments.
๐ What Canaries Produce
- CloudWatch Metrics: Success rate, response time, failure count
- CloudWatch Logs: Detailed execution logs
- Screenshots: Visual screenshots of the page state when a test fails
- Alarms: Can trigger SNS notifications when canary fails
CloudWatch ServiceLens โ End-to-End Observability
ServiceLens is a CloudWatch feature that combines CloudWatch metrics/logs/alarms with AWS X-Ray traces. It gives you a complete picture of your application's health in one place.
๐ What ServiceLens Connects
๐ก Key ServiceLens Capabilities
- Service Map: Visual graph of your application services with health indicators
- Drill down: Click on an alarm โ see the X-Ray trace that caused it
- Correlated data: For any time period, see related metrics, logs, AND traces together
- Anomaly detection: See which services have unusual patterns
API Gateway Metrics โ What to Monitor
API Gateway automatically sends important metrics to CloudWatch. These are tested frequently in the exam.
Latency is high AND IntegrationLatency is high โ The backend (Lambda, HTTP) is slow. Focus optimization there.
Monitoring KPIs โ What to Track in Practice
KPI stands for Key Performance Indicator โ a specific, measurable number that tells you if your application is meeting its goals. The exam may ask what to monitor for various use cases.
| Service | Key Metrics to Monitor | What to Alarm On |
|---|---|---|
| Lambda | Errors, Duration, Throttles, ConcurrentExecutions, IteratorAge (for streams) | Errors > 0, Duration approaching timeout, Throttles > 0 |
| API Gateway | Latency, IntegrationLatency, 5XXError, 4XXError, CacheHitCount | 5XX rate > 1%, Latency p99 > 5 seconds |
| DynamoDB | ConsumedReadCapacityUnits, ConsumedWriteCapacityUnits, ThrottledRequests, SuccessfulRequestLatency | ThrottledRequests > 0, Latency spike |
| SQS | ApproximateNumberOfMessagesVisible (queue depth), ApproximateAgeOfOldestMessage | Queue depth growing, messages too old |
| RDS | DatabaseConnections, CPUUtilization, FreeableMemory, ReadIOPS, WriteIOPS | Connections near max, CPU > 80% |
| EC2 | CPUUtilization, NetworkIn/Out, StatusCheckFailed | CPU > 80%, Status check failed |