Sub topic 14
Filtering messages per subscriber
This chapter assumes you can create an SNS topic, subscribe an SQS queue to it, and publish with boto3. If not, review the fan-out chapter first. Here you will make each subscriber receive only the messages it cares about.
Why filter at the subscription
By default, SNS copies every published message to every subscriber. If a billing queue only needs order_created events, the other events cost you receives, Lambda invocations, and code that discards them.
A filter policy is a JSON document attached to a subscription. SNS compares it with each message and delivers the message only when it matches. Messages that do not match are not delivered to that subscriber, and they are not charged to its queue.
Filtering on attributes
By default, a filter policy is applied to message attributes, not the body. The publisher must set the attribute. The subscriber then lists the values it accepts.
import json
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
queue_arn = "arn:aws:sqs:us-east-1:123456789012:shipping" # replace with your queue ARN
sns.subscribe(
TopicArn=topic_arn,
Protocol="sqs",
Endpoint=queue_arn,
Attributes={
"FilterPolicy": json.dumps(
{"eventType": ["order_created", "order_shipped"]}
),
},
)
sns.publish(
TopicArn=topic_arn,
Message=json.dumps({"orderId": "1001"}),
MessageAttributes={
"eventType": {"DataType": "String", "StringValue": "order_shipped"}
},
)The queue also needs the access policy from the previous chapter, or SNS cannot write to it.
How matching works
Rules follow a small set of patterns:
- Within one key, values are combined with OR.
["order_created", "order_shipped"]matches either. - Across different keys, conditions are combined with AND. Every key in the policy must match.
- A message that lacks a key named in the policy does not match.
Beyond exact strings, SNS supports operators written as objects inside the list.
| Pattern | Example | Matches |
|---|---|---|
| Prefix | `{"prefix": "order_"}` | Values starting with `order_` |
| Anything-but | `{"anything-but": ["test"]}` | Any value except `test` |
| Numeric | `{"numeric": [">=", 100]}` | Numbers at or above 100 |
| Exists | `{"exists": true}` | Messages that carry the key |
Filtering on the message body
Setting FilterPolicyScope to MessageBody makes SNS match against the JSON body instead of attributes. Nested keys are written as nested objects.
sns.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName="FilterPolicyScope",
AttributeValue="MessageBody",
)
sns.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName="FilterPolicy",
AttributeValue=json.dumps({"order": {"total": [{"numeric": [">", 500]}]}}),
)Here subscription_arn is the value returned by subscribe. Body filtering requires the body to be valid JSON.
Common mistakes
- Publishing without the attribute the policy names, so nothing matches.
- Using
DataTypeStringfor a value the policy treats as a number. UseNumberfor numeric matching on attributes. - Expecting the body to be filtered while the scope is still the default
MessageAttributes. - Treating a filter as security. It controls delivery, not who may subscribe.
Exercise
A subscription has the filter policy {"eventType": ["ordercreated"], "region": ["eu"]}. A message arrives with eventType=ordercreated and region=us. Is it delivered, and why?
Show answer
No. Different keys are combined with AND, so both eventType and region must match. The region value us is not in ["eu"], so the message is not delivered to this subscriber.
Exercise
Your filter policy checks a field inside the JSON body, but no messages arrive. Which subscription setting should you check first?
Show answer
FilterPolicyScope. The default is MessageAttributes, so the policy looks at attributes and ignores the body. Set it to MessageBody to filter on the body fields.