Metrics: time-stamped numbers from every AWS service. CPU, errors, latency. Free for basic. Custom metrics: $0.30/month each.
Alarms: connect metrics to actions (page SNS, scale ASG). Use 3 evaluation periods + 2 datapoints to alarm — kills false alerts.
Logs Insights: query all logs in seconds. Fields, stats, percentiles, filter. Pay per GB scanned (~$0.005).
Metric Filters: run continuously, turn log patterns into metrics you can alarm on. Costs $0.30 per metric.
Production rule: CPU at 80% for 2 of 3 periods = page. 1 spike = nothing. TreatMissingData = breaching for heartbeat metrics.
Cost trap: publishing metrics with userId dimension. Each userId = separate billable metric. Use low-cardinality only.
Plain-English First
Imagine your house has a smart thermostat, a smoke detector, and a security camera — all sending alerts to your phone when something goes wrong. AWS CloudWatch is exactly that, but for your cloud infrastructure. It watches your servers, databases, and apps 24/7, records everything they do, and pages you the moment something looks off. You don't have to sit staring at a screen — CloudWatch does the watching so you can focus on building.
Every production system breaks. The difference between a 5-minute outage and a 5-hour disaster? Almost always the same thing: how fast you knew something was wrong.
AWS CloudWatch is the native observability service at the heart of every serious AWS deployment. It's not glamorous, but skipping it is like flying a plane with no instruments. Fine until it isn't.
This article covers metrics, alarms, logs, and dashboards. How they connect. How to set them up with CLI and CloudFormation. And the three mistakes engineers make with CloudWatch that page them at 3 AM for no reason.
CloudWatch Metrics: The Heartbeat of Your Infrastructure
A metric is just a time-stamped number with a name and a namespace. That's it. EC2 sends CloudWatch a CPUUtilization number every minute. RDS sends DatabaseConnections. Lambda sends Duration and Errors. These numbers stream in automatically — you don't write a single line of code to get them.
What makes metrics powerful is the dimension system. A dimension is a key-value pair that narrows down which resource a metric belongs to. For example, CPUUtilization by itself tells you nothing. CPUUtilization where InstanceId=i-0abc123 tells you exactly which server is melting. You can also publish your own custom metrics — think order count per minute, active WebSocket connections, or queue depth in your own application.
Metrics are stored in CloudWatch for 15 months, but the resolution degrades over time: data points are kept at 1-second resolution for 3 hours, then aggregated to 1-minute for 15 days, then 5-minute for 63 days, and finally 1-hour for 15 months. This matters when you're debugging an incident from three weeks ago — you'll only have 5-minute averages, not second-by-second data.
Knowing the retention and resolution schedule helps you set the right alarm evaluation periods and avoid false conclusions from aggregated data.
Custom metric cost trap: AWS charges $0.30 per custom metric per month. If you publish put-metric-data --dimensions Name=userId,Value=u-12345, each userId creates a separate billable metric. With 10,000 active users, that's $3,000 per month. Always use low-cardinality dimensions: Environment (prod/staging), Region, ServiceName, InstanceType. Never put unique identifiers in dimensions.
publish_custom_metric.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/bash
# publish_custom_metric.sh
# Publishes a custom business metric to CloudWatch.
# Runthis from an EC2 instance, a container, or your CI/CD pipeline.
# Prerequisite: AWSCLI installed and IAM role with cloudwatch:PutMetricData permission.
APP_NAME="checkout-service"ENVIRONMENT="production"
# Simulate reading the number of orders processed in the last minute.
# In a real app you'd query your database or read from an in-memory counter.
ORDERS_PROCESSED=142
# Publish the custom metric to a namespace we own.
# Namespace acts like a folder — use a consistent naming convention.
aws cloudwatch put-metric-data \
--namespace "TheCodeForge/${APP_NAME}" \
--metric-name "OrdersProcessedPerMinute" \
--value "${ORDERS_PROCESSED}" \
--unit "Count" \
--dimensions \
"Name=Environment,Value=${ENVIRONMENT}" \
"Name=AppName,Value=${APP_NAME}" \
--region us-east-1
# Verify the metric was accepted (exit code 0 means success)
if [ $? -eq 0 ]; then
echo "[OK] Metric published: ${ORDERS_PROCESSED} orders for ${APP_NAME} in ${ENVIRONMENT}"else
echo "[ERROR] Failed to publish metric. Check IAM permissions and region."
exit 1
fi
Output
[OK] Metric published: 142 orders for checkout-service in production
Custom Metric Costs Add Up Fast — Watch Your Dimensions
AWS charges $0.30 per custom metric per month. If you publish metrics with unique dimension combinations (e.g. per user-id), each unique combination is counted as a separate metric. A single app can accidentally generate thousands of billable metrics. Always use low-cardinality dimensions like Environment, Region, or AppName — never user IDs or request IDs.
Production Insight
A startup published custom metrics with userId dimension to track per-customer API latencies. They had 50,000 active customers. Each customer generated 5 metrics per day. CloudWatch bill: $15,000 per month.
Root cause: The engineer assumed dimensions were free like tags. They're not. Each unique combination of dimension values = one billable metric.
Fix: Removed userId dimension. Switched to percentiles (p50, p90, p99) across all customers. Bill dropped to $15/month.
Rule: If you need per-user metrics, send them to a separate analytics service (Athena, Redshift, third-party). CloudWatch is for aggregated infrastructure monitoring, not per-customer analytics.
Key Takeaway
Metrics = time-stamped numbers with dimensions. Built-in are free. Custom cost $0.30/month.
Dimensions must be low-cardinality. environment, region, service name. NEVER userId.
1-second resolution lasts 3 hours. 1-minute for 15 days. Plan retention accordingly.
Know the difference between standard and high-resolution metrics.
UseBuilt-in metrics. Already published. Free. No code needed.
IfApplication business metric: orders/minute, users online, queue length
→
UseCustom metric. Publish via CLI or SDK. $0.30/month per metric.
IfPer-user or per-request metrics
→
UseDo NOT use CloudWatch. Use Athena, Redshift, or third-party analytics.
IfHigh-frequency metrics (sub-minute, thousands of data points/second)
→
UseHigh-resolution custom metrics cost more. Use CloudWatch embedded metric format or third-party tool like Datadog.
CloudWatch Alarms: Turning Numbers Into Actions
A metric sitting in CloudWatch does nothing on its own. An alarm is what connects a metric to a response. You define a threshold, a comparison operator, and an evaluation period — and CloudWatch will flip the alarm state from OK to ALARM the moment that condition is met.
An alarm has exactly three states: OK (everything is fine), ALARM (threshold breached), and INSUFFICIENT_DATA (not enough data points have arrived yet, which happens right after you create an alarm or if the metric stops publishing). Understanding INSUFFICIENT_DATA is important — it's not the same as OK, and treating it that way is a common mistake.
Alarms can trigger three types of actions: SNS notifications (email, SMS, PagerDuty webhook), EC2 actions (stop, terminate, reboot, or recover an instance), and Auto Scaling actions (scale in or scale out). This is where CloudWatch becomes genuinely powerful — you can build self-healing infrastructure where an alarm automatically replaces a failing instance without any human involvement.
For composite alarms, you can combine multiple alarms with AND/OR logic. This lets you avoid alert fatigue by only paging someone when CPU is high AND error rate is also high — not when just one or the other spikes briefly.
The DatapointsToAlarm setting is your best defense against alert fatigue. If you set EvaluationPeriods=3 and DatapointsToAlarm=2, the alarm only fires if 2 out of 3 consecutive evaluation windows breach the threshold. A single 1-minute spike won't wake you at 3 AM. A sustained 3-minute problem will.
cloudwatch_alarm.yamlYAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# cloudwatch_alarm.yaml
# CloudFormation template that creates a CloudWatch alarm on a Lambda function.
# Deploy with: aws cloudformation deploy --template-file cloudwatch_alarm.yaml \
# --stack-name checkout-lambda-alarms --capabilities CAPABILITY_IAM
AWSTemplateFormatVersion: '2010-09-09'Description: >-
Alarm that fires when the checkout Lambda error rate exceeds 1% over 5 minutes.
Sends an alert to the on-call SNS topic when triggered.
Parameters:
LambdaFunctionName:
Type: StringDefault: checkout-processor
Description: The name of the Lambda function to monitor.
OnCallSnsTopicArn:
Type: StringDescription: ARN of the SNS topic that routes to PagerDuty or email.
Resources:
# Alarm: triggers ifLambda errors exceed 5 in any 5-minute window.
# EvaluationPeriods: how many periods must breach before alarm fires.
# DatapointsToAlarm: of those periods, how many must actually breach.
# Using2-of-3 prevents a single noisy data point from waking someone at 3am.
CheckoutLambdaErrorAlarm:
Type: AWS::CloudWatch::AlarmProperties:
AlarmName: !Sub'${LambdaFunctionName}-high-error-rate'AlarmDescription: >-
Fires when checkout Lambda has more than 5 errors in a 5-minute period.
CheckLambda logs in CloudWatchfor stack traces.
Namespace: AWS/Lambda # Built-in Lambda namespace — no setup needed
MetricName: ErrorsDimensions:
- Name: FunctionNameValue: !RefLambdaFunctionName # Scoped to our specific function
Statistic: Sum # Add up all error counts in the period
Period: 300 # Each evaluation window is 5minutes (300 seconds)
EvaluationPeriods: 3 # Look at the last 3windows (15 minutes total)
DatapointsToAlarm: 2 # Alarm only if2 out of 3 windows breach threshold
Threshold: 5 # More than 5 errors triggers the alarm
ComparisonOperator: GreaterThanThresholdTreatMissingData: notBreaching # No data = function not invoked = not an error
AlarmActions:
- !RefOnCallSnsTopicArn # Page on-call engineer via SNSOKActions:
- !RefOnCallSnsTopicArn # Also notify when alarm recovers
Outputs:
AlarmName:
Description: Name of the created CloudWatch alarm
Value: !RefCheckoutLambdaErrorAlarm
# Alarm initial state in CloudWatch console: INSUFFICIENT_DATA
# (changes to OK once Lambda emits its first metric data point)
#
# When errors exceed threshold:
# SNS delivers message to on-call topic:
# Subject: ALARM: "checkout-processor-high-error-rate" in US East (N. Virginia)
# Body: Threshold Crossed: 2 datapoints [6.0, 8.0] were greater than threshold 5.0
Pro Tip: Always Set TreatMissingData Intentionally
The default value for TreatMissingData is missing, which causes the alarm to stay in its current state when no data arrives. For error-count metrics this is fine, but for availability metrics (like Lambda Invocations, HealthyHostCount, heartbeat metrics), missing data should be treated as breaching — because if the metric stops publishing, something is very wrong. Pick the right value for each alarm, not the default.
Production Insight
A company had a CloudWatch alarm on EC2 Status Check Failed metric with EvaluationPeriods=1 and DatapointsToAlarm=1. Every time EC2 performed routine maintenance (instance reboot), the status check would fail for 30 seconds. Alarm fired. On-call got paged. Every day. Engineers started ignoring CloudWatch pages entirely.
When a real outage happened, no one responded for 45 minutes.
Fix: Changed to EvaluationPeriods=3, DatapointsToAlarm=2, Period=60 seconds. Now a 30-second maintenance reboot doesn't fire the alarm (only 1 of 3 periods breaches). A sustained 3-minute failure does.
Rule: Alert fatigue kills on-call effectiveness. Your alarms should only page when the problem is sustained (at least 2 of 3 evaluation windows) AND when missing data indicates a real problem (TreatMissingData: breaching for availability metrics).
Key Takeaway
Alarms connect metrics to actions. 3 states: OK, ALARM, INSUFFICIENT_DATA.
EvaluationPeriods=3, DatapointsToAlarm=2 = no paging for 1-minute spikes.
TreatMissingData: breaching for heartbeat/invocations metrics.
Composite alarms = AND/OR logic to reduce false alerts.
CloudWatch Logs: Centralising and Querying Application Output
CloudWatch Logs is where your application output lives. The hierarchy works like this: a Log Group is the top-level container (one per application or service), Log Streams are individual sources within that group (one per Lambda invocation, one per EC2 instance, one per container), and Log Events are the individual timestamped lines inside each stream.
Logs arrive in CloudWatch either automatically (Lambda, ECS, and CloudTrail do this natively) or via the CloudWatch Logs Agent or the newer CloudWatch Agent installed on EC2 instances.
The real power is CloudWatch Logs Insights, a query language that lets you search and aggregate across gigabytes of logs in seconds. It's not SQL, but it's close enough that you'll feel at home immediately. You can filter for errors, extract fields from structured JSON logs, calculate percentiles, and visualise results as time-series charts.
Metric filters are another killer feature: they scan incoming log lines for a pattern and convert matches into CloudWatch metrics. This means you can turn a log line like ERROR: payment gateway timeout into an incrementing metric — and then alarm on that metric. No log aggregation pipeline, no third-party tool, no extra cost beyond the metric itself.
Logs Insights cost warning: You're charged per GB of data scanned ($0.005 per GB). A poorly written query that scans 100 GB costs $0.50. That's cheap for incident debugging. But a query that runs every minute as a dashboard widget will cost $720/month. Use Logs Insights for ad-hoc debugging only. For continuous metrics, use Metric Filters.
logs_insights_query.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/bin/bash
# logs_insights_query.sh
# Runs a CloudWatchLogsInsights query to find the top 10 slowest
# API endpoints in the last hour, using structured JSON logs.
#
# Assumes your app logs JSON lines like:
# {"level":"INFO","endpoint":"/api/checkout","duration_ms":342,"status":200}
LOG_GROUP_NAME="/production/checkout-service"
QUERY_LOOKBACK_SECONDS=3600 # Last1 hour
START_TIME=$(date -u -d "-${QUERY_LOOKBACK_SECONDS} seconds" +%s) # Linux
# On macOS use: date -u -v -${QUERY_LOOKBACK_SECONDS}S +%s
END_TIME=$(date -u +%s)
echo "Starting Logs Insights query on: ${LOG_GROUP_NAME}"
echo "Time range: last ${QUERY_LOOKBACK_SECONDS} seconds"
# Start the query — LogsInsights runs asynchronously, so we get a query ID back.
QUERY_ID=$(aws logs start-query \
--log-group-name "${LOG_GROUP_NAME}" \
--start-time "${START_TIME}" \
--end-time "${END_TIME}" \
--query-string '
fields @timestamp, endpoint, duration_ms, status
| filter ispresent(duration_ms) # Only include log lines that have this field
| stats avg(duration_ms) as avg_duration,
max(duration_ms) as max_duration,
count() as request_count
by endpoint
| sort avg_duration desc # Slowest endpoints first
| limit 10
' \
--query 'queryId' \
--output text \
--region us-east-1)
echo "Query submitted. ID: ${QUERY_ID}"
echo "Waiting for results..."
# Poll until the query finishes (usually 2-10 seconds for an hour of logs)
whiletrue; doSTATUS=$(aws logs get-query-results \
--query-id "${QUERY_ID}" \
--query 'status' \
--output text \
--region us-east-1)
if [ "${STATUS}" == "Complete" ]; then
echo "Query complete. Results:"
# Fetch and pretty-print the results
aws logs get-query-results \
--query-id "${QUERY_ID}" \
--query 'results[*].[?field==`endpoint`].value | [0] | join(`,`, @)' \
--output json \
--region us-east-1break
elif [ "${STATUS}" == "Failed" ]; then
echo "[ERROR] Query failed. Check query syntax and log group name."
exit 1
fi
sleep 2
done
Output
Starting Logs Insights query on: /production/checkout-service
Logs Insights is for ad-hoc investigation — you run it manually when debugging. Metric filters run continuously in the background and turn log patterns into metrics you can alarm on. Use metric filters for things you always want to know (error rate, timeout count). Use Logs Insights for things you want to understand during an incident (which user triggered the error, what was the full request payload).
Production Insight
A team created a CloudWatch dashboard with a Logs Insights widget that ran every 60 seconds for the last 15 minutes of logs. The widget scanned 50 GB per execution. Daily cost: 50 GB × $0.005 × 1,440 executions = $360/day. Monthly: $10,800.
Root cause: They didn't know Logs Insights charges per GB scanned. A dashboard widget refreshes continuously.
Fix: Replaced Logs Insights widget with Metric Filters + standard CloudWatch metric graph. Metric Filters cost $0.30 per metric per month (not per query). Dashboard cost dropped to near zero.
Rule: Logs Insights is for human-driven debugging only. Never put Logs Insights queries in auto-refreshing dashboards or automated systems. Use Metric Filters and standard metrics for continuous monitoring.
Logs Insights: ad-hoc queries, pay per GB scanned. $0.005/GB.
Metric Filters: continuous log→metric conversion, cost per metric, not per query.
Never put Logs Insights in auto-refreshing dashboards. You'll pay $10k/month.
Putting It Together: Dashboards and a Real Monitoring Architecture
A CloudWatch Dashboard is a customisable canvas where you pin metrics graphs, alarm states, and log query results side by side. The point isn't just pretty charts — it's reducing the time-to-understanding during an incident. When your on-call engineer gets paged at 2am, the first thing they open should be a dashboard that answers: is this an app problem, a database problem, or a network problem?
Good dashboard design follows the RED method: Rate (requests per second), Errors (error rate), and Duration (latency percentiles). Put those three graphs at the top. Below them, add the saturation metrics — CPU, memory, DB connections. At the bottom, link to Logs Insights queries for the most common failure modes.
Here's the architecture pattern that works in production: CloudWatch receives metrics and logs from all your services automatically. Alarms on the most critical thresholds fire to an SNS topic. That SNS topic routes to PagerDuty (or OpsGenie, or just email if you're early-stage). The on-call engineer opens the service dashboard, runs a Logs Insights query to get the stack trace, fixes the issue, and the OKAction on the alarm auto-resolves the incident. Everything is connected, traceable, and auditable.
This closed loop — metric to alarm to notification to dashboard to logs — is the entire CloudWatch mental model. Once you've internalised it, everything else is just configuration.
# Row 2: [Alarm status panel — shows OK / ALARM / INSUFFICIENT_DATA in real time]
Pro Tip: Pin Dashboards to Cross-Account Views
If you run multiple AWS accounts (dev, staging, prod), you can add widgets from different accounts to a single dashboard using cross-account cross-region CloudWatch. This means one dashboard can show prod metrics from us-east-1 and eu-west-1 side by side. Set it up once in your monitoring account and your whole team has a single pane of glass — no tab switching during incidents.
Production Insight
A team's dashboard contained 47 graphs. On-call engineers had to scroll through 6 screen pages to find the relevant metrics. Mean time to diagnosis (MTTD) was 12 minutes.
Root cause: Dashboard design by accumulation. Every team added their graphs to the same dashboard. No one removed old ones. The dashboard became unusable.
Fix: Created three dashboards: Overview (RED metrics for all services), Service-Specific (detailed for checkout service), Infrastructure (CPU/memory for EC2). Each dashboard had fewer than 10 widgets. MTTD dropped to 3 minutes.
Rule: A dashboard should fit on one screen without scrolling. If you need more than 10 widgets, split into multiple dashboards. The purpose of a dashboard during an incident is to answer questions in seconds, not to catalogue every metric.
Key Takeaway
Dashboard = canvas for metrics, alarms, logs. One screen only (<10 widgets).
RED method: Rate, Errors, Duration at the top. Saturation below.
Cross-account widgets let you monitor all environments from one dashboard.
● Production incidentPOST-MORTEMseverity: high
The 3 AM Alarm That Wasn't: TreatMissingData Default
Symptom
CloudWatch alarm configured on Lambda Errors metric shows OK status. No notification sent. autorep shows no invocations for hours. The service is down but the monitoring claims everything is fine.
Assumption
The team assumed TreatMissingData default value (missing) would be safe. They thought 'missing data' meant no errors — which would be OK. They didn't realise a dead service also produces no data.
Root cause
The Lambda's event source mapping failed at 2 AM (DynamoDB stream permissions revoked). The function wasn't invoked at all. CloudWatch stopped receiving any metric data points for that function.
TreatMissingData was left at the default (missing), which means 'keep the alarm in its current state when no data arrives'. The alarm was currently OK, so it stayed OK. No notification.
A service that should always be emitting metrics going silent is itself a critical failure. The default setting masked it completely.
Fix
1. Changed the alarm's TreatMissingData to breaching:
TreatMissingData: breaching
2. Added a heartbeat metric: Lambda publishes custom metric every minute. Alarm on missing heartbeat → pages immediately.
3. Set metric filter to count invocations: filter @message like /Processed/ | stats count(). Alarm on zero invocations for 10 minutes.
4. Add CloudWatch alarm on Lambda Invocations metric with TreatMissingData: breaching — zero invocations = dead service.
Prevention: For any metric where silence = failure (invocations, heartbeat, queue consumers, active connections), always set TreatMissingData: breaching.
Key lesson
TreatMissingData default (missing) is dangerous for availability metrics.
Silence from a service that should be talking is itself a problem worth paging on.
Lambda Invocations = 0 for 5 minutes means something is broken upstream.
Add explicit heartbeat metrics for critical scheduled jobs.
Production debug guideThe 4 most common CloudWatch failure modes and how to diagnose them4 entries
Symptom · 01
Alarm shows INSUFFICIENT_DATA for hours, never OK or ALARM
→
Fix
Check if metric is actually publishing. Go to CloudWatch Metrics → browse namespace → look for recent data points. No data = service not publishing = fix the publisher.
Symptom · 02
Alarm fires constantly — every few minutes pages on-call
→
Fix
Check EvaluationPeriods and DatapointsToAlarm. Likely set to 1 and 1 (any single breach fires). Increase to 3 and 2 so only sustained breaches page.
Symptom · 03
Custom metrics cost $300+ per month unexpectedly
→
Fix
List custom metrics: aws cloudwatch list-metrics --namespace YourApp. Look for high-cardinality dimensions (userId, requestId). Each unique combination = separate billable metric.
Symptom · 04
Logs Insights query returns nothing for expected logs
→
Fix
Check log group retention period. Default is never expire, but someone may have set 7 days. aws logs describe-log-groups. Also verify timestamp range in query.
★ CloudWatch — 60-Second DiagnosisRun these commands when CloudWatch isn't behaving as expected
Set log retention to 30 days for app logs, 90 days for compliance. Don't pay to store logs you'll never read.
Common mistakes to avoid
5 patterns
×
Setting alarms with EvaluationPeriods=1 and DatapointsToAlarm=1
Symptom
Alert fatigue from single noisy spikes; engineers start ignoring pages; real outages get missed.
Fix
Use at least EvaluationPeriods=3 with DatapointsToAlarm=2 so the alarm only fires when a problem persists across multiple windows, not from one momentary blip.
×
Publishing custom metrics with high-cardinality dimensions like userId or requestId
Symptom
AWS bill unexpectedly shows thousands of custom metrics and costs $300+ per month instead of $3.
Fix
Never use unique identifiers as dimension values. Stick to low-cardinality values like Environment (production/staging), Region, or ServiceName.
×
Leaving TreatMissingData at its default (missing) for availability-type metrics
Symptom
A service goes completely dark (stops publishing metrics) and no alarm fires because CloudWatch sees 'no data' and keeps the alarm in its current state (which was OK).
Fix
For any metric where silence means failure (HealthyHostCount, heartbeat metrics, invocations count), explicitly set TreatMissingData: breaching so a dead service pages you.
×
Putting Logs Insights queries in auto-refreshing dashboards
Symptom
Monthly CloudWatch bill hits $10,000+. Dashboard has a Logs Insights widget that scans 50 GB every 60 seconds.
Fix
Logs Insights is for manual debugging only. Never auto-refresh. Use Metric Filters to convert log patterns to metrics, then graph the metrics (costs $0.30/month).
×
Storing logs forever with no expiration
Symptom
Log group has 2 TB of data from 3 years ago. CloudWatch Logs storage bill is $60/month for logs you never query.
Fix
Set retention period to 30 days for application logs, 90 days for compliance logs, 365 days for audit logs. Use aws logs put-retention-policy --log-group-name /my/app --retention-in-days 30.
INTERVIEW PREP · PRACTICE MODE
Interview Questions on This Topic
Q01SENIOR
CloudWatch Alarms have three states — OK, ALARM, and INSUFFICIENT_DATA. ...
Q02SENIOR
You're trying to alert on the error rate of a Lambda function, but you w...
Q03SENIOR
What's the difference between a CloudWatch Metric Filter and a Logs Insi...
Q01 of 03SENIOR
CloudWatch Alarms have three states — OK, ALARM, and INSUFFICIENT_DATA. When would an alarm be in INSUFFICIENT_DATA and why is it dangerous to treat that state the same as OK?
ANSWER
INSUFFICIENT_DATA occurs when CloudWatch hasn't received enough metric data points to evaluate the alarm. This happens right after creating an alarm (at least 2 evaluation periods needed) or when the metric source stops publishing data.
Treating INSUFFICIENT_DATA as OK is dangerous because a dead service (Lambda not running, EC2 crashed, app not sending heartbeat) also produces no data. The alarm would show OK, and you'd never know the service is down.
Correct approach: For availability metrics (heartbeats, invocations, healthy hosts), set TreatMissingData: breaching. For error rate metrics (silence means no errors), set TreatMissingData: notBreaching.
Example: A Lambda that should process transactions every minute stops being invoked due to a broken event source mapping. Invocations metric goes from 5/minute to 0. With TreatMissingData: breaching on an Invocations < 1 alarm, CloudWatch fires ALARM and pages on-call. With default (missing), the alarm stays OK and no one knows.
Q02 of 03SENIOR
You're trying to alert on the error rate of a Lambda function, but you want to avoid false alarms from momentary spikes. Walk me through how you'd configure the alarm's EvaluationPeriods and DatapointsToAlarm to achieve this.
ANSWER
Configuration: Set EvaluationPeriods: 3 (look at the last 3 evaluation windows) and DatapointsToAlarm: 2 (require 2 of those 3 windows to breach the threshold).
Why this works: With Period=300 seconds (5 minutes), each evaluation window is 5 minutes. The alarm looks at the last 15 minutes (3 windows). It only fires if 10 minutes worth of data breaches the threshold.
Effect: A single 5-minute spike won't fire the alarm. A sustained problem that spans at least 10 of the last 15 minutes will.
Period selection: For Lambda error rates, use Period=300 (5 minutes). Errors per minute vary widely; 5-minute windows smooth noise.
Threshold design: Don't use absolute error count. Use error rate percentage: (Errors / Invocations) 100 > 1 requires a metrics math expression alarm, which supports e1/e2100 > 1.
Result: On-call gets paged only for real, sustained issues, not for every transient network blip.
Q03 of 03SENIOR
What's the difference between a CloudWatch Metric Filter and a Logs Insights query, and when would you choose one over the other in a production monitoring setup?
ANSWER
Both work with log data but serve completely different purposes:
Metric Filter: Runs continuously on every incoming log line. When it matches a pattern (e.g. 'ERROR'), it increments a CloudWatch metric. You then alarm on that metric. Latency: ~1 minute. Cost: $0.30 per custom metric per month.
Logs Insights Query: Runs on-demand when you trigger it. Scans stored log data and returns results like 'top 10 slowest endpoints'. Used for debugging during incidents. Latency: 2-30 seconds. Cost: $0.005 per GB scanned.
Choose Metric Filter when:
- You always need to know about a condition (error rate > 5%)
- The condition is simple (contains 'ERROR', 'TIMEOUT')
- You need an alarm to page on-call
Choose Logs Insights when:
- You're manually debugging an incident
- You need complex queries (stats, percentiles, joins)
- You need to see which user triggered the error or the full payload
- The question is 'why did this happen?' not 'should we page?'
Critical rule: Never put Logs Insights queries in auto-refreshing dashboards. You'll pay $10k/month. Metric Filters + standard metric graphs auto-refresh cheaply.
01
CloudWatch Alarms have three states — OK, ALARM, and INSUFFICIENT_DATA. When would an alarm be in INSUFFICIENT_DATA and why is it dangerous to treat that state the same as OK?
SENIOR
02
You're trying to alert on the error rate of a Lambda function, but you want to avoid false alarms from momentary spikes. Walk me through how you'd configure the alarm's EvaluationPeriods and DatapointsToAlarm to achieve this.
SENIOR
03
What's the difference between a CloudWatch Metric Filter and a Logs Insights query, and when would you choose one over the other in a production monitoring setup?
SENIOR
FAQ · 5 QUESTIONS
Frequently Asked Questions
01
How much does AWS CloudWatch cost for a basic setup?
Basic EC2, Lambda, and RDS metrics are free — AWS publishes these automatically at no charge. You start paying when you add custom metrics ($0.30 per metric per month), store logs ($0.50 per GB ingested, $0.03 per GB stored per month), run Logs Insights queries ($0.005 per GB scanned), or create more than 10 dashboards (first 3 are free). For a small production service, expect $5-30/month; for a large multi-service platform, budget $100-500/month. The biggest cost surprises come from high-cardinality custom metrics (dimensions like userId) and auto-refreshing Logs Insights queries in dashboards.
Was this helpful?
02
What is the difference between CloudWatch and CloudTrail?
CloudWatch monitors the performance and health of your running resources — CPU, errors, latency, application logs. CloudTrail records who did what to your AWS account — API calls like 'who deleted that S3 bucket?' or 'who changed this security group?'. Think of CloudWatch as your operations monitor and CloudTrail as your audit log. You often use them together: CloudTrail logs go to CloudWatch Logs, where you set metric filters to alarm on sensitive actions like root account logins or security group deletion.
Was this helpful?
03
Can CloudWatch automatically fix problems, or does it only alert?
It can do both. CloudWatch Alarms support three types of automatic actions beyond notifications: EC2 actions (automatically stop, reboot, or recover an instance when an alarm fires), Auto Scaling actions (scale out more instances when CPU is high, scale in when it's low), and SNS notifications that trigger Lambda functions — which can then do anything you can code, from restarting a service to rolling back a deployment. The most powerful setups combine all three for genuinely self-healing infrastructure: an alarm detects a failed instance, Auto Scaling launches a replacement, and Lambda updates the load balancer target group.
Was this helpful?
04
What retention period should I set for application logs?
Rule of thumb: Application logs (INFO, DEBUG): 30 days. Error logs: 90 days. Compliance logs (audit trails, PCI/HIPAA): 365 days or longer as required. Security logs (VPC Flow Logs, CloudTrail): 90–365 days depending on investigation needs. Never keep logs forever — you'll pay $0.03/GB/month for storage you never query. Set retention with: aws logs put-retention-policy --log-group-name /my/app --retention-in-days 30. For compliance retention, use S3 export (CloudWatch Logs exports to S3) which costs $0.023/GB/month — cheaper than CloudWatch native storage.
Was this helpful?
05
How do I set up a heartbeat alarm to detect when a service stops publishing?
Step-by-step heartbeat alarm setup:
1. In your service code (cron/scheduler that runs every minute): ``python import boto3 cloudwatch = boto3.client('cloudwatch') cloudwatch.put_metric_data( Namespace='TheCodeForge/CheckoutService', MetricData=[{ 'MetricName': 'Heartbeat', 'Value': 1, 'Unit': 'Count', 'Timestamp': datetime.utcnow() }] ) ``
Why this works: If the service stops publishing, after 3 minutes of missing data, the alarm fires. TreatMissingData: breaching converts silence into ALARM.