Sub topic 5
Publishing custom metrics
This chapter assumes you know what a namespace, a dimension, a statistic, and a period are, as covered in the earlier chapters. You should also be able to run AWS CLI commands against an account where you have cloudwatch:PutMetricData and cloudwatch:GetMetricStatistics permissions.
Why publish your own metrics
AWS services publish metrics such as CPUUtilization for you. They cannot see inside your application. Page load time, items in a queue you manage, orders placed per minute, and cache hit ratio are all facts only your code knows. A custom metric is a metric you publish yourself into a namespace you choose.
Custom namespaces cannot start with AWS/, because that prefix is reserved for AWS services. A common convention is a short application name such as MyApp.
Publishing one data point
The put-metric-data command sends data to CloudWatch. This example publishes a single page load time for the checkout service.
aws cloudwatch put-metric-data \
--namespace MyApp \
--metric-name PageLoadTime \
--dimensions Service=checkout \
--unit Milliseconds \
--value 230The command has no output on success. Each part of the call matters:
--namespace MyAppis the container. A metric is only found by looking in the namespace it was published to.--metric-name PageLoadTimeis the name within that namespace.--dimensions Service=checkoutadds a name/value pair that becomes part of the metric's identity.--unit Millisecondslabels the data. CloudWatch does not convert units, so use one unit consistently for a given metric.--value 230is the measurement.
Notice the dimension syntax. In put-metric-data, the shorthand is Name=Value pairs separated by commas, such as Service=checkout,Stage=prod. This differs from the Name=...,Value=... form that get-metric-statistics and put-metric-alarm use, which you will see below.
The metric does not need to be created first. The first call that mentions a new namespace, name, and dimension combination creates it. Data then takes a short time to appear in queries, so do not expect it instantly.
Dimensions define separate metrics
Every unique combination of namespace, metric name, and dimension set is its own metric. Publishing with Service=checkout and publishing with Service=search creates two metrics. Publishing with no dimensions creates a third, and it does not automatically add up the other two.
That last point surprises many people. CloudWatch does not aggregate across dimension values on its own. If you want a total for all services, you have two choices:
- Publish an additional data point with no dimensions (or with a dimension set you choose for the total).
- Use metric math at query time to add the individual metrics together.
Be careful with dimension values that have many possible values, such as a user ID or request ID. Each new value creates a new metric, which increases cost and makes the data hard to use. Use dimensions for a small, bounded set of values like service, environment, or region.
Reading the data back
To check that your data arrived, query it with get-metric-statistics. The example below reads CPU for an EC2 instance, which uses the same call you would use for a custom metric. Only the namespace, name, and dimensions change.
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-0123456789abcdef0 \
--start-time 2026-11-26T18:00:00Z \
--end-time 2026-11-26T19:00:00Z \
--period 300 \
--statistics Average MaximumThis returns the average and maximum CPU in 5-minute buckets over one hour. To read your custom metric, you would use --namespace MyApp, --metric-name PageLoadTime, and --dimensions Name=Service,Value=checkout. The dimensions you pass must match exactly the ones you published. If you published with Service=checkout and query without a dimension, you get no data, because that is a different metric.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Query returns no data points | Dimensions in the query differ from those published, or the time range is wrong | Run `aws cloudwatch list-metrics --namespace MyApp` to see the exact dimension sets |
| `AccessDenied` on publish | The caller lacks `cloudwatch:PutMetricData` | Add the permission to the role or user |
| Metric appears in the wrong region | CloudWatch is regional, and the CLI used a different default region | Pass `--region` explicitly or set the profile region |
| Data seems missing for old timestamps | Data older than the accepted window is rejected | Publish with a current timestamp |
| Totals do not match | Per-dimension metrics were not aggregated | Publish a total or use metric math |
The list-metrics command is the fastest way to debug a missing metric, because it shows exactly how each metric is identified.
Timestamps, batching, and limits
If you leave out --timestamp, CloudWatch uses the time it receives the call. You can set --timestamp yourself, but CloudWatch accepts data only within a window: up to two weeks in the past and up to two hours in the future. Anything outside that range is rejected.
Calling the API once per measurement is wasteful and slow at scale. There are two ways to send more per call:
- Multiple metrics per call. The
--metric-dataparameter takes a list, so one call can carry several data points. - Statistic sets. Instead of sending 1,000 raw values, send a summary: the sample count, sum, minimum, and maximum for a period. CloudWatch can then compute the average and totals from it.
The statistic set form looks like this:
aws cloudwatch put-metric-data \
--namespace MyApp \
--metric-name PageLoadTime \
--dimensions Service=checkout \
--unit Milliseconds \
--statistic-values Sum=46000,Minimum=120,Maximum=980,SampleCount=200The trade-off is that a statistic set loses detail. You can no longer calculate percentiles from the individual values, because CloudWatch never saw them. If you need percentiles such as p99, publish raw values, or use the --values and --counts form, which sends a list of values with how many times each occurred.
Resolution: standard and high
By default, a custom metric has standard resolution, meaning one-minute granularity. You can request high resolution by adding --storage-resolution 1, which stores data at one-second granularity. High-resolution metrics cost more and are mainly worth it for fast-moving signals where a minute is too coarse. Alarms on high-resolution metrics can evaluate at periods of 10 or 30 seconds.
The retention of data depends on its period. Data kept at one-second resolution is available for three hours, and is then rolled up into coarser periods. This is also true of standard metrics: one-minute data is kept for 15 days, five-minute data for 63 days, and one-hour data for 15 months.
Publishing from code
The CLI is useful for testing, but production applications publish through an SDK. Here is a complete Python example using boto3.
import boto3
from datetime import datetime, timezone
cloudwatch = boto3.client("cloudwatch", region_name="us-east-1")
cloudwatch.put_metric_data(
Namespace="MyApp",
MetricData=[
{
"MetricName": "PageLoadTime",
"Dimensions": [{"Name": "Service", "Value": "checkout"}],
"Timestamp": datetime.now(timezone.utc),
"Value": 230,
"Unit": "Milliseconds",
}
],
)In a real service, collect measurements in memory and send them in batches at an interval, rather than making a network call on every request. A failed publish should be logged and retried, but it should never block or crash the request that produced the measurement.
Cost considerations
Each unique metric (namespace, name, and dimension combination) is billed per month, and API calls to publish data are billed too. Two habits keep this under control: avoid unbounded dimension values, and batch data points into fewer calls. A later chapter covers cost in full.
Exercise
You publish PageLoadTime to namespace MyApp with the dimension Service=checkout. You then run get-metric-statistics for the same namespace and metric name, but with no dimensions, and get no data. Why, and how would you find out which dimension sets exist?
Show answer
A metric is identified by its namespace, name, and exact dimension set. Data published with Service=checkout belongs to a different metric from one with no dimensions, so the query matches nothing. Run aws cloudwatch list-metrics --namespace MyApp to see the exact dimension sets, then repeat the query with --dimensions Name=Service,Value=checkout.
Exercise
Your service handles 5,000 requests per minute and you need a p99 latency alarm. Should you publish one statistic set per minute or the raw values? Explain.
Show answer
Publish the raw values, or use the --values and --counts form. A statistic set holds only sample count, sum, minimum, and maximum, so CloudWatch cannot calculate percentiles from it. The --values and --counts form keeps the distribution while still sending fewer data points than one call per request.