Introduction
With Azure Service Bus, you get some great features but to get guaranteed FIFO (First-In, First-Out, i.e. ordered delivery), there was a lot of documentation to read through so I thought I’d show a quick example using a Topic and Subscriber.
Service Bus Message Sessions
To ensure FIFO, Service Bus requires that a Session is used which is fairly simple. The sender needs to set the SessionId property on the Message that it sends.
Sender:
This method below initialises a TopicClient using a connection string and topic name. It then creates a list of messages to send to the service bus topic and it sets the same SessionId on each one. If you don’t specify the same SessionId, you’ll find messages received in the wrong order.
Receiver:
The receiver, initialises a SubscriptionClient then calls the RegisterSessionHandle() method which registers a message handler and takes a SessionHandlerOptions parameter. This SessionHandlerOptions object requires that a exception message handler is specified which is called in case of an exception handling the message.
This handler references the ProcessMessageAsync() method which takes an IMessageSession, Message and CancellationToken:
The ProcessMessageException() method looks like this:
That’s all you need to do to get this working. Let’s test it out.
Testing
To test it out, I set up a simple console app which sends the messages to the topic, waits for them to be processed and then checks to make sure all received messages are in the correct order. See below: