SQLServerCentral Article

Get Your Service Broker Messages in Order. Always.

,

Service Broker is a fantastic feature of SQL Server that doesn't get used often enough by developers. It provides a reliable messaging service with guaranteed delivery and automatic processing with whatever logic you choose to program into the system.

However many people struggle with the ordering of messages as they expect the Service Broker queue to act as a first-in-first-out (FIFO) system for all of their messages. Since developers are often counting on this ordering of messages, they sometimes find the order of processing isn't what they expect, which can cause issues with some of their logic.

Problems with Conversations

The main issue with Service Broker message ordering has to do with conversations. A conversation is essentially a series of messages that take place between the parties that connect to the queue. Typically a series of different messages are included within a conversation, but sometimes developers choose different conversations for different messages.

The ordering of messages is guaranteed, but only within a conversation. If you send different messages that are related in different conversations, they might be received in different orders than you expect. This could result in strange logical behaviors in your application.

A Hack for Guaranteed Ordering

If you actually require ordering to occur among all messages in a specific sequence, there is a solution. One of the many trace flags SQL Server provides will help you out.

NOTE: Be very careful enabling this and test your application thoroughly. This is undocumented and designed for testing by MS engineers.

Add this code during your service startup. It cannot be enabled once SQL Server is running, so you'll need to alter your service startup parameters in Configuration Manager, the registry, or the Services applet.

  -t 20150401

This is a lower case t, and it must be lower case. An upper case T will not work.

This flag will turn on timestamps for the queue receiver and then each message will be processed in the order it is received, regardless of conversations. Of course, the downside to this technique is that it's an April Fools joke and won't work at all. I hope you read this far.

Happy coding.

Rate

3.13 (15)

You rated this post out of 5. Change rating

Share

Share

Rate

3.13 (15)

You rated this post out of 5. Change rating