Zach
Zach

Reputation: 325

Determine if message will be retried from observer context in MassTransit 3

I would like to track the number of message retries and redelivers that occur while using MassTransit 3. I have both retries and redeliveries configured:

config.UseDelayedRedelivery(r => r.Immediate(2));
config.UseRetry(r => r.Immediate(3));

I have set up a IConsumeObserver and a IReceiveObserver as described here. And I can inspect the ConsumeContext/ReceiveContext in PostConsume<T>(ConsumeContext<T> context)/PostReceive(ReceiveContext context).

But when inspecting the contexts I cannot see a difference between the context for a message which was consumed without exception and one that threw an exception during consumption and will be redelivered.

How can I, in the PostConsume, method of an IConsumeObserver or IReceiveObserver determine if context represents a message that will be redelivered or one that has completed sucesfully?

Upvotes: 0

Views: 1239

Answers (2)

Alexey Zimarev
Alexey Zimarev

Reputation: 19610

You can do it. MassTransit keeps the redelivery count in the message headers, otherwise, it won't know when to stop redelivering, according to your policy.

If this line returns a non-zero (or not null, I am not sure) - you are dealing with a redelivered message.

context.Headers.Get(MessageHeaders.RedeliveryCount, default(int?)));

If your message is being retried (not redelivered), check this answer from Chris: Get MassTransit message retries amount

Upvotes: 1

Doug Johnson
Doug Johnson

Reputation: 560

The consumer can influence whether or not a message will be redelivered, but it doesn't have full control or knowledge of it. For example, everything succeeds on the consuming side, but it just takes too long, the publisher will retry and the consumer has no simple way to know that this will happen.

It's often best to design your application so that consuming the same message multiple times has the same effect as consuming it one time.

Additionally, you check the MessageId on consuming the message if you want to see if you've consumed it before.

The ConsumeContext also has a RetryCount, but I don't believe it's incremented until the next time the consumer runs.

Upvotes: 0

Related Questions