# AnomalyDetectionAlarm

CloudWatch Alarm that uses anomaly detection to trigger alarms.

This alarm type is specifically designed for use with anomaly detection operators
like LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD.

Extends: Construct › Resource › AlarmBase › Alarm › AnomalyDetectionAlarm
Implements: IResource, IAlarm, IAlarmRule, IEnvironmentAware, IAlarmRef, IConstruct, IDependable

- Source: [`aws-cloudwatch/lib/alarm.ts`](https://github.com/aws/aws-cdk/blob/v2.276.0/packages/aws-cdk-lib/aws-cloudwatch/lib/alarm.ts#L639)
- Type last changed: v2.197.0 · 21 May 2025

## Example

```ts
// Create a metric
const metric = new cloudwatch.Metric({
  namespace: 'AWS/EC2',
  metricName: 'CPUUtilization',
  statistic: 'Average',
  period: Duration.hours(1), // Alarm will use the metric's period
});

// Create an anomaly detection alarm
const alarm = new cloudwatch.AnomalyDetectionAlarm(this, 'AnomalyAlarm', {
  metric: metric,
  evaluationPeriods: 1,

  // Number of standard deviations for the band (default: 2)
  stdDevs: 2,
  // Alarm outside on either side of the band, or just below or above it (default: outside)
  comparisonOperator: cloudwatch.ComparisonOperator.LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
  alarmDescription: 'Alarm when metric is outside the expected band',
});
```

## Initializer

```ts
new AnomalyDetectionAlarm(scope: Construct, id: string, props: AnomalyDetectionAlarmProps)
```

## Construct Props

- `actionsEnabled`: boolean = true — Whether the actions for this alarm are enabled.

- `alarmDescription`: string — Description for the alarm.

  **Default:** No description

- `alarmName`: string — Name of the alarm.

  **Default:** Automatically generated name

- `comparisonOperator`: [ComparisonOperator](/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.ComparisonOperator.html) — Comparison operator to use to check if metric is breaching.

  **Default:** LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD

  Must be one of the anomaly detection operators:
  - LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD
  - GREATER_THAN_UPPER_THRESHOLD
  - LESS_THAN_LOWER_THRESHOLD

- `datapointsToAlarm`: number = ``evaluationPeriods`` — The number of datapoints that must be breaching to trigger the alarm.

  This is used only if you are setting an "M
  out of N" alarm. In that case, this value is the M. For more information, see Evaluating an Alarm in the Amazon
  CloudWatch User Guide.

- `evaluateLowSampleCountPercentile`: string — Specifies whether to evaluate the data and potentially change the alarm state if there are too few data points to be statistically significant.

  **Default:** Not configured.

  Used only for alarms that are based on percentiles.

- `evaluationPeriods`: number (required) — The number of periods over which data is compared to the specified threshold.

- `metric`: [IMetric](/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IMetric.html) (required) — The metric to add the alarm on.

  Metric objects can be obtained from most resources, or you can construct
  custom Metric objects by instantiating one.

- `period`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) — Use `metric.with({ period: ... })` to encode the period into the Metric object

  **Default:** The period from the metric

  Cannot be used with `MathExpression` objects.

- `statistic`: string — Use `metric.with({ statistic: ... })` to encode the period into the Metric object

  **Default:** The statistic from the metric

  Can be one of the following:

  - "Minimum" | "min"
  - "Maximum" | "max"
  - "Average" | "avg"
  - "Sum" | "sum"
  - "SampleCount | "n"
  - "pNN.NN"

  Cannot be used with `MathExpression` objects.

- `stdDevs`: number = 2 — The number of standard deviations to use for the anomaly detection band.

  The higher the value, the wider the band.

  - Must be greater than 0. A value of 0 or negative values would not make sense in the context of calculating standard deviations.
  - There is no strict maximum value defined, as standard deviations can theoretically extend infinitely. However, in practice, values beyond 5 or 6 standard deviations are rarely used, as they would result in an extremely wide anomaly detection band, potentially missing significant anomalies.

- `treatMissingData`: [TreatMissingData](/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.TreatMissingData.html) = TreatMissingData.Missing — Sets how this alarm is to handle missing data points.

## Properties

- `alarmArn`: string — ARN of this alarm.

- `alarmName`: string — Name of this alarm.

- `alarmRef`: [AlarmReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_cloudwatch.AlarmReference.html) — A reference to a Alarm resource.

- `ANOMALY_DETECTION_NO_THRESHOLD`: number (static) — Conventional value for the threshold property when creating anomaly detection alarms.

  Anomaly detection alarms don't have numbered threshold. Instead, they have a dynamically
  calculated threshold based on the metric math expression that contains a metric expression.

  The `threshold` property is required, but the value is ignored. This
  constant has the value 0, and has a symbolic name to indicate why the
  threshold is 0. You can use `new AnomalyDetectionAlarm()` to avoid having to pass
  the `threshold` property at all.

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) — The environment this resource belongs to.

  For resources that are created and managed in a Stack (those created by
  creating new class instances like `new Role()`, `new Bucket()`, etc.), this
  is always the same as the environment of the stack they belong to.

  For referenced resources (those obtained from referencing methods like
  `Role.fromRoleArn()`, `Bucket.fromBucketName()`, etc.), they might be
  different than the stack they were imported into.

- `metric`: [IMetric](/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IMetric.html) — The metric object this alarm was based on.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) — The tree node.

- `PROPERTY_INJECTION_ID`: string (static) — Uniquely identifies this class.

- `stack`: [Stack](/cdk/api/v2/docs/aws-cdk-lib.Stack.html) — The stack in which this resource is defined.

## Methods

- `addAlarmAction(...actions: IAlarmAction[]): void` — Trigger this action if the alarm fires.

  Typically SnsAction or AutoScalingAction.

- `addAlarmMuteRule(id: string, options: AlarmMuteRuleOptions): AlarmMuteRule` — Add an alarm mute rule.

- `addInsufficientDataAction(...actions: IAlarmAction[]): void` — Trigger this action if there is insufficient data to evaluate the alarm.

  Typically SnsAction or AutoScalingAction.

- `addOkAction(...actions: IAlarmAction[]): void` — Trigger this action if the alarm returns from breaching state into ok state.

  Typically SnsAction or AutoScalingAction.

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  When set, any cross-stack reference to this resource will use the specified
  mechanism instead of the global default determined by the
  `@aws-cdk/core:defaultCrossStackReferences` context key. This is useful for
  selectively weakening specific references to avoid the "deadly embrace" problem
  without changing the app-wide default.

  **Parameters**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — Apply the given removal policy to this resource.

  The Removal Policy controls what happens to this resource when it stops
  being managed by CloudFormation, either because you've removed it from the
  CDK application or because you've made a change that requires the resource
  to be replaced.

  The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
  account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).

- `fromAlarmArn(scope: Construct, id: string, alarmArn: string): IAlarm` (static) — Import an existing CloudWatch alarm provided an ARN.

  **Parameters**

  - `scope` — The parent creating construct (usually `this`).
  - `id` — The construct's name.
  - `alarmArn` — Alarm ARN (i.e. arn:aws:cloudwatch:<region>:<account-id>:alarm:Foo).

- `fromAlarmName(scope: Construct, id: string, alarmName: string): IAlarm` (static) — Import an existing CloudWatch alarm provided an Name.

  **Parameters**

  - `scope` — The parent creating construct (usually `this`).
  - `id` — The construct's name.
  - `alarmName` — Alarm Name.

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  Use this method instead of `instanceof` to properly detect `Construct`
  instances, even when the construct library is symlinked.

  Explanation: in JavaScript, multiple copies of the `constructs` library on
  disk are seen as independent, completely different libraries. As a
  consequence, the class `Construct` in each copy of the `constructs` library
  is seen as a different class, and an instance of one class will not test as
  `instanceof` the other class. `npm install` will not create installations
  like this, but users may manually symlink construct libraries together or
  use a monorepo tool: in those cases, multiple copies of the `constructs`
  library can be accidentally installed, and `instanceof` will behave
  unpredictably. It is safest to avoid using `instanceof`, and using
  this type-testing method instead.

  **Parameters**

  - `x` — Any object.

  **Returns:** true if `x` is an object created from a class which extends `Construct`.

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `renderAlarmRule(): string` — AlarmRule indicating ALARM state for Alarm.

- `toAnnotation(): HorizontalAnnotation` — Turn this alarm into a horizontal annotation.

  This is useful if you want to represent an Alarm in a non-AlarmWidget.
  An `AlarmWidget` can directly show an alarm, but it can only show a
  single alarm and no other metrics. Instead, you can convert the alarm to
  a HorizontalAnnotation and add it as an annotation to another graph.

  This might be useful if:

  - You want to show multiple alarms inside a single graph, for example if
    you have both a "small margin/long period" alarm as well as a
    "large margin/short period" alarm.

  - You want to show an Alarm line in a graph with multiple metrics in it.

- `toString(): string` — Returns a string representation of this construct.

- `with(...mixins: IMixin[]): IConstruct` — Applies one or more mixins to this construct.

  Mixins are applied in order. The list of constructs is captured at the
  start of the call, so constructs added by a mixin will not be visited.
  Use multiple `with()` calls if subsequent mixins should apply to added
  constructs.
