Message priority
The default behavior in Nexus is to process messages in the order that they come in; oldest first. In some cases this is not granular enough and you have some messages that needs to be prioritized over others. Nexus allows you to control this by passing a number as priority when you enqueue the message. Eg:
public class MyController(IEnqueuer<MyMessage> enqueuer)
{
public async Task<IActionResult> Enqueue()
{
await enqueuer.EnqueueAsync(new MyMessage { ... }, new EnqueueContext { Priority = 10 });
return Ok();
}
}
Database and in-memory queues lease eligible messages by highest priority first, then oldest internal ID. This controls lease selection, not completion order: already leased messages keep processing, and parallel workers or instances can finish in a different order. External pending storage follows its provider's priority and ordering support. Use a single processing thread when the application needs sequential handling, and account for retries and delayed messages.
Default priority
The default priority in Nexus is 0. When you enqueue messages you're encouraged to create an enum or a static class with your named priority levels rather than setting numbers like in the example above.
Note that you can have low prio messages that have a negative priority. Which means that they will be processed after any message with the default (0) priority.
Programmatically determining the priority
In some cases messages comes in through the API and you don't want to let the external party dictate the priority, but if they use the Nexus API directly to enqueue you don't get to set the priority.
For this scenario and others you can implement IMessagePriorityCalculator<TMessage> and register with IServiceCollection.
public static class MessagePriority
{
public const int High = 100;
public const int Low = 0;
}
public class MyMessagePriorityCalculator : IMessagePriorityCalculator<MyMessage>
{
public async Task<int?> CalculatePriorityAsync(MyMessage message)
{
if (message.SomeProperty == "some value")
{
return MessagePriority.High;
}
return MessagePriority.Low;
}
}
Note that this class is only called for messages that doesn't have an explicit priority set already.