</>Học Dev
Bài học

Tuần 8 - Ngày 1: Amazon CloudWatch

Tuần 8 – Ngày 1

Tuần 8 - Ngày 1: Amazon CloudWatch

Mục tiêu học tập

  • Hiểu CloudWatch: metrics, logs, alarms, dashboards
  • Nắm custom metrics, log groups, log insights
  • Áp dụng CloudWatch Alarms cho monitoring

1. Tổng quan CloudWatch

CloudWatch = monitoring service tập trung cho AWS resources và applications.

4 main components

  1. Metrics: số liệu theo thời gian
  2. Logs: collect, store, analyze logs
  3. Alarms: cảnh báo khi metric vượt threshold
  4. Dashboards: visualize metrics

Use cases

  • Monitor EC2 CPU, RDS connections, Lambda invocations
  • Centralize application logs
  • Alert on system anomalies
  • Auto-scaling triggers
  • Build operations dashboards

2. CloudWatch Metrics

Built-in metrics

  • EC2: CPU, NetworkIn/Out, DiskReadOps (no memory by default — need agent)
  • RDS: DatabaseConnections, FreeStorageSpace, CPUUtilization
  • S3: BucketSizeBytes, NumberOfObjects (daily)
  • Lambda: Invocations, Errors, Duration, Throttles
  • ELB: RequestCount, TargetResponseTime, HTTPCode_Target_4XX_Count

Custom metrics

  • Push custom metrics via API: PutMetricData
  • Dimensions: extra context (e.g., instance ID, environment)
cloudwatch.put_metric_data(
    Namespace='MyApp',
    MetricData=[{
        'MetricName': 'OrdersProcessed',
        'Value': 100,
        'Unit': 'Count',
        'Dimensions': [
            {'Name': 'Environment', 'Value': 'prod'}
        ]
    }]
)

High-Resolution metrics

  • Standard: 60-second granularity
  • High-resolution: 1-second granularity (extra cost)

Retention

  • 1-minute: retained 15 days
  • 5-minute: 63 days
  • 1-hour: 455 days (15 months)

3. CloudWatch Logs

Components

  • Log Group: container (e.g., /aws/lambda/my-function)
  • Log Stream: source within group (e.g., per instance)
  • Log Events: timestamped log lines

Sources

  • Lambda (automatic)
  • ECS, EKS (configurable)
  • CloudWatch Agent on EC2
  • VPC Flow Logs
  • Route 53 query logs
  • API Gateway access logs
  • ALB access logs (to S3, then to CloudWatch)
  • Custom: API or SDK

Retention

  • Configurable per log group: 1 day - 10 years - Never expire
  • Default: Never expire (cost grows!)

Logs Insights

  • Query language for log analysis
  • Example: count errors per minute
fields @timestamp, @message
| filter @message like /ERROR/
| stats count() by bin(1m)

4. CloudWatch Agent

Định nghĩa

CloudWatch Agent = installed on EC2/on-prem to collect:

  • Memory utilization (not default in CloudWatch)
  • Disk usage, I/O
  • Network detailed metrics
  • Custom logs (/var/log/myapp.log)

Setup

  1. Install CloudWatch Agent
  2. Configure via JSON or SSM Parameter Store
  3. Start agent → metrics + logs flow

5. CloudWatch Alarms

States

  • OK: metric within threshold
  • ALARM: metric breached threshold
  • INSUFFICIENT_DATA: not enough data

Configuration

  • Metric: which to monitor
  • Threshold: condition (>, <, =)
  • Period: evaluation period (1 min, 5 min, etc.)
  • Datapoints to alarm: 3 out of 5 periods (avoid false alarm)
  • Actions: SNS, SSM auto-remediation, Auto Scaling, EC2 actions

Actions

  • SNS notification (email, SMS)
  • Auto Scaling (scale in/out)
  • EC2 Action (stop, terminate, reboot, recover)
  • Systems Manager (run automation document)

Composite Alarm

  • Combine multiple alarms with AND/OR
  • Reduce alarm fatigue

6. Dashboards

Features

  • Drag-and-drop widgets
  • Line, stacked area, number, gauge, text
  • Multiple regions in 1 dashboard
  • Shareable
  • Auto-refresh

Cost

  • $3/dashboard/month (3 dashboards free)

7. CloudWatch Synthetics

Định nghĩa

Synthetics = scheduled scripts (canaries) test endpoint availability + UX.

Use case

  • Monitor website uptime
  • Test transaction flow (login, search, purchase)
  • API endpoint health
  • Alert on regression

Type

  • Heartbeat (URL ping)
  • API canary (REST API workflow)
  • Broken link checker
  • Visual monitoring (screenshot diff)
  • GUI workflow

8. CloudWatch RUM (Real User Monitoring)

Định nghĩa

RUM = monitor end-user experience (browser performance, errors).

Captures

  • Page load time
  • JavaScript errors
  • User journey
  • Geographic distribution

Use case

  • Web app performance monitoring
  • A/B testing analytics
  • Frontend troubleshooting

9. CloudWatch Anomaly Detection

Định nghĩa

ML auto-detect anomalies in metrics, alarm on deviation từ baseline.

Use case

  • Detect unusual API call spikes
  • Identify cost anomalies
  • Catch performance regressions

10. Cross-Account, Cross-Region Observability

Định nghĩa

View metrics + logs từ multiple accounts trong 1 dashboard.

Setup

  • Monitoring Account: receive data
  • Source Accounts: send data
  • Sink + Link configuration

Use case

  • Centralized ops dashboard for organization
  • Compliance reporting

11. CloudWatch Metric Math

Định nghĩa

Compute derived metrics from existing metrics.

Examples

e1 = m1 / m2 * 100  (error rate %)
e2 = sum(m1)        (total over time)
e3 = m1 + m2 + m3   (aggregate)

Use case

  • Custom KPIs
  • Rate calculations
  • Aggregation across resources

12. Pricing

  • Metrics: $0.30/metric/month (custom) + $0.01/1000 API requests
  • Logs: $0.50/GB ingested + $0.03/GB stored
  • Alarms: $0.10/alarm/month
  • Dashboards: $3/dashboard/month

Free tier

  • 10 custom metrics
  • 10 alarms
  • 5 GB logs ingested
  • 1M API requests

Câu hỏi ôn tập

  1. EC2 default metrics có bao gồm memory không?

    Xem đáp án

    Không — EC2 default metrics không có memory, disk utilization. Default metrics chỉ include: CPU Utilization, Network In/Out, Disk Read/Write (cho instance store), Status Check metrics. Memory và disk space cần CloudWatch Agent cài trên instance để gửi custom metrics. Đây là điểm hay nhầm trong kỳ thi — "EC2 memory metric" không có sẵn mà không cần agent.

  2. CloudWatch Logs retention default là bao lâu?

    Xem đáp án

    Never expire (vô thời hạn) — mặc định logs không bao giờ tự xóa và sẽ tốn tiền tích lũy. Nên set retention policy ngay khi tạo log group: 1 ngày đến 10 năm. Best practice: set retention phù hợp với compliance requirements (HIPAA thường 7 năm, nhiều apps đủ 90 ngày). Có thể export logs cũ sang S3 trước khi delete.

  3. Composite Alarm dùng để làm gì?

    Xem đáp án

    Kết hợp nhiều alarms dùng Boolean logic (AND/OR/NOT) thành một alarm duy nhất. Ví dụ: ALARM if (CPUAlarm AND MemoryAlarm) — chỉ alert khi cả hai đều trong ALARM state, giảm noise. Hoặc ALARM if (HighCPU OR HighDisk) — alert khi một trong hai. Composite Alarm giảm alert fatigue — không cần nhận từng alert riêng biệt khi chúng có correlation.

  4. CloudWatch Synthetics monitor gì?

    Xem đáp án

    Synthetic monitoring — chạy canary scripts (Node.js/Python) để simulate user behavior và monitor endpoints: (1) API availability và latency, (2) Website navigation flows (login → checkout), (3) Broken links, screenshot diffs. Canaries chạy theo schedule (cron), alert khi responses sai hoặc latency cao. Phát hiện issues proactively trước users thực. Tích hợp với X-Ray cho distributed tracing.

  5. Anomaly Detection hoạt động dựa trên gì?

    Xem đáp án

    Machine Learning model train trên metric history — học patterns (hourly, weekly, seasonal variations). Model tạo "expected band" cho metric. CloudWatch alert khi metric value nằm ngoài band. Ưu điểm: không cần set static thresholds (thích hợp cho metrics thay đổi theo thời gian). Cần ít nhất 2 tuần history để model accurate. Có thể exclude scheduled maintenance windows khỏi training.

Bài tập thực hành

  • Tạo CloudWatch Alarm: EC2 CPU > 80% trong 5 phút → SNS email
  • Install CloudWatch Agent trên EC2, configure memory metrics
  • Tạo Log Group cho Lambda, query với Logs Insights
  • Tạo dashboard với 4 widgets (CPU, Memory, Disk, Network)
  • Setup Synthetics canary monitor website
  • Push custom metric từ app, alarm khi vượt threshold

Tài liệu tham khảo chính thức


Tiếp theo: CloudTrail và Config