TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท cloud ยท monitoring ยท observability ยท logging

Amazon CloudWatch

AWS's monitoring service. It stores time-series metrics, evaluates alarms on them that notify or act, collects and queries logs, and draws dashboards, for AWS services and your own applications.

15 min6 animations

๐Ÿ“š Builds on๐Ÿšš Amazon EC2 and Auto Scaling

๐Ÿ–จ๏ธ Cheat sheet

The van's dashboard

You run a delivery van. While you drive, you can't open the bonnet every few minutes to see how the engine is doing. So the van has a dashboard. Gauges show how hot the engine is and how much fuel is left. A trip log records what happened on the way: "parcel 17 delivered", "road closed, took a detour". And when something stays wrong for a while, a warning light comes on, so you notice even if you weren't looking at the gauges.

The van doesn't decide what's on the dashboard; it just keeps sending readings and writing lines. The dashboard keeps them, so later you can look back and ask what happened at three o'clock. That dashboard, for every van your company runs, is called CloudWatch.

What CloudWatch is

Amazon CloudWatch is AWS's monitoring service. Its core parts are:

PartWhat it holds
MetricsTime-ordered numeric datapoints, such as an instance's CPUUtilization every minute
AlarmsRules that watch one metric (or an expression) and change state when it crosses a threshold
LogsTimestamped text events, grouped and searchable, with configurable retention
DashboardsSaved pages of graphs, numbers, alarm states and log query results

Most AWS services publish metrics on their own: EC2 instances, load balancers, Lambda functions, queues and databases all send them without any setup. Your applications add their own metrics and send logs. Everything is Regional: metrics, alarms and log groups live in the Region they were written to, while dashboards can show data from several Regions and accounts.

The point is to answer two questions without logging into a machine: "is it healthy right now?" (metrics and alarms) and "what happened?" (logs, and traces for requests that cross services).

CloudWatch at a glance4 steps
๐ŸŽ›๏ธ Dashboard๐ŸšDelivery vanโฒ๏ธGauges๐Ÿ““ Trip log๐ŸšจWarning light๐Ÿง‘You
Press play and watch it happen!

Gauges and readings

Every gauge shows one thing, like engine heat, and gets a new reading every few minutes (every minute if you pay for the faster one). Gauges sit on panels: the van maker's engine panel, or a panel you added yourself. Each gauge also has a little tag saying which one it is, like "van 1" or "front-left tyre", because "tyre pressure" alone doesn't tell you much.

Looking back, you rarely want every single reading. You ask for a summary of each stretch of time: "what was the hottest the engine got in each five minutes?", or "what was it on average?". The hottest and the average can tell very different stories, so you choose the summary that answers your question.

You can fit your own gauges too, like one that counts parcels delivered, and ask for a fast one whose needle moves every second instead of every minute. Each gauge you add costs a little every month, so you fit the ones you'll really look at. A gauge you added yourself is called a custom metric.

Metrics, dimensions and statistics

A metric is identified by a namespace (AWS/EC2, or your own such as OrdersService), a metric name (CPUUtilization) and up to 30 dimensions, name/value pairs such as InstanceId=i-0abc123. Every distinct combination of dimensions is a separate metric: CPUUtilization for two instances is two metrics. To see them as one, query them together (a Metrics Insights query or a SEARCH expression) or publish a version with fewer dimensions.

Each datapoint has a timestamp, a value and a unit. When you read a metric you choose a period (60 seconds, 5 minutes...) and a statistic that summarises the datapoints in each period: Average, Sum, Minimum, Maximum, SampleCount, or a percentile such as p99. Averages hide spikes; for latency, look at p99 or Maximum.

  • Resolution: standard-resolution metrics have one-minute granularity. High-resolution custom metrics (StorageResolution=1) keep data down to one second, so alarms and graphs can react in seconds.
  • EC2 monitoring: basic monitoring sends instance metrics every 5 minutes for free; detailed monitoring sends them every minute, at a cost. Memory and disk-space usage are not EC2 metrics at all, since the hypervisor can't see inside the guest: install the CloudWatch agent, which publishes them (for example mem_used_percent) under the CWAgent namespace.
  • Retention rolls data up as it ages: sub-minute datapoints for 3 hours, 1-minute for 15 days, 5-minute for 63 days, 1-hour for 455 days (about 15 months). Metrics can't be deleted; they expire once no new data arrives.

Custom metrics come from PutMetricData (the SDK, CLI, Micrometer or the agent), or from logs in the embedded metric format (EMF): a structured JSON log line with an _aws block that tells CloudWatch which fields to extract as metrics. EMF lets you emit high-cardinality context (an order ID) in the log line while only the declared dimensions become metrics.

1{2  "_aws": {3    "Timestamp": 1761400000000,4    "CloudWatchMetrics": [{5      "Namespace": "OrdersService",6      "Dimensions": [["Channel"]],7      "Metrics": [{ "Name": "OrderLatency", "Unit": "Milliseconds" }]8    }]9  },10  "Channel": "web",11  "OrderLatency": 182,12  "orderId": "o-917"13}

On Lambda, writing that line to standard output is enough; on EC2 or containers, send it through the CloudWatch agent (or Fluent Bit/FireLens), which marks it as EMF.

๐Ÿ”ง Going deeper

Gotchas

  • Custom metrics are billed per metric per month, and each new dimension value is a new metric. A dimension such as userId or requestId can create millions of them; put such values in logs (or EMF properties), not dimensions.
  • A metric that only reports when something happens (errors, throttles) has gaps, not zeros. Graph Sum with a period, and think about missing data when you alarm on it.
Metrics, dimensions and statistics5 steps
๐Ÿ› ๏ธ Engine panelEngine heat: van 1012345Engine heat: van 2012345๐ŸšVan 1๐ŸšVan 2๐Ÿง‘You
Press play and watch it happen!

Warning lights

Gauges only help if someone is looking. So you add a warning light to a gauge, and give it a red line: "engine heat above 80". The light doesn't flash at the first hot reading, because one hot minute on a hill is normal. It waits until enough recent readings are bad, for example two of the last three.

The light has three looks. Off means everything is fine. On means there's trouble. Grey means it can't tell, because no readings are arriving at all. A light like that, with its red line and its patience, is called an alarm.

When the light comes on, it can do more than glow. It can text the boss's phone, call another van out from the depot to share the work, or switch the van's engine off and on again. When things are fine again, it goes off, and can text the boss that too.

Alarms: thresholds, M of N, states and actions

A metric alarm watches one metric (or a metric math expression) with a statistic and a period, and compares each period's value with a threshold using an operator such as GreaterThanThreshold.

  • Evaluation periods (N): how many recent periods are considered.
  • Datapoints to alarm (M): how many of those N must breach. "2 of 3" ignores a single spike but still reacts within a few periods; "3 of 3" means three breaching periods in a row.
  • States: OK, ALARM and INSUFFICIENT_DATA (just created, or not enough data to evaluate).
  • Missing data (TreatMissingData): missing (the default; if every point in the evaluation range is missing, the alarm goes to INSUFFICIENT_DATA), notBreaching (good, right for error counts that only report when errors happen), breaching (bad, right for heartbeats) and ignore (keep the current state).

Actions run on state changes: notify an SNS topic (email, SMS, chat, a Lambda), run an Auto Scaling policy, or run an EC2 action (stop, terminate, reboot or recover the instance), or invoke a Lambda function directly. Apart from Auto Scaling actions, which keep firing while the alarm stays in ALARM, actions run once per transition, not repeatedly while the state lasts. Target tracking policies on an Auto Scaling group create and manage their own alarms.

1aws cloudwatch put-metric-alarm \2  --alarm-name web-1-cpu-high \3  --namespace AWS/EC2 --metric-name CPUUtilization \4  --dimensions Name=InstanceId,Value=i-0abc123 \5  --statistic Average --period 60 \6  --evaluation-periods 3 --datapoints-to-alarm 2 \7  --threshold 80 --comparison-operator GreaterThanThreshold \8  --treat-missing-data missing \9  --alarm-actions arn:aws:sns:eu-west-1:123456789012:ops-alerts \10  --ok-actions arn:aws:sns:eu-west-1:123456789012:ops-alerts

A 60-second period on an EC2 metric needs detailed monitoring; with basic monitoring there's only one datapoint every 5 minutes. Composite alarms combine other alarms with AND, OR and NOT, which cuts noise: page only when "error rate high AND latency high", not for each alarm on its own.

An alarm with 2 of 3 datapoints6 steps
Engine heat gauge012345๐ŸšVan 1๐ŸšจWarning light๐Ÿ“ฑBoss's phone๐ŸญVan depot
Press play and watch it happen!

The trip log

Gauges tell you something is wrong, but not why. For that you read the trip log. Every van writes its own pages, line by line, and the pages for one kind of job go into one logbook: all the delivery vans' pages in the "deliveries" logbook, say.

Logbooks get thick, so you decide how long to keep pages before they're shredded: a week, a month, ten years. If you never decide, they're kept forever and the shelf keeps growing.

Two helpers make the log useful. One reads every new line as it's written, and each time a line says "flat tyre", it nudges a "flat tyres" gauge up by one, so a warning light can watch it. The other searches the whole logbook for you when you ask a question, like "which vans had a flat tyre this morning?". Each van's own set of pages is called a log stream.

CloudWatch Logs: groups, streams, retention and queries

A log event is a timestamp and a message. Events from one source (one instance, one container, one Lambda execution environment) form a log stream, and streams that share retention, permissions and settings belong to a log group, such as /aws/lambda/orders or /app/orders-service.

  • Retention is set per log group, from one day to ten years. The default is never expire, so set it, or the storage bill grows forever.
  • Logs Insights queries one or more log groups over a time range with a pipe-based language. JSON log fields are discovered automatically, and you pay per GB scanned, so narrow the time range and groups.
1fields @timestamp, @logStream, @message2| filter level = "ERROR"3| stats count(*) as errors by bin(5m)4| sort errors desc
  • A metric filter matches a pattern in incoming events and publishes a metric, such as ErrorCount going up by 1 per match, which you can then alarm on. Filters apply only to events ingested after the filter exists, not to history.
  • A subscription filter streams matching events on to Lambda, Kinesis Data Streams, Amazon Data Firehose or OpenSearch for processing or archiving.

AWS services such as Lambda write to CloudWatch Logs directly. On EC2, the CloudWatch agent tails your log files and ships them.

Log groups, metric filters and Logs Insights5 steps
๐Ÿ“š Deliveries logbookVan 1's pages01234Van 2's pages01234๐ŸšVan 1๐ŸšVan 2โฒ๏ธFlat tyre gauge๐Ÿง‘You
Press play and watch it happen!

Saved views in the glovebox

The van's screen can show any gauges you like, but picking them one by one every morning is slow. So you keep cards in the glovebox. The "morning check" card says: engine heat for every van, the fuel gauges, the warning lights, and the last ten flat-tyre lines from the trip log. Slide it in, and the screen shows all of that side by side.

The card doesn't hold any readings itself. It only says what to show, so every time you look, it fetches the latest. Change the time on the screen from "last hour" to "last week", and every picture on it redraws for that week. CloudWatch calls a card like that a dashboard: the same word as the whole panel, but it means one saved view of it.

Dashboards

A dashboard is a saved layout of widgets: line and stacked graphs, single numbers, gauges, alarm status, Logs Insights query results, text and more. The dashboard body is JSON, so you can keep it in source control and deploy it with CloudFormation or CDK.

Dashboards store no data. Each widget holds a query (metrics, a math expression, a Logs Insights query or an alarm), and the console runs those queries when you open the page or change the shared time range or refresh interval. One dashboard can combine metrics from several Regions, and from several accounts with cross-account observability.

Good dashboards are built for a question: one per service showing its traffic, errors, latency (p99, not just Average) and saturation, next to the alarms that page someone. CloudWatch also builds automatic dashboards for many AWS services, which are a useful starting point.

A dashboard runs its widgets' queries4 steps
๐Ÿง‘You๐Ÿ—‚๏ธ Morning check cardโฒ๏ธGauges๐ŸšจWarning lights๐Ÿ““ Trip log
Press play and watch it happen!

Fitting your own gauges

Your van's gear can do the counting itself. A meter-reader built into the van counts things as they happen, like parcels delivered and how long each drop-off took. Once a minute it sends the dashboard a short summary, not one message per parcel, so the line to the dashboard stays quiet.

For everything the van's gear can't see, a helper rides along. The helper copies the trip log onto the dashboard's shelf and reads gauges the van maker didn't fit, like how full the cargo area is.

And to follow one parcel through every hand-over from van to depot to van, each stop stamps the parcel's card with the time it arrived and left. Lay the stamps side by side and you see where it waited longest. That stamped card is called a trace.

Spring Boot: Micrometer, the agent and traces

A Spring Boot app records metrics through Micrometer. Add the Spring Cloud AWS metrics starter, which brings in micrometer-registry-cloudwatch2 and the Actuator, and set a namespace:

1<dependency>2  <groupId>io.awspring.cloud</groupId>3  <artifactId>spring-cloud-aws-starter-metrics</artifactId>4</dependency>
1management.cloudwatch.metrics.export.namespace=OrdersService2management.cloudwatch.metrics.export.step=1m
1@Service2class OrderService {3    private final Counter placed;4    private final Timer checkout;5 6    OrderService(MeterRegistry registry) {7        this.placed = Counter.builder("orders.placed").tag("channel", "web").register(registry);8        this.checkout = Timer.builder("orders.checkout").register(registry);9    }10 11    void place(Order order) {12        checkout.record(() -> save(order));13        placed.increment();14    }15}

The registry aggregates in memory and sends one batch of PutMetricData calls per step, so a busy app doesn't make a call per event. Tags become dimensions. Spring Boot registers many meters by default (JVM, HTTP, pools), and each one becomes billable custom metrics, so add a MeterFilter that accepts only the meters you use.

Without Spring, the AWS SDK v2 call is direct:

1try (CloudWatchClient cw = CloudWatchClient.create()) {2    cw.putMetricData(PutMetricDataRequest.builder()3            .namespace("OrdersService")4            .metricData(MetricDatum.builder()5                    .metricName("OrdersPlaced")6                    .dimensions(Dimension.builder().name("Channel").value("web").build())7                    .unit(StandardUnit.COUNT)8                    .value(1.0)9                    .build())10            .build());11}

On EC2, run the CloudWatch agent alongside the app: it ships log files to CloudWatch Logs, publishes memory and disk metrics, and can accept EMF and StatsD. Write logs as JSON (Spring Boot 3.4+ supports structured logging: logging.structured.format.file=ecs with logging.file.name for a file the agent tails, or logging.structured.format.console where the platform collects standard output, as on Lambda or ECS) so Logs Insights can filter on fields.

For traces, AWS X-Ray records each request's path through services as segments and draws a service map. The X-Ray SDKs and daemon entered maintenance mode in February 2026, with end of support in February 2027; AWS recommends OpenTelemetry instead, via the AWS Distro for OpenTelemetry (ADOT) Java agent. CloudWatch Application Signals builds on that instrumentation: with the ADOT agent and the CloudWatch agent, it derives per-service latency, error and request metrics from traces and lets you define service level objectives (SLOs) on them.

A Spring Boot app on EC2 reports to CloudWatch4 steps
๐ŸšVan 1๐ŸงฎMeter-reader๐Ÿง‘โ€๐Ÿ”งRide-along helperโฒ๏ธGauges๐Ÿ““ Trip log
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Amazon CloudWatch, told the same way as the story.
  1. The light's red line is 80 and it needs 2 of the last 3 readings over it. Readings come in as 90, 60, 70. Is the light on?
  2. Van 1's engine got very hot for one minute, but the five-minute average looks calm. Which summary would have shown the hot minute?
  3. You fit a parcels gauge and tag every reading with the customer's name, so each customer gets their own gauge. Why is that a bad idea?
  4. You set up a helper to count every "flat tyre" line in the trip log, starting today. The log already has last month's flat tyres. What does the gauge show?
Answer every question to check.Passing marks Amazon CloudWatch as done.
Got the hang of Amazon CloudWatch? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ›ฐ๏ธ AWS in productionStep 6 of 7

โ† Previous on the path๐Ÿƒ AWS Step FunctionsNext on the path โ†’๐Ÿฆ AWS KMS and Secrets Manager