Skip to content

Observability

Alarms

An alarm watches a CloudWatch metric of one resource, such as a function's error rate or a database's free storage, and notifies you when it crosses a threshold. You define alarms on the resource in your config, and the deploy creates them in CloudWatch in your AWS account.

  • Without the Console, an alarm delivers to Slack, Microsoft Teams, Discord, email or a webhook straight from your AWS account. See Notification targets.
  • With the Console, an alarm can also deliver to a Console alert channel (console-channel) or the Stacktape Slack app (slack-app), and a firing alarm opens an incident. A deploy without a Console connection refuses console-channel and slack-app targets.

A good start for a production stage: an error-rate alarm on each public API, function or load balancer, and CPU and free-storage alarms on each database. Runtime exceptions are better caught by error tracking, and spend by budgets.

Supported resources

Stacktape supports inline alarms on five resource types. Each resource accepts a specific set of trigger types:

ResourceConfig propertyAccepted alarm triggers
Lambda functionalarmslambda-error-rate, lambda-duration
Relational databasealarmsdatabase-cpu-utilization, database-connection-count, database-read-latency, database-write-latency, database-free-storage, database-free-memory
HTTP API Gatewayalarmshttp-api-gateway-error-rate, http-api-gateway-latency
Application Load Balanceralarmsapplication-load-balancer-error-rate, application-load-balancer-unhealthy-targets, application-load-balancer-custom
SQS queuealarmssqs-queue-received-messages-count, sqs-queue-not-empty

Trigger types

Lambda function triggers

Trigger typeThreshold propertyUnitDefault statisticDefault comparison
lambda-error-ratethresholdPercent%n/aGreaterThanThreshold
lambda-durationthresholdMillisecondsmsavgGreaterThanThreshold

Relational database triggers

Trigger typeThreshold propertyUnitDefault statisticDefault comparison
database-cpu-utilizationthresholdPercent%avgGreaterThanThreshold
database-connection-countthresholdCountcountavgGreaterThanThreshold
database-read-latencythresholdSecondssavgGreaterThanThreshold
database-write-latencythresholdSecondssavgGreaterThanThreshold
database-free-storagethresholdMBMBminLessThanThreshold
database-free-memorythresholdMBMBavgLessThanThreshold
Note:

For threshold-based triggers that expose comparisonOperator, the default is GreaterThanThreshold, except database-free-storage and database-free-memory, which default to LessThanThreshold — the alarm fires when the metric drops below the threshold.

HTTP API Gateway triggers

Trigger typeThreshold propertyUnitDefault statisticDefault comparison
http-api-gateway-error-ratethresholdPercent%n/aGreaterThanThreshold
http-api-gateway-latencythresholdMillisecondsmsavgGreaterThanThreshold

Application Load Balancer triggers

Trigger typeThreshold propertyUnitDefault statisticDefault comparison
application-load-balancer-error-ratethresholdPercent%n/aGreaterThanThreshold
application-load-balancer-unhealthy-targetsthresholdPercent%n/aGreaterThanThreshold
application-load-balancer-customthreshold (+ metric)variesavgGreaterThanThreshold

The application-load-balancer-custom trigger lets you alarm on additional ALB CloudWatch metrics beyond the built-in error-rate and unhealthy-targets triggers. See the API reference for supported properties.

The application-load-balancer-unhealthy-targets trigger also accepts an optional onlyIncludeTargets array to scope monitoring to specific container services behind the load balancer.

SQS queue triggers

Trigger typeThreshold propertyUnitDefault statisticDefault comparison
sqs-queue-received-messages-countthresholdCountcountavgGreaterThanThreshold
sqs-queue-not-empty(none)———

The sqs-queue-not-empty trigger has no configurable threshold — it fires whenever the queue has any unprocessed messages (visible, in-flight, messages received, or messages sent).

Customizing comparison and statistic

Most triggers accept two optional overrides:

  • comparisonOperator — how the metric is compared to the threshold. Options: GreaterThanThreshold, GreaterThanOrEqualToThreshold, LessThanThreshold, LessThanOrEqualToThreshold. The default varies by trigger type (see tables above).
  • statistic — how metric values within each evaluation period are aggregated. Options: avg, min, max, sum, p90, p95, p99. Available on triggers that aggregate over time (duration, latency, counts, utilization, storage, memory). Error-rate triggers compute the ratio directly and don't expose a statistic override.

Defining alarms on resources

Stacktape alarms are defined inline on individual resources using the alarms property. Each alarm specifies a trigger (what to monitor and the threshold) and optionally an evaluation window and notificationChannels.

Lambda function alarms

A Lambda function accepts lambda-error-rate and lambda-duration triggers. The following example fires when more than 5% of invocations fail:

TypeScript
export default defineConfig(() => {  const api = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({      entryfilePath: './src/api.ts'    }),    alarms: [      {        trigger: {          type: 'lambda-error-rate',          properties: {            thresholdPercent: 5          }        }      }    ]  });  return { resources: { api } };});

Database alarms

A relational database supports six trigger types covering CPU, storage, memory, connections, and I/O latency. The following example combines a CPU alarm with a free-storage alarm and tunes the evaluation window to avoid firing on brief spikes:

TypeScript
export default defineConfig(() => {  const mainDb = new RelationalDatabase({    credentials: {      masterUserPassword: '$Secret(db-password)'    },    engine: new RdsEnginePostgres({      version: '16',      primaryInstance: { instanceSize: 'db.t4g.micro' }    }),    alarms: [      {        trigger: {          type: 'database-cpu-utilization',          properties: { thresholdPercent: 80 }        },        evaluation: {          period: 300,          evaluationPeriods: 3,          breachedPeriods: 2        }      },      {        trigger: {          type: 'database-free-storage',          properties: { thresholdMB: 1000 }        }      }    ]  });  return { resources: { mainDb } };});

In this example, the CPU alarm evaluates three 5-minute periods and only fires if at least two of them breach 80%. The free-storage alarm uses the defaults (one 60-second period, fires after a single breached period) — appropriate for storage pressure that you want to catch right away.

Multiple alarms with notifications

This example shows a Lambda function with two alarms, each sending notifications to a Slack channel when triggered:

TypeScript
export default defineConfig(() => {  const api = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({      entryfilePath: './src/api.ts'    }),    alarms: [      {        trigger: {          type: 'lambda-error-rate',          properties: { thresholdPercent: 5 }        },        description: 'API error rate exceeds 5%',        evaluation: {          period: 60,          evaluationPeriods: 3,          breachedPeriods: 2        },        notificationChannels: [          {            type: 'slack',            properties: {              conversationId: 'C01234ABCDE',              accessToken: '$Secret(slack-bot-token)'            }          }        ]      },      {        trigger: {          type: 'lambda-duration',          properties: {            thresholdMilliseconds: 5000,            statistic: 'p95'          }        },        description: 'P95 duration exceeds 5s'      }    ]  });  return { resources: { api } };});

The description property adds context to notification messages. The statistic: 'p95' override on the duration alarm fires only when the 95th percentile exceeds the threshold, filtering out occasional slow invocations.

Evaluation windows

Stacktape alarm evaluation windows control how CloudWatch evaluates the metric before firing the alarm. The evaluation property prevents short-lived spikes from triggering false alerts while still catching sustained problems.

Three settings control the evaluation:

PropertyDefaultDescription
period60Duration of one evaluation window in seconds. Must be a multiple of 60.
evaluationPeriods1How many recent periods to look at.
breachedPeriods1How many of those periods must breach the threshold to fire. Must be ≤ evaluationPeriods.

How it works: At the end of each period, CloudWatch checks whether the metric breached the threshold during that period. If breachedPeriods out of the last evaluationPeriods periods are in breach, the alarm fires.

Example: With period: 300, evaluationPeriods: 5, breachedPeriods: 3, CloudWatch looks at the last 25 minutes (5 × 300s). If the threshold was breached in at least 3 of those 5 periods, the alarm fires. This pattern catches sustained issues while ignoring isolated spikes.

Tip:

For production error-rate alarms, start with evaluationPeriods: 3 and breachedPeriods: 2 at a 60-second period. This gives you a 3-minute detection window that filters out single-period noise while still alerting within minutes.

For database storage alarms, the defaults (period: 60, evaluationPeriods: 1, breachedPeriods: 1) are usually appropriate — you want to know immediately when storage is running low.

Notification targets

Stacktape alarms can send notifications to one or more targets when they fire and when they recover. Configure the notificationChannels array on each alarm to specify where alerts are delivered. Supported target types include MS Teams, Slack, email, Discord, and webhooks.

Inline targets (slack, ms-teams, discord, email and webhook) are sent by the stack's own service Lambda, from your AWS account. The Lambda reads $Secret and secure SSM values when it sends the notification. Tokens, webhook URLs, signing secrets and headers are never sent to Stacktape. Email goes through Amazon SES in your account from the sender address. Microsoft Teams, Discord and webhook receivers get the same request format as from a Console alert channel. A webhook request carries the alarm's EventBridge event ID as id, so a receiver can drop a repeated delivery.

Each target receives one message when the alarm fires and one when it returns to OK after firing. A new alarm's first evaluation to OK sends nothing. If a target fails, the Lambda retries it without resending the targets that already received the message. Muting an incident in the Console does not silence inline targets, because the Console does not deliver them.

To reuse a named Console alert channel, add a console-channel reference to the alarm's notificationChannels. The Console delivers console-channel and slack-app targets with the credentials it keeps:

YAML
notificationChannels:  - type: console-channel    properties:      channelName: production-alerts

A firing alarm also opens an incident. Configure notification rules to route incident alerts to your team. Choose the delivery paths you need to avoid duplicate notifications.

Alarm description

Use the optional description property on an alarm to include a custom message in notification messages and the AWS console. This is helpful when you have multiple alarms on the same resource — the description makes it clear what the alarm means without looking up the config.

History tracking

The includeInHistory property controls whether alarm state changes should appear in monitoring history. It defaults to true. Set it to false on noisy development-stage alarms that would clutter the history view. Such an alarm is not reported to the Console, so it opens no incident. Its inline targets are still notified. console-channel and slack-app targets need history, and the deploy refuses an alarm that combines them with includeInHistory: false.

What leaves your AWS account

What leaves your AWS account compares every feature in one table.

When an alarm with history changes state, the stack's service Lambda sends the Console the alarm event: the alarm name and trigger type, the project, stage and region, the new state and its time, the alarm's description, ARN and condition (comparison, statistic and unit), the stack name, the affected resource with its AWS console link, a link to the alarm, and the EventBridge event ID. It also sends the console-channel names and resolved slack-app channel IDs, which the Console delivers. Inline targets and their settings stay in your account.

Migrating legacy Console alarm rules

The Console no longer creates or edits alarm rules. Existing rules appear under Legacy alarm rules on the Alarms page. They keep applying to every matching resource until you exclude them on that resource or delete them.

Run stacktape alarm export to print those rules as config entries, including their project and stage scope. Add each entry to the alarms list of every resource it should monitor, and preserve stage-specific behavior with stage-based configuration.

On the same resources, list the rule's name in disabledGlobalAlarms. Without it the legacy rule still applies next to the alarm you added, and the resource gets two alarms that notify twice. Deploy each affected stage, check the alarms, and then delete the legacy rule in the Console. The alarm export guide shows a complete example.

Viewing alarm states

CLI

Use stacktape alarm list to inspect alarms from the CLI. See the CLI reference for flags and output details.

stacktape alarm list --stage production --region eu-west-1
Note:

INSUFFICIENT_DATA typically means the resource hasn't produced enough metric data yet — common right after deployment or for resources with low traffic. It does not indicate a configuration error.

Console

The Console's Alarms page shows deployed alarms and their states across projects and stages. Open an alarm to inspect its state history. Configure thresholds and evaluation windows in the stack config, then deploy to apply them.

Alarms as event triggers

Stacktape alarm state changes can be used as event sources for Lambda functions, enabling automated remediation workflows. See alarms as triggers for configuration details.

API reference

AlarmDefinition8 properties
  • nameRequiredstring

    A unique name for this alarm (e.g., api-error-rate, db-cpu-high).

  • triggerRequired

    The metric and threshold that fires this alarm.

  • Custom alarm description used in notification messages and the AWS console.

  • evaluationAlarmEvaluation

    How long and how often to evaluate the metric before triggering.

  • forServicesstring[]

    Only activate this alarm for these services. If omitted, applies to all services.

  • forStagesstring[]

    Only activate this alarm for these stages (e.g., production). If omitted, applies to all stages.

  • includeInHistorybooleanDefault true

    Whether alarm state changes should appear in monitoring history.

  • Where to send notifications when the alarm fires and when it recovers.

Alarms FAQ

How much do CloudWatch alarms cost?

AWS charges per alarm metric per month. Stacktape alarms use standard resolution, so their periods are multiples of 60 seconds. For most stacks, alarms cost a small fraction of compute and database spend. See CloudWatch pricing.

Can I set different thresholds for production and development?

Yes. Use stage-based configuration to pick thresholds or leave alarms out for a stage, then deploy each affected stage.

How do I test that an alarm works?

Deploy it, check it with stacktape alarm list, then set a threshold your current traffic breaches (for example thresholdPercent: 0 on an error-rate alarm), deploy and wait one evaluation period. Check that the alert arrives, then restore the real threshold.

Can I alarm on a custom metric my application publishes?

Not from the Stacktape config. Each resource type has a fixed set of triggers; only application-load-balancer-custom takes any ALB metric by name. For your own metrics, create the alarm in CloudWatch or add it as raw CloudFormation in your config's overrides.