Programming Search⌘K

Patternadvanced

Priority Queue pattern

Also called Priority Queue, message priority, priority queues for messages.

The Priority Queue pattern gives each message a priority, so that urgent messages are processed before the others, either in one queue that orders by priority or in a separate queue for each priority.

Family
integration
Intent
Process urgent requests before less urgent ones, by a priority on each message and either one queue that delivers by priority or one queue for each priority with its own consumers.
Also called
prioritized queue

Intent

Let a workload process urgent requests faster than less urgent ones. The Azure page states the aim so: give priorities to the requests that go to a service, so that the workload processes the requests of high priority more quickly. The requests travel as messages in one or more queues. This helps an application that gives different service levels to different kinds of requests or customers.1

Problem

By default, most workloads process tasks in the order in which they arrive, in a first-in, first-out (FIFO) queue. This order does not show how important a task is.1 Some tasks need attention at once, and others can wait. If an urgent task waits behind many tasks that are not urgent, the users see a delay, and the workload can break a service-level agreement (SLA).1

The forces are a fast path for urgent work, a fair chance for the other work, and simple operation.

Solution

The producer gives each message a priority value, and the consumers process the messages by priority, not only by arrival order.1 The Azure page names two ways.1

  one queue:        producer --> [ h h n l l ] --> consumers
                                  ordered by priority

  multiple queues:  producer --+--> [ high ] --> pool of 3 consumers
                               +--> [ low  ] --> pool of 1 consumer
  • One queue. All messages go to one queue, which delivers the messages of high priority first.1
  • Multiple queues. Each priority has its own queue. One pool of consumers can serve all the queues, and take from a lower queue only when the higher queues are empty. Or each queue has its own pool, and the queues of high priority get more consumers or faster ones.1

The participants are the producer, which sets the priority, the queue or queues, and the consumers.1

Starvation. With one shared pool, the higher queues always go first. Thus the messages of low priority can wait for a long time, or never be processed.1 RabbitMQ names this problem resource starvation.2 The Azure page suggests to increase the priority of old messages, so that the messages of low priority also get processed in the end.1 The program below has one consumer, which handles one message in each tick. For 20 ticks, a message of high priority arrives in each tick, and 5 messages of low priority arrive in the first 5 ticks.

# One consumer handles one message per tick. For 20 ticks, a high message
# arrives on each tick, which uses all of the capacity. 5 low messages
# arrive in the first 5 ticks.
TICKS, AGE_LIMIT = 30, 6
arrivals = []
for t in range(20):
    arrivals.append((t, "high"))
    if t < 5:
        arrivals.append((t, "low"))


def run(pick):
    waiting, waits = [], {"high": [], "low": []}
    i = 0
    for t in range(TICKS):
        while i < len(arrivals) and arrivals[i][0] == t:
            waiting.append(arrivals[i])
            i += 1
        if waiting:
            m = pick(waiting, t)
            waiting.remove(m)
            waits[m[1]].append(t - m[0])
    return waits


def fifo(waiting, t):
    return waiting[0]


def strict(waiting, t):
    high = [m for m in waiting if m[1] == "high"]
    return high[0] if high else waiting[0]


def aging(waiting, t):
    old = [m for m in waiting if t - m[0] >= AGE_LIMIT]
    return old[0] if old else strict(waiting, t)


for name, pick in [("FIFO", fifo), ("strict priority", strict), ("priority, aging after 6 ticks", aging)]:
    w = run(pick)
    print("%-30s high: max wait %2d | low: max wait %2d" % (name + ":", max(w["high"]), max(w["low"])))
Output
FIFO:                          high: max wait  5 | low: max wait  5
strict priority:               high: max wait  0 | low: max wait 20
priority, aging after 6 ticks: high: max wait  5 | low: max wait  6

FIFO makes the urgent messages wait behind the others. Strict priority gives the urgent messages no wait at all, but a message of low priority waits 20 ticks, until the urgent messages stop. With aging, a message that has waited 6 ticks goes first. The messages of low priority then wait at most 6 ticks, and the urgent ones wait at most 5 ticks, as with FIFO. Aging moves the delay; it does not remove it, because the consumer has no spare capacity.

The broker. In RabbitMQ, classic queues and quorum queues support priorities. A publisher sets the priority of a message, and a larger number is a higher priority.2 A classic queue needs the x-max-priority argument, in the range 1 to 255, and it keeps an internal sub-queue for each priority. RabbitMQ recommends a small number of priorities, from 2 to 4.2 A quorum queue has 32 priority levels, from 0 to 31.2

Example

Each example file puts 8 messages with 3 priorities in one in-memory queue with a heap. The consumer takes one message in each tick. The messages of high priority go first, and the 3 messages of low priority wait 5 or 6 ticks. Messages with the same priority must keep their arrival order. A heap does not guarantee this, so the key of each message has its arrival number after the priority. Thus l1 comes before l2.

PythonGitHub
import heapq
from itertools import count

LEVEL = {"high": 0, "normal": 1, "low": 2}  # a smaller number goes first
# (tick, id, priority) in the order the messages arrive
arrivals = [(0, "l1", "low"), (0, "l2", "low"), (0, "h1", "high"), (1, "n1", "normal"),
            (1, "h2", "high"), (2, "l3", "low"), (3, "h3", "high"), (4, "n2", "normal")]

queue = []
seq = count()  # the arrival number breaks ties, so equal priorities stay FIFO
i, t, order = 0, 0, []
while i < len(arrivals) or queue:
    while i < len(arrivals) and arrivals[i][0] == t:
        _, mid, prio = arrivals[i]
        heapq.heappush(queue, (LEVEL[prio], next(seq), t, mid, prio))
        i += 1
    if queue:
        _, _, arrived, mid, prio = heapq.heappop(queue)
        print("tick %d: %s (%s, waited %d)" % (t, mid, prio, t - arrived))
        order.append(mid)
    t += 1
print("order: " + " ".join(order))
print("l1 before l2: %s" % str(order.index("l1") < order.index("l2")).lower())
Output
tick 0: h1 (high, waited 0)
tick 1: h2 (high, waited 0)
tick 2: n1 (normal, waited 1)
tick 3: h3 (high, waited 0)
tick 4: n2 (normal, waited 0)
tick 5: l1 (low, waited 5)
tick 6: l2 (low, waited 6)
tick 7: l3 (low, waited 5)
order: h1 h2 n1 h3 n2 l1 l2 l3
l1 before l2: true
  • Verdict: idiom. heapq keeps a list as a binary heap, and a tuple key compares field by field, so (level, seq) gives the priority first and the arrival order second.
  • itertools.count gives the arrival number; without it, two messages of the same priority would compare by the next fields, and the order would depend on the ids.
  • A smaller number pops first in heapq, so high has the level 0; RabbitMQ uses the opposite rule, where a larger number is a higher priority.
JavaGitHub
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

public class Main {
    record Arrival(int tick, String id, String prio) {
    }

    record Msg(int level, long seq, int arrived, String id, String prio) {
    }

    public static void main(String[] args) {
        Map<String, Integer> level = Map.of("high", 0, "normal", 1, "low", 2);
        List<Arrival> arrivals = List.of(new Arrival(0, "l1", "low"), new Arrival(0, "l2", "low"),
                new Arrival(0, "h1", "high"), new Arrival(1, "n1", "normal"), new Arrival(1, "h2", "high"),
                new Arrival(2, "l3", "low"), new Arrival(3, "h3", "high"), new Arrival(4, "n2", "normal"));
        // PriorityQueue is not stable, so the arrival number breaks ties.
        PriorityQueue<Msg> queue = new PriorityQueue<>(
                Comparator.comparingInt(Msg::level).thenComparingLong(Msg::seq));
        List<String> order = new ArrayList<>();
        long seq = 0;
        int i = 0;
        for (int t = 0; i < arrivals.size() || !queue.isEmpty(); t++) {
            while (i < arrivals.size() && arrivals.get(i).tick() == t) {
                Arrival a = arrivals.get(i++);
                queue.add(new Msg(level.get(a.prio()), seq++, t, a.id(), a.prio()));
            }
            Msg m = queue.poll();
            if (m != null) {
                System.out.printf("tick %d: %s (%s, waited %d)%n", t, m.id(), m.prio(), t - m.arrived());
                order.add(m.id());
            }
        }
        System.out.println("order: " + String.join(" ", order));
        System.out.println("l1 before l2: " + (order.indexOf("l1") < order.indexOf("l2")));
    }
}
Output
tick 0: h1 (high, waited 0)
tick 1: h2 (high, waited 0)
tick 2: n1 (normal, waited 1)
tick 3: h3 (high, waited 0)
tick 4: n2 (normal, waited 0)
tick 5: l1 (low, waited 5)
tick 6: l2 (low, waited 6)
tick 7: l3 (low, waited 5)
order: h1 h2 n1 h3 n2 l1 l2 l3
l1 before l2: true
  • Verdict: idiom. java.util.PriorityQueue is a heap, and Comparator.comparingInt(...).thenComparingLong(...) builds the key of level and arrival number.
  • The Javadoc of PriorityQueue says that ties are broken arbitrarily, so the arrival number is necessary to keep FIFO order inside a priority.
  • A record holds each message, so the comparator reads the fields through the accessor methods.
var level = new Dictionary<string, int> { ["high"] = 0, ["normal"] = 1, ["low"] = 2 };
(int Tick, string Id, string Prio)[] arrivals =
[
    (0, "l1", "low"), (0, "l2", "low"), (0, "h1", "high"), (1, "n1", "normal"),
    (1, "h2", "high"), (2, "l3", "low"), (3, "h3", "high"), (4, "n2", "normal"),
];

// PriorityQueue does not keep FIFO order for equal priorities, so the arrival number breaks ties.
var queue = new PriorityQueue<(int Arrived, string Id, string Prio), (int Level, long Seq)>();
var order = new List<string>();
long seq = 0;
int i = 0;
for (int t = 0; i < arrivals.Length || queue.Count > 0; t++)
{
    while (i < arrivals.Length && arrivals[i].Tick == t)
    {
        var a = arrivals[i++];
        queue.Enqueue((t, a.Id, a.Prio), (level[a.Prio], seq++));
    }
    if (queue.TryDequeue(out var m, out _))
    {
        Console.WriteLine($"tick {t}: {m.Id} ({m.Prio}, waited {t - m.Arrived})");
        order.Add(m.Id);
    }
}
Console.WriteLine("order: " + string.Join(" ", order));
Console.WriteLine($"l1 before l2: {(order.IndexOf("l1") < order.IndexOf("l2")).ToString().ToLowerInvariant()}");
Output
tick 0: h1 (high, waited 0)
tick 1: h2 (high, waited 0)
tick 2: n1 (normal, waited 1)
tick 3: h3 (high, waited 0)
tick 4: n2 (normal, waited 0)
tick 5: l1 (low, waited 5)
tick 6: l2 (low, waited 6)
tick 7: l3 (low, waited 5)
order: h1 h2 n1 h3 n2 l1 l2 l3
l1 before l2: true
  • Verdict: idiom. PriorityQueue<TElement, TPriority> in .NET keeps the priority apart from the element, and a value tuple (Level, Seq) is a priority that compares field by field.
  • The .NET documentation says that the queue does not guarantee first-in, first-out order for equal priorities, so the arrival number is part of the priority.
  • TryDequeue returns the element and its priority, and it returns false when the queue is empty.
package main

import (
	"container/heap"
	"fmt"
	"strings"
)

type msg struct {
	level, seq, arrived int
	id, prio            string
}

// queue implements heap.Interface; the arrival number breaks ties.
type queue []msg

func (q queue) Len() int {
	return len(q)
}

func (q queue) Less(i, j int) bool {
	if q[i].level != q[j].level {
		return q[i].level < q[j].level
	}
	return q[i].seq < q[j].seq
}

func (q queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
}

func (q *queue) Push(x any) {
	*q = append(*q, x.(msg))
}

func (q *queue) Pop() any {
	old := *q
	m := old[len(old)-1]
	*q = old[:len(old)-1]
	return m
}

func main() {
	level := map[string]int{"high": 0, "normal": 1, "low": 2}
	arrivals := []struct {
		tick     int
		id, prio string
	}{
		{0, "l1", "low"}, {0, "l2", "low"}, {0, "h1", "high"}, {1, "n1", "normal"},
		{1, "h2", "high"}, {2, "l3", "low"}, {3, "h3", "high"}, {4, "n2", "normal"},
	}
	q := &queue{}
	var order []string
	seq, i := 0, 0
	for t := 0; i < len(arrivals) || q.Len() > 0; t++ {
		for i < len(arrivals) && arrivals[i].tick == t {
			a := arrivals[i]
			heap.Push(q, msg{level[a.prio], seq, t, a.id, a.prio})
			seq++
			i++
		}
		if q.Len() > 0 {
			m := heap.Pop(q).(msg)
			fmt.Printf("tick %d: %s (%s, waited %d)\n", t, m.id, m.prio, t-m.arrived)
			order = append(order, m.id)
		}
	}
	fmt.Println("order: " + strings.Join(order, " "))
	pos := map[string]int{}
	for k, id := range order {
		pos[id] = k
	}
	fmt.Printf("l1 before l2: %t\n", pos["l1"] < pos["l2"])
}
Output
tick 0: h1 (high, waited 0)
tick 1: h2 (high, waited 0)
tick 2: n1 (normal, waited 1)
tick 3: h3 (high, waited 0)
tick 4: n2 (normal, waited 0)
tick 5: l1 (low, waited 5)
tick 6: l2 (low, waited 6)
tick 7: l3 (low, waited 5)
order: h1 h2 n1 h3 n2 l1 l2 l3
l1 before l2: true
  • Verdict: idiom. container/heap works on any type that has the methods Len, Less, Swap, Push and Pop, and here a slice of messages has them.
  • Less compares the level first and the arrival number second, so the messages of one priority keep their arrival order.
  • heap.Pop returns an empty interface, so the caller converts the value back to the message type.

Consequences

Benefits.

  • Different service levels. The urgent work, or the work of a premium customer, gets more speed and availability.1
  • Focus. The work for reliability and performance can go to the most critical flows.1
  • Fault isolation. With a pool of consumers for each queue, a problem in one queue does not affect the other queues.1

Liabilities.

  • Starvation. With one pool and strict priority, a steady stream of urgent messages can delay the other messages without limit.12
  • Order. A priority changes the order in which the consumers see the messages. RabbitMQ names priorities as one of the queue features that affect this order.3
  • Prefetch. A priority has an effect only on the messages that wait in the queue. If a consumer has already received 10 messages of low priority under its prefetch limit, a new urgent message waits behind them. RabbitMQ thus recommends manual acknowledgements and a prefetch limit on the consumers.2
  • Cost. In RabbitMQ, each priority level costs memory, disk and CPU.2 Some queue services charge for each send, receive and query, so more queues can cost more.1
  • Interaction with other features. In a classic priority queue, a message expires only when it reaches the head of the queue. A queue with a length limit drops messages from the head, so it can drop a message of high priority to make room for one of low priority.2

When not to use it

The Azure page names two cases.1

  • All work items are of the same importance, and FIFO order is more important than priority.
  • Tasks of different priority depend on each other's order, and a change of order gives wrong results or needs complex coordination.

RabbitMQ also asks for simpler alternatives first, because a priority queue is harder to reason about than a FIFO queue. Its example is three queues, priority.low, priority.medium and priority.high, which avoid head-of-line blocking and keep the normal delivery order in each queue.2

Queue-based load leveling. If the producers can send faster than the consumers process, the Azure page suggests the combination with a queue that buffers the bursts.1

Competing consumers. The Azure page lists Competing Consumers as a related pattern: several consumers read the same queue in parallel, and only one of them processes each message.1

Routing by priority. The multiple-queue form sends each message to a queue by its priority value, as a Content-Based Router does. In the Azure example, a filter on a topic sends each message to the subscription of its priority.1

Known uses

  • Azure: the example of the Azure page has a Service Bus topic with two subscriptions, one for each value of a Priority property, which SQL filters select. The consumer of high priority can scale to 200 instances, and the consumer of low priority to 40.1
  • RabbitMQ: classic and quorum queues with message priorities, and the alternative of one queue for each priority class.2

References

  1. Microsoft, Azure Architecture Center, Priority Queue pattern, context and problem; solution; problems and considerations; when to use this pattern; example
  2. RabbitMQ documentation (version 4.4), Priority Queues, what is a priority queue; before adopting priority queues; quorum queues; priority queue behaviour; resource starvation; how priority queues work with consumers; interaction with other features
  3. RabbitMQ documentation (version 4.4), Queues, message ordering; when messages can be reordered

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source