We are working in the migration from Microsoft.Azure.ServiceBus to Azure.Messaging.ServiceBus. We have a very complex implementation where the messages that are sent could exceed the maximum size allowed for an ServiceBusMessage (previously a Microsoft.Azure.ServiceBus.Message).
We had a method that starting from the size of the message, if the message exceed the maximum size, it split it in several messages and send them separately. That method use a property that was present in Message but is not longer present in the ServiceBusMessage. So if we try to send messages bigger than the maximum we will receive an exception as the documentation says we want to prevent it and split the message as we were doing previously with the Messages but i don’t find any way to know the size of it.
There is a not-answered question in stackoverflow that is very similar to mine:
How to get the ServiceBusMessage message size?
The property i am referring to is:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.servicebus.message.size?view=azure-dotnet-legacy#microsoft-azure-servicebus-message-size
2
Answers
The size property in the legacy package was, unfortunately, not accurate. It reflected a point-in-time understanding though the message size was expected to expand when formally serialized and packaged for the service operation. In short, it caused more confusion than the value it provided and was only included due to the lack of a "safe batch" concept.
There is no supported way to measure the size of an individual message as a stand-alone call. The recommended approach for
Azure.Messaging.ServiceBus
would be to use ServiceBusMessageBatch to measure. If callingTryAdd
returnsfalse
then the message is too large to be included.The caveat here is that with the large message size feature, Service Bus introduced new semantics where the size of a single message may exceed the size of a batch, which was previously not possible. If you’re relying on large message support (> 1mb), then there’s no way to accurately measure, as message serialization takes place at the time a message is sent.
Your best approach would be to use the size of the body as a general heuristic, reserve ~30k for overhead, and reserve a conservative estimate for any application properties that you’re adding.
Not something you’ll be easily able to achieve. If you want a safe and reliable solution, claim check pattern is your best option if large message feature is not an option (read Premium tier).
Here’s a previous version of the ASB SDK repository for the idea and inspiration. Note that the current SDK is not identical and would require inheritance to achieve a similar result.