JensB
JensB

Reputation: 6850

Stop consumption of message if it cannot be completed

I'm new to mass transit and have a question regarding how I should solve a failure to consume a message. Given the below code I am consuming INotificationRequestContract's. As you can see the code will break and not complete.

public class NotificationConsumerWorker : IConsumer<INotificationRequestContract>
{
    private readonly ILogger<NotificationConsumerWorker> _logger;
    private readonly INotificationCreator _notificationCreator;

    public NotificationConsumerWorker(ILogger<NotificationConsumerWorker> logger, INotificationCreator notificationCreator)
    {
        _logger = logger;
        _notificationCreator = notificationCreator;
    }

    public Task Consume(ConsumeContext<INotificationRequestContract> context)
    {
        try
        {
            throw new Exception("Horrible error");
        }
        catch (Exception e)
        {
            // >>>>> insert code here to put message back for later consumption. <<<<<
            _logger.LogError(e, "Failed to consume message"); 
            throw;
        }
    }
}

How do I best handle a scenario such as this where the consumption fails? In my specific case this is likely to occur if a required external service is unavailable.

I can see two solutions.

Upvotes: 0

Views: 759

Answers (1)

Chris Patterson
Chris Patterson

Reputation: 33278

The exceptions section of the documentation provides sufficient guidance for dealing with consumer exceptions.

There are two retry approaches, which can be used in combination:

  1. Message Retry, which waits while the message is locked, in-process, for the next retry. Therefore, these should be short, to deal with transient issues.
  2. Message Redelivery, which delays the message using either the broker delayed delivery, or a message scheduler, so that it is redelivered to the receive endpoint at some point in the future.

Once all retry/redelivery attempts are exhausted, the message is moved to the _error queue.

Upvotes: 1

Related Questions