Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Monitoring with CloudWatch and X-Ray

Practical notes on using Amazon CloudWatch (metrics, logs, alarms, dashboards) and AWS X-Ray (distributed tracing), with definitions, exact statements, CLI/SDK syntax to remember, worked examples, common exam mistakes and quick checks.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Cloud applications run on many services and machines. Engineers use monitoring to know if the system is healthy, to find performance bottlenecks, and to diagnose failures. Amazon CloudWatch gives metrics, logs and alarms for AWS services and custom apps; AWS X-Ray gives distributed tracing to follow a request across services and find latency or errors.

Key ideas

  • Namespace (defined): A namespace is a container for metrics; namespaces isolate metrics from each other (for example AWS/EC2). Metric names are unique only inside a namespace.

  • Dimension (defined): A dimension is a name/value pair that uniquely identifies a metric (for example InstanceId=i-0123456789). A metric can have up to 10 dimensions.

  • Metric resolution and period (defined): Period is the length of each metric datapoint (for example 60 seconds). Resolution refers to granularity; CloudWatch supports standard (60 s) and high-resolution (1 s) metrics. (Assumption: some AWS services send metrics at fixed resolution; EC2 basic monitoring historically had 5-minute resolution vs detailed 1-minute.) Retention: 1-second high-resolution datapoints are available for 3 hours; 1-minute for 15 days; 5-minute for 63 days; 1-hour for 455 days.

  • Statistic & aggregation (defined): For each period, CloudWatch computes a statistic from the raw values in that period (e.g., Average, Sum, Minimum, Maximum, SampleCount). Use the statistic that matches the question (e.g., Average CPU). You can also use percentiles via ExtendedStatistic (for example p90, p99) when supported by the metric.

  • Alarm (defined): An alarm watches a metric and enters an ALARM state when the metric violates a configured threshold for the required number of evaluation periods. Key fields: Threshold, ComparisonOperator (>, <, >=, <=), Period, EvaluationPeriods, DatapointsToAlarm (optional), TreatMissingData. Alarm states are OK, ALARM, and INSUFFICIENT_DATA.

  • Log group and log stream (defined): A log group is a collection of log streams that share the same retention and access control. A log stream is an ordered sequence of log events from the same source (for example an EC2 instance or a single Lambda execution environment).

  • Metric filter (defined): A metric filter extracts numeric values from log events using a filter pattern and publishes them as custom CloudWatch metrics. This lets you convert textual logs into metrics for alarms and graphs.

  • CloudWatch Agent (defined): The CloudWatch Agent is software you install on servers to collect system metrics (CPU, memory, disk) and push them to CloudWatch. There is also a CloudWatch Logs agent or unified agent.

  • CloudWatch Logs Insights (defined): Logs Insights is an interactive query language for CloudWatch Logs; you write queries to find patterns and calculate aggregates from log data.

  • Dashboards (defined): Dashboards are visual pages that show widgets (graphs, numbers) built from metrics and logs, used for runbooks and on-call screens.

  • Events (defined): Events (now EventBridge) are time-based or event-based rules that trigger actions (for example: run a Lambda when an alarm enters ALARM). CloudWatch Events and EventBridge are the same system for routing events.

  • AWS X-Ray (defined): X-Ray is a distributed tracing service. A trace represents a single request flowing through multiple services. Each trace is made of segments (service-level) and subsegments (detailed operations). X-Ray builds a service map to show latency/error hotspots.

  • Segment & subsegment (defined): A segment represents work done by a single AWS resource (for example an EC2 instance or Lambda). A subsegment represents a smaller unit inside the segment (for example a SQL query). Segments/subsegments include start/end times and metadata/annotations.

  • Annotations vs Metadata (defined): Annotations are indexed key-value pairs attached to traces (searchable). Metadata is not indexed and is stored for debugging (larger payloads allowed).

  • Sampling (defined): Sampling controls how many requests X-Ray records as full traces. The default sampling rule is: keep 1 request per second (reservoir) and sample a fixed rate of 5% thereafter. This reduces overhead and storage.

  • X-Ray daemon (defined): The X-Ray daemon receives UDP segments from the SDK and batches them to the X-Ray service. SDKs send trace data to the daemon on UDP port 2000 by default.

  • What to draw in an exam diagram: draw a box for the client, arrows to a load balancer, arrows to two EC2/Lambda service boxes, then arrows between services to a database. Add a CloudWatch box collecting metrics and logs with arrows from each service and an X-Ray box collecting traces with arrows showing segments for each service. Label metrics (namespace, metric name, dimensions), log groups and streams, X-Ray segments/subsegments and the daemon (UDP:2000). Also draw an alarm on the CloudWatch box connected to SNS/Lambda.

Formulas

Alarm triggers when count_breaches >= DatapointsToAlarm

  • count_breaches = number of periods (within EvaluationPeriods) where ComparisonOperator(metric_value, Threshold) is true. Units: dimensionless. Use when configuring alarms.

DatapointsToAlarm ≤ EvaluationPeriods

  • both are integer counts. Default DatapointsToAlarm = EvaluationPeriods (consecutive breaches).

Required consecutive seconds = Period × EvaluationPeriods (assumes DatapointsToAlarm = EvaluationPeriods and no missing data)

  • Period in seconds (s), EvaluationPeriods integer. Use to compute how long a condition must last before alarm.

aws cloudwatch put-metric-alarm --alarm-name NAME --metric-name METRIC --namespace NAMESPACE --statistic STAT --period P --evaluation-periods E --threshold T --comparison-operator 'GreaterThanThreshold' --alarm-actions arn:aws:sns:...

  • Syntax to remember for CLI alarm creation. Symbols: NAME (string), METRIC (string), NAMESPACE (string), STAT (e.g., Average), P (seconds), E (int), T (numeric threshold). Applies when using AWS CLI.

aws logs put-metric-filter --log-group-name GROUP --filter-name NAME --filter-pattern 'PATTERN' --metric-transformations metricName=METRIC,metricNamespace=NAMESPACE,metricValue=$.value

  • Syntax to remember for creating metric filters from logs.

aws xray create-sampling-rule --sampling-rule-body file://rule.json

  • Syntax to remember for custom sampling rules.

Worked examples

Example 1 — CloudWatch alarm for EC2 CPU (numerical, exam style) Given: An EC2 instance reports CPUUtilization every 60 s. You must trigger an alarm when the 60-second average CPU is above 70% for 3 consecutive periods. Period = 60 s, EvaluationPeriods = 3, Threshold = 70 (%), Statistic = Average. Steps:

  1. Formula: Required consecutive seconds = Period × EvaluationPeriods = 60 s × 3 = 180 s.
  2. Alarm rule: cpu > 70 for 3 evaluation periods. Use CLI syntax (see Formulas) or console to set: Period=60, EvaluationPeriods=3, Threshold=70, ComparisonOperator=GreaterThanThreshold, Statistic=Average.
  3. If metric datapoints over three minutes are 68, 75, 72 (%), breaches = 2 (75 and 72). ALARM is not triggered because breaches < EvaluationPeriods (consecutive requirement). If datapoints were 71, 73, 74 then breaches = 3 and alarm enters ALARM state. Final: Alarm triggers only when three consecutive averages exceed 70% (after 180 s).

Example 2 — Create a custom metric from application logs (algorithmic trace) Goal: Turn log line {"duration":123,"user":"alice"} into a metric RequestDuration. Steps:

  1. Ensure logs are sent to CloudWatch Logs in a log group /myapp.
  2. Create a metric filter: filter pattern {$.duration = *} and metric transformation metricName=RequestDuration, metricNamespace=MyApp, metricValue=$.duration (for non-JSON logs, use an extraction pattern that names a duration field and set metricValue=$duration). CLI example in Formulas.
  3. After creating the metric filter, CloudWatch creates datapoints when logs match. You can then create an alarm on MyApp/RequestDuration with Statistic=Average, Period=60.
  4. Example: log lines 100, 150, 200 ms in one minute; Average = (100+150+200)/3 = 150 ms; if threshold 300 ms, alarm remains OK.

Example 3 — X-Ray trace interpretation (theory model answer) Given: A web request goes: Client → API Gateway → Lambda A → DynamoDB → Lambda B → external HTTP call. X-Ray trace collected shows segments with durations: API Gateway 500 ms, Lambda A 480 ms, DynamoDB call 120 ms, Lambda B 200 ms, external HTTP 150 ms. Explain:

  1. The trace root is API Gateway segment. Lambda A segment is a child; inside Lambda A two subsegments: call to DynamoDB (120 ms) and call to Lambda B (200 ms via invocation).
  2. If total Lambda A is 480 ms but child calls sum to 320 ms, remaining 160 ms is execution time in Lambda A code (processing/serialization).
  3. Look for subsegment with high error rate or high latency (e.g., external HTTP 150 ms). Use annotations to filter traces by user id. Suggest increasing timeout or investigating external service.
  4. Conclusion: hotspot is Lambda B/external HTTP; create alarm on X-Ray error rate or add annotation and use Logs Insights for details.

Common mistakes

  • Using Average when Sum or Maximum is required (e.g., using Average for request count will hide peaks).
  • Forgetting to create a metric filter or to enable the CloudWatch Agent; then no data appears.
  • Mixing up log group and log stream permissions; leaving no IAM role for agent to publish logs.
  • Misunderstanding X-Ray sampling: assuming X-Ray records every request — it samples. This hides rare problems unless you adjust sampling rules or use annotations to force sampling.
  • Thinking X-Ray SDK sends data directly to AWS (it sends to the local daemon on UDP:2000 by default).

For your exam

Question types you will see:

  • Definitions: explain CloudWatch metric, log group, X-Ray trace, segment, sampling.
  • Short notes: compare CloudWatch metrics vs logs, explain metric filters, explain X-Ray service map and when to use tracing vs metrics.
  • Derivations/calculations: compute how long an alarm takes to fire given Period and EvaluationPeriods; compute number of samples recorded given sampling rules.
  • Programs / commands: write AWS CLI to create an alarm or metric filter, or show pseudocode using an SDK to add annotations to traces (refer to the boto3 topic for coding details).
  • Diagrams: draw system with services, CloudWatch collection arrows, X-Ray segments and an alarm connected to SNS. Label namespaces, log groups and the X-Ray daemon.

What a full-marks answer includes: clear definitions (bolded terms), parameter values and units, CLI or SDK syntax if asked for configuration, step-by-step reasoning for timing/threshold questions, correct diagram labels (metrics namespace, log group names, segments/subsegments, UDP daemon port), and mention of IAM permissions and sampling impact.

Quick check

  1. What is a CloudWatch metric?
  2. How many seconds will an alarm wait to trigger if Period=60 and EvaluationPeriods=5?
  3. What is the difference between an X-Ray annotation and metadata?

Answers: A time-series numeric data point with namespace and dimensions; 300 s (60×5); annotations are indexed and searchable (small), metadata is unindexed and for debugging (larger).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?