CloudWatch không chỉ là log, nó là platform observability

Mình từng ngồi hàng giờ lọc log tay để tìm top IP gây lỗi — Contributor Insights làm việc đó tự động. CloudWatch có nhiều tính năng nâng cao mà ít người biết tận dụng, bài này tổng hợp bốn cái hữu ích nhất cho production.

EMF (Embedded Metric Format)

import { Metrics } from "@aws-lambda-powertools/metrics";
const metrics = new Metrics({
  namespace: "MyApp",
  defaultDimensions: { service: "api" },
});

metrics.addMetric("Latency", "Milliseconds", Date.now() - start);
metrics.publishStoredMetrics(); // Không PutMetricData API call, không throttle

Contributor Insights

Top-N analysis — top 10 IP, user-agent, URL gây nhiều request/error nhất.

aws cloudwatch put-insight-rule --rule-name top-talkers --rule-state ENABLED --rule-definition '{
  "Schema": {"Name": "CloudWatchLogRule", "Version": 1},
  "LogGroupNames": ["/aws/lambda/api-handler"],
  "LogFormat": "JSON",
  "Contribution": {"Keys": ["$.sourceIP"], "AggregateOn": "Sum"}
}'

Synthetics Canary

aws synthetics create-canary --name api-health --schedule Expression="rate(5 minutes)" \
  --runtime-version syn-nodejs-puppeteer-9.1 --artifact-s3-location s3://canary-artifacts/

Test API endpoint từ external perspective, screenshot, HAR file.

Anomaly Detection

aws cloudwatch put-anomaly-detector --namespace AWS/ApiGateway --metric-name Count --stat Sum
aws cloudwatch put-metric-alarm --alarm-name api-traffic-anomaly \
  --comparison-operator GreaterThanUpperThreshold --threshold-metric-id "e1" \
  --metrics '[{"Id":"e1","Expression":"ANOMALY_DETECTION_BAND(m1,2)"},{"Id":"m1","MetricStat":{...}}]'

Bài sau: Phần 34: X-Ray — distributed tracing