Sub topic 11
Testing patterns and monitoring rules
This chapter covers how to check that an event pattern matches the events you expect before you depend on it, and how to watch rules once they are running. It assumes you can create a bus, a rule, and a target with the AWS CLI. It also assumes you can read JSON and know how CloudWatch alarms notify you through SNS.
Why a rule that does not match is hard to notice
An event that matches no rule is dropped without an error. The producer's PutEvents call still succeeds, and no target is invoked. A typo in a pattern, a wrong bus name, or a number sent as a string all look like silence. Silence is the hardest failure to debug, so you test patterns before attaching them and monitor rules after.
Testing has three layers, and each catches a different class of mistake:
- Pattern test. Check the pattern against a sample event without creating any resources.
- End-to-end test. Publish a real event to a real bus and confirm that it reaches a target.
- Monitoring. Use metrics and alarms to catch problems that appear later, such as failing targets or changed producers.
Testing a pattern with test-event-pattern
The test-event-pattern command evaluates a pattern against one event and reports whether they match. It needs no bus, rule, or target, so it costs nothing and has no side effects.
Save the pattern from earlier chapters as pattern.json. It matches OrderPlaced events from com.example.orders where detail.amount is at least 100 and detail.status is not test.
{
"source": ["com.example.orders"],
"detail-type": ["OrderPlaced"],
"detail": {
"amount": [{ "numeric": [">=", 100] }],
"status": [{ "anything-but": ["test"] }]
}
}Now save a sample event as sample-event.json. The event you pass must have the full envelope that EventBridge delivers: id, account, source, time, region, resources, and detail-type, plus detail.
{
"version": "0",
"id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718",
"detail-type": "OrderPlaced",
"source": "com.example.orders",
"account": "123456789012",
"time": "2026-11-26T18:00:00Z",
"region": "us-east-1",
"resources": [],
"detail": {
"orderId": "1001",
"amount": 250,
"status": "new"
}
}Run the test:
aws events test-event-pattern --event-pattern file://pattern.json --event file://sample-event.jsonThe command prints {"Result": true} when the event matches and {"Result": false} when it does not. Note that detail is a JSON object here. In PutEvents it is a string containing JSON. The service parses that string before matching, so the two forms behave the same once the event is on the bus.
Build a table of cases
One passing event proves little. Test the boundaries, and include events that should not match. For the pattern above, a useful set looks like this:
| Case | Change to the sample event | Expected result |
|---|---|---|
| Baseline | None | true |
| Boundary | `amount` set to `100` | true |
| Below threshold | `amount` set to `99` | false |
| Excluded status | `status` set to `"test"` | false |
| Missing field | `status` removed | false |
| Number as string | `amount` set to `"250"` | false |
| Wrong case | `detail-type` set to `"orderplaced"` | false |
Two of these rows surprise people. First, anything-but only matches when the field exists, so an event with no status field does not match, even though its status is not test. If you want to accept missing fields, you need an exists: false alternative in an $or list. Second, numeric only matches JSON numbers. A producer that serializes 250 as "250" silently stops matching.
Script the cases
Keep each case as a file and loop over them, so a pattern change can be re-verified in seconds. This script expects files named match-*.json (should match) and nomatch-*.json (should not match).
#!/usr/bin/env bash
set -u
fail=0
for f in cases/match-*.json cases/nomatch-*.json; do
want=true
case "$(basename "$f")" in nomatch-*) want=false ;; esac
got=$(aws events test-event-pattern \
--event-pattern file://pattern.json \
--event "file://$f" \
--query Result --output text | tr 'A-Z' 'a-z')
if [ "$got" != "$want" ]; then
echo "FAIL $f: expected $want, got $got"
fail=1
fi
done
exit $failThis runs in a continuous integration job without a deployed stack, since test-event-pattern only needs credentials and the events:TestEventPattern permission.
Testing end to end with a logging target
After the pattern passes, create the rule on the real bus. During development, add an Amazon CloudWatch Logs log group as a target, so you can see the exact event that arrives. Use the same two commands as in earlier chapters, with a targets.json that points at the log group's ARN.
aws events put-rule --name high-value-orders --event-bus-name orders-bus --event-pattern file://pattern.json
aws events put-targets --rule high-value-orders --event-bus-name orders-bus --targets file://targets.jsonThen publish a real event and read the log group:
aws events put-events --entries '[{"Source":"com.example.orders","DetailType":"OrderPlaced","Detail":"{\"orderId\":\"1002\",\"amount\":250,\"status\":\"new\"}","EventBusName":"orders-bus"}]'A CloudWatch Logs target needs a resource policy on the log group that lets events.amazonaws.com and delivery.logs.amazonaws.com write to it. The console adds this policy for you. With the CLI or infrastructure as code you must create it with aws logs put-resource-policy.
If the event does not show up, work through these checks in order:
- Did
put-eventsreturnFailedEntryCountof 0? Failed entries mean the event never reached the bus. - Is
EventBusNamein the entry the same bus the rule is on? An entry with no bus name goes to the default bus. - Does the rule's state say
ENABLED? Check withaws events describe-rule --name high-value-orders --event-bus-name orders-bus. - Does the exact event, with
detailparsed, passtest-event-pattern? - Does the target have permission to receive the event?
Monitoring rules with CloudWatch metrics
EventBridge publishes metrics to the AWS/Events namespace, with dimensions for the rule and, for rules on a custom bus, the bus. List the metrics that exist in your account before building alarms, because that shows the exact dimension names.
aws cloudwatch list-metrics --namespace AWS/Events --metric-name FailedInvocationsThese are the metrics you will use most:
| Metric | What it counts | Typical use |
|---|---|---|
| `TriggeredRules` | Rules that matched an event and fired | Confirm a rule is firing at the expected rate |
| `Invocations` | Attempts to invoke a target | Track delivery volume |
| `FailedInvocations` | Invocations that failed permanently, after retries are exhausted | Alarm on this |
| `ThrottledRules` | Rule executions that were throttled | Detect load beyond limits |
| `DeadLetterInvocations` | Events successfully sent to a dead-letter queue | Know that retries gave up |
| `InvocationsFailedToBeSentToDlq` | Events that could not be written to the DLQ | Alarm on this, because the event is lost |
FailedInvocations does not count attempts that were retried and then succeeded. A target that is flaky but recovers will not raise it. To see that behavior, look at the retry-attempt metrics or compare Invocations with the target service's own metrics.
Metrics only appear after something happens. A rule that never matches has no TriggeredRules datapoints at all, which is different from a datapoint of zero. Set the alarm's missing-data handling deliberately.
Alarm on permanent failures
This alarm sends an SNS notification when any invocation for the rule fails permanently within a five-minute window. Replace the dimensions with the ones that list-metrics showed you.
aws cloudwatch put-metric-alarm \
--alarm-name high-value-orders-failed-invocations \
--namespace AWS/Events \
--metric-name FailedInvocations \
--dimensions Name=RuleName,Value=high-value-orders Name=EventBusName,Value=orders-bus \
--statistic Sum \
--period 300 \
--evaluation-periods 1 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:123456789012:ops-alertsnotBreaching is right here because no failures means no datapoints, and that is a healthy state. For a rule that should always fire, such as one driven by a steady stream of orders, alarm on TriggeredRules falling below a floor and use breaching for missing data. That catches a producer that stopped publishing or started sending a changed event shape.
Watch the dead-letter queue
If the target in the previous chapter has a dead-letter queue, the queue is the best record of what failed. Alarm on its depth with the SQS metric ApproximateNumberOfMessagesVisible in the AWS/SQS namespace, using the QueueName dimension. Each message carries attributes such as ERROR_CODE, ERROR_MESSAGE, and RETRY_ATTEMPTS, which tell you why delivery failed. An AccessDenied error code points at permissions. A throttling error points at the target's capacity.
Common errors
- Testing with an event that has
detailas a string. Intest-event-patternthe event is plain JSON, sodetailmust be an object. - Leaving out envelope fields in the sample event, which makes the test call fail with a validation error.
- Trusting one positive case and never testing a negative case.
- Alarming on
FailedInvocationsalone and missing events that matched no rule. - Setting missing-data treatment to
missingorbreachingon a rule that legitimately goes quiet, which causes false alarms.
Exercise
Your pattern uses "status": [{ "anything-but": ["test"] }]. A test event has no status field in detail. What does test-event-pattern return, and how would you change the pattern to also accept events with no status?
Show answer
It returns {"Result": false}, because anything-but only matches when the field is present. To accept missing fields, replace the status condition with an $or list containing { "status": [{ "anything-but": ["test"] }] } and { "status": [{ "exists": false }] }, inside detail.
Exercise
A rule fires correctly, but its Lambda target throws an error on every call, and the target has a retry policy and a DLQ. Which metric rises permanently once retries are exhausted, which metric tells you the event landed in the DLQ, and where do you find the reason for the failure?
Show answer
FailedInvocations rises once retries are exhausted. DeadLetterInvocations shows that the event was written to the DLQ. The reason is in the DLQ message attributes, such as ERROR_CODE and ERROR_MESSAGE.