This post shows how to use Azure Service Bus Topics and filters to handle a scenario where events and event handers aren’t known when starting the system.

Background

One of our systems can contain 0 or 10 different event types. And it can contain 0 or 100 event handlers. The idea is that the event handlers can be added dynamically runtime. And to make things even more interesting, also the events can be added runtime. One event can have zero-n event handlers.

We use Azure Service Bus topics for the pub&sub model of communication.

The problem

The problem is that if we don’t know the types of events when starting the system, how can we easily create the required topics?

The solution

The solution was to only use one pre-defined topic and then to filter the communications using Azure Service Bus subscription filters.

More details

As the events and event handlers can change dynamically when the system is running, pre-creating all the Service Bus topics is cumbersome and not actually possible. To get around this there’s couple options:

The event creator and event handler both try to create the Service Bus Topic if it doesn’t exists.

All the event creators and handlers use the same pre-created topic and use message properties and subscription filters to handle only the relevant messages.

We ended up using the second option. So there’s only one topic (system-events)and all the event creators push their messages into the same topic.

When pushing the event, the event creator adds a property to message which defined the message’s type. For example newinvoice.

All the event handlers then subscribe to the same system-eventstopic. But when creating the subscription, they attach a filter to the subscription, indicating what types of messages they are interested in.

How to use the topic filters in C#

The official Azure GitHub contains a good sample of using Service Bus topic filters in C#.

Main thing is to specify the filter on event handler when creating the subscription: