I recently had the pleasure of working on a project where I needed to send (relatively) large amounts of data in a MSMQ message via NServiceBus. To give a bit of background, I have an endpoint that receives a reference to a transaction. I take that reference and pull roughly 2-7 mb of data all in XML enhance it and then I need to publish it to a handful of subscribers. On any given day, there are thousands if not tens of thousands of these messages being sent through this system, and speed/processing time is crucial.
One path that I explored to achieve faster speeds across the wire was the compression of the transport messages using a compression mutator in NServiceBus. Essentially, when as message is ready to be sent, it is gzip’ed a header is added and its published. On the other end, any message with this header is taken, un-gzip’ed and processed. In the initial testing phase, I saw reductions in message size ranging from 94%-97% with a nominal increase in processing time.
public class TransportMessageCompressionMutator : IMutateTransportMessages, IMutateOutgoingTransportMessages
public void MutateOutgoing(LogicalMessage message, TransportMessage transportMessage)
MemoryStream mStream = new MemoryStream(transportMessage.Body);
MemoryStream outStream = new MemoryStream();
using (GZipStream tinyStream = new GZipStream(outStream, CompressionMode.Compress))
// copy the compressed buffer only after the GZipStream is disposed,
// otherwise, not all the compressed message will be copied.
transportMessage.Body = outStream.ToArray();
transportMessage.Headers["IWasCompressed"] = "true";
public void MutateIncoming(TransportMessage transportMessage)
using (GZipStream bigStream = new GZipStream(new MemoryStream(transportMessage.Body), CompressionMode.Decompress))
MemoryStream bigStreamOut = new MemoryStream();
transportMessage.Body = bigStreamOut.ToArray();