Tuesday, June 11, 2013

Azure Servicebus and Topic Subscriptions

This post is about getting your subscriptions deleted if you are using AutoDeleteOnIdle on the subscription.

SHORT STORY:

If your topic subscriptions gets deleted, send a dummy message to the topic every half hour or something.

LONG STORY:

This is just a little tip. If you're using Azure Servicebus and subscribing to topics using a autogenerated subscription name you have to make sure that the subscription is deleted when it goes out of scope. Since the service bus is disconnected by design it's impossible for Azure to really know when you subscription is invalid.

Luckily the greats guys at the Azure team thought of this and introduced the AutoDeleteOnIdle-property for you to use.

This property is set when you create a subscription. In the example below set the AutoDeleteOnIdle to one (1) hour. This means that if the client is not in an active call to receive within one hour, the subscription is deleted, saving the total message count and your hard earned cash.

The code below creates the subscription. Keep track of your subscription Id. In this example it's a guid but you can really use any string.

var manager = GetNameSpaceManager();
_subscriptionId = Guid.NewGuid().ToString();
var description = new SubscriptionDescription(topic, _subscriptionId);
description.AutoDeleteOnIdle = TimeSpan.FromHours(1);
manager.CreateSubscription(description);

After the subscription is created we need to receive some messages. There are several ways to do this, but in my example I use the blocking Receive-method. That is, run this on a background thread and when a message arrives, raise an event, create a worker or do what-ever to handle it. Also, replace <T> with your expected message type or create a generic handler.

while(_running)
{
    if (_subscriptionId == null)
        break;

    var message = client.Receive(TimeSpan.FromMinutes(30)); 
    if (message != null)
    {
        var body = message.GetBody<T>();
        // Do stuff with message
        message.Complete();
    }
}

However, this will not work as expected at the moment. The docs and my communication with Microsoft says that this will work but the subscription will be deleted sooner or later.

The work-around that I implemented is that I send a dummy message every half hour to the topic. This seems to keep the subscription alive as intended.