Sub topic 16
Monitoring endpoints with Synthetics canaries
This chapter assumes you can create a metric alarm with an SNS action (covered in the alarm chapters). It also assumes you can run the AWS CLI and know basic IAM roles and S3 buckets. You don't need to know Node.js well, because the script is short.
Why monitor from the outside
Metrics such as CPU or memory describe a resource from the inside. They can all look healthy while users get errors. A certificate expires, a DNS record is wrong, or a load balancer routes to a broken target. None of these show up as a CPU spike.
A CloudWatch Synthetics canary is a script that runs on a schedule and acts like a user or client. It calls your endpoint, checks the response, and publishes the result as metrics. Because the check runs even when nobody is using your site, you learn about an outage before a customer reports it.
How a canary works
A canary is a script that Synthetics runs for you on AWS Lambda. Each run follows the same path.
Each run produces three kinds of output:
- Metrics in the
CloudWatchSyntheticsnamespace, with the dimensionCanaryName. - Artifacts in an S3 bucket you choose. These include logs, HTTP archive (HAR) files, and screenshots for browser canaries.
- Log events in a log group named
/aws/lambda/cwsyn-<canary-name>-<id>.
The main metrics are in this table.
| Metric | Meaning | Typical statistic |
|---|---|---|
| `SuccessPercent` | Percentage of runs in the period that passed | Average |
| `Duration` | Run time in milliseconds | Average or p99 |
| `Failed` | Count of failed runs | Sum |
Canary types
You pick a blueprint or write your own script. These are the common choices.
- Heartbeat monitoring loads one URL in a headless browser and takes a screenshot.
- API canary calls REST endpoints and checks status codes and bodies.
- Broken link checker crawls a page and tests each link.
- GUI workflow clicks through a multi-step user journey, such as logging in.
- Visual monitoring compares screenshots against a baseline.
Runtimes exist for Node.js with Puppeteer and for Python with Selenium. Runtime versions are retired over time. List the current ones before you create a canary:
aws synthetics describe-runtime-versions \
--query "RuntimeVersions[].VersionName"Writing the script
This script checks a health endpoint and fails the run if the status is not 200. Replace the host name with one you own. executeStep records a named step in the run report, and any thrown error marks the run as failed.
const synthetics = require('Synthetics');
const log = require('SyntheticsLogger');
const https = require('https');
const checkHealth = async function () {
const statusCode = await new Promise((resolve, reject) => {
const req = https.request(
{ hostname: 'www.example.com', path: '/health', method: 'GET', timeout: 10000 },
(res) => {
res.resume();
res.on('end', () => resolve(res.statusCode));
}
);
req.on('timeout', () => req.destroy(new Error('Request timed out')));
req.on('error', reject);
req.end();
});
log.info('Health endpoint returned ' + statusCode);
if (statusCode !== 200) {
throw new Error('Expected 200 but got ' + statusCode);
}
};
exports.handler = async () => {
return await synthetics.executeStep('checkHealth', checkHealth);
};The Node.js runtimes expect the file at nodejs/node_modules/index.js inside the zip, and the handler name is index.handler. Package and upload it:
mkdir -p nodejs/node_modules
cp index.js nodejs/node_modules/index.js
zip -r canary.zip nodejs
aws s3 cp canary.zip s3://my-canary-code-111122223333/canary.zipCreating and starting the canary
The canary needs an execution role. The role must allow Lambda to assume it, write to the artifact bucket, write logs, and publish metrics to the CloudWatchSynthetics namespace. The console can create this role for you. With the CLI you create it yourself.
aws synthetics create-canary \
--name checkout-health \
--code S3Bucket=my-canary-code-111122223333,S3Key=canary.zip,Handler=index.handler \
--artifact-s3-location s3://my-canary-artifacts-111122223333/checkout-health/ \
--execution-role-arn arn:aws:iam::111122223333:role/CanaryExecutionRole \
--schedule Expression="rate(5 minutes)" \
--runtime-version syn-nodejs-puppeteer-9.1 \
--run-config TimeoutInSeconds=60 \
--success-retention-period-in-days 14 \
--failure-retention-period-in-days 31
aws synthetics start-canary --name checkout-healthReplace the runtime version with one returned by describe-runtime-versions. A new canary stays in the READY state until you start it. Check progress with aws synthetics get-canary-runs --name checkout-health.
The schedule can be rate(5 minutes), a cron expression, or a one-time run. The run timeout must be shorter than the schedule interval. Otherwise runs can overlap.
Alarming on a canary
Canary metrics are ordinary metrics, so the alarm works as you already know it. Two choices matter here.
First, set --treat-missing-data breaching. If the canary stops running because it was stopped, lost permissions, or hit a Lambda problem, no data points arrive. Under the default missing setting the alarm would stay quiet. Treating missing data as breaching makes a silent canary raise an alarm.
Second, avoid alarming on a single failed run. Networks drop a request now and then. Requiring two failures out of three keeps the alarm useful.
aws cloudwatch put-metric-alarm \
--alarm-name checkout-health-canary \
--namespace CloudWatchSynthetics \
--metric-name SuccessPercent \
--dimensions Name=CanaryName,Value=checkout-health \
--statistic Average \
--period 300 \
--evaluation-periods 3 \
--datapoints-to-alarm 2 \
--threshold 100 \
--comparison-operator LessThanThreshold \
--treat-missing-data breaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:ops-alertsThe period of 300 seconds matches the five-minute schedule, so each period holds one data point. If the period were shorter than the schedule, some periods would be empty and breaching would trigger false alarms.
Common errors
- The run fails with an access error. The execution role lacks write access to the artifact bucket or
cloudwatch:PutMetricData. Check the run's log file in the S3 artifacts. - The canary stays in READY. You created it but did not call
start-canary. - The endpoint is private. A canary outside your VPC cannot reach private addresses. Attach the canary to a VPC with subnets and security groups, and give it a route to the internet or VPC endpoints for S3 and CloudWatch.
- The script passes when it should fail. HTTP libraries often return a 500 as a normal response. Check the status code and body yourself, as the script above does.
- The timeout equals the schedule. Leave a margin so one slow run does not collide with the next.
Cost considerations
Canaries are billed per run, and each run also uses S3 storage, log storage, and the alarm. Cost grows with run frequency, the number of canaries, and the retention you set. A one-minute schedule costs about five times as much as a five-minute one. Set artifact retention to what you need, and add an S3 lifecycle rule on the artifact bucket for older objects.
Exercise
A canary runs every 10 minutes. You create an alarm on SuccessPercent with a 60-second period, 3 evaluation periods, and treat-missing-data set to breaching. The endpoint is healthy, yet the alarm goes to ALARM. Why, and how do you fix it?
Show answer
With a 10-minute schedule and a 60-second period, nine of every ten periods contain no data point. Missing data is treated as breaching, so the alarm fires even though every run passes. Set the alarm period to 600 seconds so each period contains one run. Alternatively, change the schedule to match the period.
Exercise
Name the three places a canary run writes its output, and say which one holds screenshots.
Show answer
It writes metrics to the CloudWatchSynthetics namespace, log events to a /aws/lambda/cwsyn-* log group, and artifacts to the S3 bucket you configured. Screenshots are stored in the S3 artifacts.