1. 程式人生 > >Simplify Your Pub/Sub Messaging with Amazon SNS Message Filtering

Simplify Your Pub/Sub Messaging with Amazon SNS Message Filtering

Contributed by: Stephen Liedig, Senior Solutions Architect, ANZ Public Sector, and Otavio Ferreira, Manager, Amazon Simple Notification Service

Want to make your cloud-native applications scalable, fault-tolerant, and highly available? Recently, we wrote a couple of posts about using AWS messaging services

Amazon SQS and Amazon SNS to address messaging patterns for loosely coupled communication between highly cohesive components. For more information, see:

Today, AWS is releasing a new message filtering functionality for SNS. This new feature simplifies the pub/sub messaging architecture by offloading the filtering logic from subscribers, as well as the routing logic from publishers, to SNS.

In this post, we walk you through the new message filtering feature, and how to use it to clean up unnecessary logic in your components, and reduce the number of topics in your architecture.

Topic-based filtering

SNS is a fully managed pub/sub messaging service that lets you fan out messages to large numbers of recipients at one time, using topics. SNS topics support a variety of subscription types, allowing you to push messages to SQS queues,

AWS Lambda functions, HTTP endpoints, email addresses, and mobile devices (SMS, push).

In the above scenario, every subscriber receives the same message published to the topic, allowing them to process the message independently. For many use cases, this is sufficient.

However, in more complex scenarios, the subscriber may only be interested in a subset of the messages being published. The onus, in that case, is on each subscriber to ensure that they are filtering and only processing those messages in which they are actually interested.

To avoid this additional filtering logic on each subscriber, many organizations have adopted a practice in which the publisher is now responsible for routing different types of messages to different topics. However, as depicted in the following diagram, this topic-based filtering practice can lead to overly complicated publishers, topic proliferation, and additional overhead in provisioning and managing your SNS topics.

Attribute-based filtering

To leverage the new message filtering capability, SNS requires the publisher to set message attributes and each subscriber to set a subscription attribute (a subscription filter policy). When the publisher posts a new message to the topic, SNS attempts to match the incoming message attributes to the filter policy set on each subscription, to determine whether a particular subscriber is interested in that incoming event. If there is a match, SNS then pushes the message to the subscriber in question. The new attribute-based message filtering approach is depicted in the following diagram.

Message filtering in action

Look at how message filtering works. The following example is based on a sports merchandise ecommerce website, which publishes a variety of events to an SNS topic. The events range from checkout events (triggered when orders are placed or canceled) to buyers’ navigation events (triggered when product pages are visited). The code below is based on the existing AWS SDK for Python.

First, create the single SNS topic to which all shopping events are published.

topic_arn = sns.create_topic(
    Name='ShoppingEvents'
)['TopicArn']

Next, subscribe the endpoints that will be listening to those shopping events. The first subscriber is an SQS queue that is processed by a payment gateway, while the second subscriber is a Lambda function that indexes the buyer’s shopping interests against a search engine.

A subscription filter policy is set as a subscription attribute, by the subscription owner, as a simple JSON object, containing a set of key-value pairs. This object defines the kind of event in which the subscriber is interested.

payment_gateway_subscription_arn = sns.subscribe(
    TopicArn = topic_arn,
    Protocol = 'sqs',
    Endpoint = 'arn:aws:sqs:ap-southeast-2:123456789012:PaymentQueue'
)['SubscriptionArn']

sns.set_subscription_attributes(
    SubscriptionArn = payment_gateway_subscription_arn, 
    AttributeName = 'FilterPolicy', 
    AttributeValue = '{"event_type": ["order_placed", "order_cancelled"]}'
)
search_engine_subscription_arn = sns.subscribe(
    TopicArn = topic_arn,
    Protocol = 'lambda',
    Endpoint = 'arn:aws:lambda:ap-southeast-2:123456789012:function:SearchIndex'
)['SubscriptionArn']

sns.set_subscription_attributes(
    SubscriptionArn = search_engine_subscription_arn,
    AttributeName ='FilterPolicy', 
    AttributeValue ='{"event_type": ["product_page_visited"]}'
)

You’re now ready to start publishing events with attributes!

Message attributes allow you to provide structured metadata items (such as time stamps, geospatial data, event type, signatures, and identifiers) about the message. Message attributes are optional and separate from, but sent along with, the message body. You can include up to 10 message attributes with your message.

The first message published in this example is related to an order that has been placed on the ecommerce website. The message attribute “event_type” with the value “order_placed” matches only the filter policy associated with the payment gateway subscription. Therefore, only the SQS queue subscribed to the SNS topic is notified about this checkout event.

message = '{"order": {"id": 5678, "status": "confirmed", "items": [' \
          '{"code": "P-9012", "product": "Santos FC Jersey", "units": 1},' \
          '{"code": "P-3156", "product": "Soccer Ball", "units": 2}]},' \
          ' "buyer": {"id": 4454}}'

sns.publish(
    TopicArn = topic_arn,
    Subject = 'Order Placed #5678',
    Message = message,
    MessageAttributes = {
        'event_type': {
            'DataType': 'String',
            'StringValue': 'order_placed'
        }
    }
)

The second message published is related to a buyer’s navigation activity on the ecommerce website. The message attribute “event_type” with the value “product_page_visited” matches only the filter policy associated with the search engine subscription. Therefore, only the Lambda function subscribed to the SNS topic is notified about this navigation event.

message = '{"product": {"id": 1251, "status": "in_stock"},' \
          ' "buyer": {"id": 4454}}'

sns.publish(
    TopicArn = topic_arn,
    Subject = 'Product Visited #1251',
    Message = message,
    MessageAttributes = {
        'event_type': {
            'DataType': 'String',
            'StringValue': 'product_page_visited'
        }
    }
)

The following diagram represents the architecture for this ecommerce website, with the message filtering mechanism in action. As described earlier, checkout events are pushed only to the SQS queue, whereas navigation events are pushed to the Lambda function only.

Message filtering criteria

It is important to remember the following things about subscription filter policy matching:

  • A subscription filter policy either matches an incoming message, or it doesn’t. It’s Boolean logic.
  • For a filter policy to match a message, the message must contain all the attribute keys listed in the policy.
  • Attributes of the message not mentioned in the filtering policy are ignored.
  • The value of each key in the filter policy is an array containing one or more values. The policy matches if any of the values in the array match the value in the corresponding message attribute.
  • If the value in the message attribute is an array, then the filter policy matches if the intersection of the policy array and the message array is non-empty.
  • The matching is exact (character-by-character), without case-folding or any other string normalization.
  • The values being matched follow JSON rules: Strings enclosed in quotes, numbers, and the unquoted keywords true, false, and null.
  • Number matching is at the string representation level. Example: 300, 300.0, and 3.0e2 aren’t considered equal.

When should I use message filtering?

We recommend using message filtering and grouping subscribers into a single topic only when all of the following is true:

  • Subscribers are semantically related to each other
  • Subscribers consume similar types of events
  • Subscribers are supposed to share the same access permissions on the topic

Technically, you could get away with creating a single topic for your entire domain to handle all event processing, even unrelated use cases, but this wouldn’t be recommended. This option could result in an unnecessarily large topic, which could potentially impact your message delivery latency. Also, you would lose the ability to implement fine-grained access control on your topics.

Finally, if you already use SNS, but had to add filtering logic in your subscribers or routing logic in your publishers (topic-based filtering), you can now immediately benefit from message filtering. This new approach lets you clean up any unnecessary logic in your components, and reduce the number of topics in your architecture.

Summary

As we’ve shown in this post, the new message filtering capability in Amazon SNS gives you a great amount of flexibility in your messaging pattern. It allows you to really simplify your pub/sub infrastructure requirements.

Message filtering can be implemented easily with existing AWS SDKs by applying message and subscription attributes across all SNS supported protocols (Amazon SQS, AWS Lambda, HTTP, SMS, email, and mobile push). It’s now available in all AWS commercial regions, at no extra charge.

Here’s a few ideas for next steps to get you started:

相關推薦

Simplify Your Pub/Sub Messaging with Amazon SNS Message Filtering

Contributed by: Stephen Liedig, Senior Solutions Architect, ANZ Public Sector, and Otavio Ferreira, Manager, Amazon Simple Notification Service

What is Pub/Sub Messaging?

Publish/subscribe messaging, or pub/sub messaging, is a form of asynchronous service-to-service communication used in serverless and mic

What are Benefits of Pub/Sub Messaging?

In modern cloud architecture, applications are decoupled into smaller, independent building blocks that are easier to develop, deploy and m

What are the Features of Pub/Sub Messaging?

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

Top skills for Alexa: 6 tips for your Amazon Echo that will simplify your life

Here are 21 commands that even seasoned Echo users may not know. Many of them are useful, some are fun, and others give the illusion that Alexa is as cogni

Encrypting messages published to Amazon SNS with AWS KMS

Amazon Simple Notification Service (Amazon SNS) is a fully managed pub/sub messaging service for decoupling event-driven microservices, distribute

Modernize Your Data Warehouse with Amazon Redshift

Data in every organization is growing in volume and complexity faster than ever. Yet, only a small fraction of this invaluable asset is available

Level Up Your Games with Amazon Aurora

Dhruv Thukral is a solutions architect at Amazon Web Services. Amazon Aurora is rapidly becoming the relational database of choice for so

ActiveMQ兩種模式PTP和PUB/SUB<轉>

pub provide ops itl 通知 subscribe cin sdn cti 1.PTP模型 PTP(Point-to-Point)模型是基於隊列(Queue)的,對於PTP消息模型而言,它的消息目的是一個消息隊列(Queue),消息生產者每次發送消息總是把消

Draw your Next App Idea with Ink to Code

load width ace export notes minimal calc constrain wan Imagine that you’ve just been struck by inspiration for your next great app. You m

2-redis的pub/sub發布訂閱

HA mage 發布消息 都是 log alt client -c div 1 基本   發布/訂閱是一種消息通信模式。發布者不是將消息發布給訂閱者,而是發布到不同頻道。訂閱者接受自己感興趣的頻道的消息,不需要接觸發布者。   sub/pub都是client,而channe

php redis pub/sub(Publish/Subscribe,發布/訂閱的信息系統)之基本使用

終端 sage 命令 -c ring 腳本 端口 ack 端口號 一.場景介紹 最近的一個項目需要用到發布/訂閱的信息系統,以做到最新實時消息的通知。經查找後發現了redis pub/sub(發布/訂閱的信息系統)可以滿足我的開發需求,而且學習成本和使用成本也比較低。 二

redis訂閱模式pub/sub

Pub/Sub:     "釋出/訂閱"在redis中,被設計的非常輕量級和簡潔,它做到了訊息的“釋出”和“訂閱”的     基本能力;但是尚未提供關於訊息的持久化等各種企業級的特性。       &

redis的pub/sub機制

      一個Redis client釋出訊息,其他多個redis client訂閱訊息,釋出的訊息“即發即失”,redis不會持久儲存釋出的訊息;訊息訂閱者也將只能得到訂閱之後的訊息,通道中此前的訊息將無從獲得。    訊息釋出者,即publish客戶端,無需獨佔連結,

genymotion報錯Your CPU is incompatible with virtualization technologies

genymotion日常報錯,以前也遇到過,始終解決不了,然後就使用android studio原生的模擬器,或者是使用真機. 但是很多時候還是很嚮往genymotion的感覺,然後發現版本是Ubuntu(32-bit),感覺不對啊= =,因為配置是64位的,同時報錯為不相

Akka-Cluster(2)- distributed pub/sub mechanism 分散式釋出/訂閱機制

   上期我們介紹了cluster singleton,它的作用是保證在一個叢集環境裡永遠會有唯一一個singleton例項存在。具體使用方式是在叢集所有節點部署ClusterSingletonManager,由叢集中的leader節點選定其中一個節點並指示上面的Cluste

Redis入門【八】---------釋出與訂閱(pub/sub

前言 一般來說,釋出(publish)與訂閱(subscribe),又稱為pub/sub的。其特點是訂閱者(listener)負責訂閱頻道(channel),傳送者(publisher)負責向頻道傳送二進位制字串訊息。 每當有訊息傳送到頻道的時候,頻道的所有訂閱者都會收到訊息,

redis 釋出/訂閱(Pub/Sub) 原始碼分析

* 背景 釋出者和訂閱者都是Redis客戶端,Channel則為Redis伺服器端,釋出者將訊息傳送到某個的頻道,訂閱了這個頻道的訂閱者就能接收到這條訊息。 Redis的這種釋出訂閱機制與基於主題的釋出訂閱類似,Channel相當於主題。 原理圖如下: * 命令

Analyze and visualize your VPC network traffic using Amazon Kinesis and Amazon Athena

Network log analysis is a common practice in many organizations.  By capturing and analyzing network logs, you can learn how devices on your netwo

Segmenting brain tissue using Apache MXNet with Amazon SageMaker and AWS Greengrass ML Inference

In Part 1 of this blog post, we demonstrated how to train and deploy neural networks to automatically segment brain tissue from an MRI scan in a s