Sub topic 15
Filtering messages per subscriber
This chapter covers how SNS subscription filter policies decide which subscribers get which messages. It assumes you can create a topic, subscribe an SQS queue, and publish with boto3, as in the fan-out chapter. You should also know that an SQS queue needs an access policy before SNS can write to it.
Why filter at the subscription
By default, SNS delivers every message published to a topic to every subscription. Suppose an order-events topic carries order_created, order_cancelled, and order_refunded events. A billing queue only cares about refunds. Without filtering, the billing consumer reads every event, discards most of them, and you pay for the SQS requests and compute that this wastes.
A filter policy is a JSON document attached to one subscription. SNS evaluates it for each published message and delivers the message only if it matches. Filtering happens inside SNS, before delivery, so the consumer never sees the rest.
The working model
A policy has a scope, which says what SNS inspects, and a set of rules.
- MessageAttributes scope (the default). SNS matches the policy against the message attributes you pass in
publish. The body is not examined. - MessageBody scope. SNS matches against fields inside the message body, which must be valid JSON. You enable this by setting the
FilterPolicyScopesubscription attribute toMessageBody.
Matching follows three rules:
- Every key in the policy must match (AND).
- Inside one key, the values are a list, and any one value matching is enough (OR).
- A message that does not match is dropped for that subscription only. Other subscriptions are unaffected.
Policies are set per subscription. You can change one at any time with set_subscription_attributes.
Attribute-based filtering
The code below subscribes a queue with a policy and then updates it. It assumes the queue's access policy from the previous chapter is already in place.
import json
import boto3
sns = boto3.client("sns")
sqs = boto3.client("sqs")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
sub_arn = sns.subscribe(
TopicArn=topic_arn,
Protocol="sqs",
Endpoint=queue_arn,
Attributes={"RawMessageDelivery": "true"},
ReturnSubscriptionArn=True,
)["SubscriptionArn"]
# Two keys are ANDed. Values inside a key are ORed.
policy = {
"eventType": ["order_created", "order_updated"],
"region": [{"prefix": "eu-"}],
"total": [{"numeric": [">=", 100]}],
}
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="FilterPolicy",
AttributeValue=json.dumps(policy),
)
sns.publish(
TopicArn=topic_arn,
Message=json.dumps({"orderId": "1001"}),
MessageAttributes={
"eventType": {"DataType": "String", "StringValue": "order_created"},
"region": {"DataType": "String", "StringValue": "eu-west-1"},
"total": {"DataType": "Number", "StringValue": "250"},
},
)This message matches. eventType is one of the listed values, region starts with eu-, and total is at least 100. If you change total to 50, the message is filtered out.
Common operators in a value list:
| Operator | Example | Matches |
|---|---|---|
| Exact | `"order_created"` | That string |
| Prefix | `{"prefix": "eu-"}` | Strings starting with `eu-` |
| Suffix | `{"suffix": ".png"}` | Strings ending with `.png` |
| Anything-but | `{"anything-but": ["test"]}` | Any value except those listed |
| Numeric | `{"numeric": [">", 0, "<=", 10]}` | A number in a range |
| Exists | `{"exists": false}` | The key is absent |
Body-based filtering
If publishers cannot add message attributes, you can filter on the JSON body instead. Set the scope first, then the policy. Policy keys now describe the body structure, and nested objects are written as nested JSON.
import json
import boto3
sns = boto3.client("sns")
sub_arn = "arn:aws:sns:us-east-1:123456789012:order-events:11111111-2222-3333-4444-555555555555" # replace with your subscription ARN
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="FilterPolicyScope",
AttributeValue="MessageBody",
)
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="FilterPolicy",
AttributeValue=json.dumps({"order": {"status": ["refunded"]}}),
)This policy matches a body such as {"order": {"status": "refunded", "id": "1001"}}. Body filtering accepts the same operators as attribute filtering.
Common errors and gotchas
- Missing attributes mean no delivery. With attribute scope, a message published without the attributes named in the policy is filtered out. Publishers that forget the
eventTypeattribute silently lose messages for every filtered subscriber. - Filtered messages are not failures. They never reach a subscription dead-letter queue, and nothing is retried. If a message vanishes, check filtering first.
- Wrong data type. A numeric rule only matches an attribute published with
DataTypeNumber. A number sent asStringwill not match. - Scope mismatch. Setting a body-shaped policy while the scope is still
MessageAttributesmatches nothing. - Invalid body. In body scope, a message whose body is not valid JSON is filtered out.
- Policy size and key limits. A policy is limited in size and, by default, in the number of attribute names it can use. Check the current SNS quotas before designing large policies.
- Propagation delay. A new or changed policy can take a short time to take effect, so messages published right after an update may follow the old rules.
- Raw delivery interaction. With
RawMessageDeliveryenabled, matched attributes arrive as SQS message attributes. Without it, they appear inside the SNS JSON envelope.
Verifying filter behavior
In CloudWatch, the NumberOfNotificationsFilteredOut metric for the topic counts messages dropped by filter policies. Variants such as NumberOfNotificationsFilteredOut-NoMessageAttributes and NumberOfNotificationsFilteredOut-InvalidAttributes show why. A spike in the no-attributes metric usually means a publisher forgot to set attributes.
Exercise
Exercise
A subscription has the policy {"eventType": ["orderrefunded"], "region": [{"prefix": "eu-"}]} with the default MessageAttributes scope. A publisher sends eventType=orderrefunded with no region attribute. Is the message delivered, and where would you see evidence of the outcome?
Show answer
It is not delivered. Every key in the policy must match, and the region key has no attribute to match. The message is filtered out for this subscription only, with no retry and no dead-letter entry. The evidence is the NumberOfNotificationsFilteredOut CloudWatch metric (and its NoMessageAttributes variant) for the topic.