Programming Search⌘K

Patterncore

Work queue

Also called work queue, task queue, job queue, worker queue.

A work queue holds tasks that several workers take and do. The queue keeps each task until a worker acknowledges it, so a task whose worker fails goes to another worker.

Family
concurrency
Intent
Put tasks on a shared queue so that several workers can take and do them concurrently, and keep each task until a worker acknowledges that the work is done, so that no task is lost when a worker fails.
Also called
Task queue, Job queue

Intent

The main idea behind work queues (also called task queues) is to avoid doing a resource-intensive task immediately and having to wait for it to complete.1 The program puts each task on a queue, and workers take the tasks and do them. The Azure Architecture Center describes the form for distributed systems as the Competing Consumers pattern: enable multiple concurrent consumers to process messages received on the same messaging channel.2

Problem

A program gets more work than one thread can do at once. Some tasks are slow, and the amount of work changes over time. The program must not wait for each task to finish before it accepts the next one. Workers can fail in the middle of a task. If the program gives a task to a worker and then forgets it, a worker that fails takes the task with it.

Solution

Put each task on a queue, and start several workers that take tasks from it. Each task goes to one worker. A worker takes a task, does the work, and then sends an acknowledgment (an ack) to the queue. The queue keeps each task that it gave out until the ack comes.

           ┌─────────── work queue ───────────┐
 producer ─┤ ready: 5 6 7 ...  unacked: 1 2 3 ├─► worker 1: take 1, work, ack 1
           │                                  ├─► worker 2: take 2, work, ack 2
           │   no ack from a lost worker:     ├─► worker 3: take 3, fails
           │   task 3 goes back to ready  ◄───┘
           └──────────────────────────────────┘

An ack tells the queue that a particular message has been received and processed, and that the queue is free to delete it.1 If a consumer dies without sending an ack, RabbitMQ understands that a message was not processed fully and re-queues it; if other consumers are online, it then quickly redelivers it to another consumer.1

The queue also decides which worker gets the next task. By default, RabbitMQ sends each message to the next consumer, in sequence, which is called round-robin.1 With fair dispatch, the queue does not give a new message to a worker until it has processed and acknowledged the previous one.1 The example uses this rule: a worker asks for a task only when it is free.

Example

The program puts ten tasks on a work queue, and three workers take them. Each delivery gets a tag, and the worker acks the tag after the work. The first worker that takes task 4 fails before it does the work and stops. The queue gets no ack for that delivery, so it puts task 4 back, and another worker does it. The queue gives out 11 deliveries for 10 tasks.

tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True

The examples for each language show the same program.

PythonGitHub
import threading
from collections import deque

TASKS = 10
WORKERS = 3
FAILS_ON = 4  # the first worker that takes this task fails before it does the work


class WorkQueue:
    """Hands out tasks and keeps each one until a worker acknowledges it."""

    def __init__(self):
        self.cond = threading.Condition()
        self.ready = deque()
        self.unacked = {}  # delivery tag -> task
        self.pending = 0  # tasks put and not yet acknowledged
        self.tag = 0
        self.deliveries = 0
        self.put_back = 0

    def put(self, task):
        with self.cond:
            self.ready.append(task)
            self.pending += 1
            self.cond.notify_all()

    def get(self):
        """Returns (tag, task), or None when every task is acknowledged."""
        with self.cond:
            while not self.ready and self.pending > 0:
                self.cond.wait(timeout=5)
            if not self.ready:
                return None
            self.tag += 1
            self.deliveries += 1
            self.unacked[self.tag] = self.ready.popleft()
            return self.tag, self.unacked[self.tag]

    def ack(self, tag):
        with self.cond:
            del self.unacked[tag]
            self.pending -= 1
            self.cond.notify_all()

    def worker_lost(self, tag):
        """The worker went away without an ack, so the task goes back on the queue."""
        with self.cond:
            self.ready.append(self.unacked.pop(tag))
            self.put_back += 1
            self.cond.notify_all()


work = WorkQueue()
results = {}
results_lock = threading.Lock()
failed = []


def worker():
    while (delivery := work.get()) is not None:
        tag, task = delivery
        with results_lock:
            fail = task == FAILS_ON and not failed
            if fail:
                failed.append(task)
        if fail:
            work.worker_lost(tag)  # this worker stops here
            return
        with results_lock:
            results[task] = task * task  # the work
        work.ack(tag)  # only after the work is done


for task in range(1, TASKS + 1):
    work.put(task)
threads = [threading.Thread(target=worker) for _ in range(WORKERS)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print("tasks put on the queue:", TASKS)
print("workers:", WORKERS)
print("deliveries:", work.deliveries)
print("tasks put back after a worker failed:", work.put_back)
print("tasks still not acknowledged:", work.pending)
print("every task has a result:", sorted(results) == list(range(1, TASKS + 1)))
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. The standard library has no queue with acknowledgments, so the example has a small WorkQueue class on threading.Condition that keeps each task until its ack.
#include <condition_variable>
#include <deque>
#include <iostream>
#include <map>
#include <mutex>
#include <optional>
#include <thread>
#include <utility>
#include <vector>

constexpr int kTasks = 10;
constexpr int kWorkers = 3;
constexpr int kFailsOn = 4;  // the first worker that takes this task fails before it does the work

// Hands out tasks and keeps each one until a worker acknowledges it.
class WorkQueue {
public:
    void put(int task) {
        std::lock_guard<std::mutex> lk(m_);
        ready_.push_back(task);
        pending_++;
        cv_.notify_all();
    }

    // Returns {tag, task}, or nothing when every task is acknowledged.
    std::optional<std::pair<int, int>> get() {
        std::unique_lock<std::mutex> lk(m_);
        cv_.wait(lk, [&] { return !ready_.empty() || pending_ == 0; });
        if (ready_.empty()) return std::nullopt;
        tag_++;
        deliveries_++;
        unacked_[tag_] = ready_.front();
        ready_.pop_front();
        return std::make_pair(tag_, unacked_[tag_]);
    }

    void ack(int tag) {
        std::lock_guard<std::mutex> lk(m_);
        unacked_.erase(tag);
        pending_--;
        cv_.notify_all();
    }

    // The worker went away without an ack, so the task goes back on the queue.
    void worker_lost(int tag) {
        std::lock_guard<std::mutex> lk(m_);
        ready_.push_back(unacked_[tag]);
        unacked_.erase(tag);
        put_back_++;
        cv_.notify_all();
    }

    int deliveries() { std::lock_guard<std::mutex> lk(m_); return deliveries_; }
    int put_back() { std::lock_guard<std::mutex> lk(m_); return put_back_; }
    int pending() { std::lock_guard<std::mutex> lk(m_); return pending_; }

private:
    std::mutex m_;
    std::condition_variable cv_;
    std::deque<int> ready_;
    std::map<int, int> unacked_;  // delivery tag -> task
    int pending_ = 0;             // tasks put and not yet acknowledged
    int tag_ = 0, deliveries_ = 0, put_back_ = 0;
};

int main() {
    WorkQueue work;
    for (int task = 1; task <= kTasks; task++) work.put(task);

    std::mutex mu;
    std::map<int, int> results;
    bool failed = false;
    std::vector<std::thread> threads;
    for (int i = 0; i < kWorkers; i++) {
        threads.emplace_back([&] {
            while (auto delivery = work.get()) {
                auto [tag, task] = *delivery;
                bool fail;
                {
                    std::lock_guard<std::mutex> lk(mu);
                    fail = task == kFailsOn && !failed;
                    if (fail) failed = true;
                }
                if (fail) {
                    work.worker_lost(tag);  // this worker stops here
                    return;
                }
                {
                    std::lock_guard<std::mutex> lk(mu);
                    results[task] = task * task;  // the work
                }
                work.ack(tag);  // only after the work is done
            }
        });
    }
    for (auto& t : threads) t.join();

    bool all = results.size() == kTasks && results.begin()->first == 1 && results.rbegin()->first == kTasks;
    std::cout << "tasks put on the queue: " << kTasks << "\n";
    std::cout << "workers: " << kWorkers << "\n";
    std::cout << "deliveries: " << work.deliveries() << "\n";
    std::cout << "tasks put back after a worker failed: " << work.put_back() << "\n";
    std::cout << "tasks still not acknowledged: " << work.pending() << "\n";
    std::cout << "every task has a result: " << (all ? "True" : "False") << "\n";
}
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. A WorkQueue class on std::mutex and std::condition_variable, with std::optional for the delivery.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    static final int TASKS = 10;
    static final int WORKERS = 3;
    static final int FAILS_ON = 4; // the first worker that takes this task fails before it does the work

    // Hands out tasks and keeps each one until a worker acknowledges it.
    static class WorkQueue {
        private final ArrayDeque<Integer> ready = new ArrayDeque<>();
        private final Map<Integer, Integer> unacked = new HashMap<>(); // delivery tag -> task
        int pending = 0; // tasks put and not yet acknowledged
        private int tag = 0;
        int deliveries = 0;
        int putBack = 0;

        synchronized void put(int task) {
            ready.addLast(task);
            pending++;
            notifyAll();
        }

        // Returns {tag, task}, or null when every task is acknowledged.
        synchronized int[] get() throws InterruptedException {
            while (ready.isEmpty() && pending > 0) wait(5000);
            if (ready.isEmpty()) return null;
            tag++;
            deliveries++;
            unacked.put(tag, ready.removeFirst());
            return new int[] {tag, unacked.get(tag)};
        }

        synchronized void ack(int tag) {
            unacked.remove(tag);
            pending--;
            notifyAll();
        }

        // The worker went away without an ack, so the task goes back on the queue.
        synchronized void workerLost(int tag) {
            ready.addLast(unacked.remove(tag));
            putBack++;
            notifyAll();
        }
    }

    static final WorkQueue work = new WorkQueue();
    static final TreeMap<Integer, Integer> results = new TreeMap<>();
    static boolean failed = false;

    static void worker() {
        try {
            int[] delivery;
            while ((delivery = work.get()) != null) {
                int tag = delivery[0], task = delivery[1];
                boolean fail;
                synchronized (results) {
                    fail = task == FAILS_ON && !failed;
                    if (fail) failed = true;
                }
                if (fail) {
                    work.workerLost(tag); // this worker stops here
                    return;
                }
                synchronized (results) {
                    results.put(task, task * task); // the work
                }
                work.ack(tag); // only after the work is done
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int task = 1; task <= TASKS; task++) work.put(task);
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < WORKERS; i++) threads.add(new Thread(Main::worker));
        for (Thread t : threads) t.start();
        for (Thread t : threads) t.join();

        boolean all = results.size() == TASKS && results.firstKey() == 1 && results.lastKey() == TASKS;
        System.out.println("tasks put on the queue: " + TASKS);
        System.out.println("workers: " + WORKERS);
        System.out.println("deliveries: " + work.deliveries);
        System.out.println("tasks put back after a worker failed: " + work.putBack);
        System.out.println("tasks still not acknowledged: " + work.pending);
        System.out.println("every task has a result: " + (all ? "True" : "False"));
    }
}
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. A WorkQueue class with synchronized methods and wait and notifyAll. A BlockingQueue alone forgets a task when a worker takes it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

// Hands out tasks and keeps each one until a worker acknowledges it.
class WorkQueue
{
    readonly object gate = new object();
    readonly Queue<int> ready = new Queue<int>();
    readonly Dictionary<int, int> unacked = new Dictionary<int, int>(); // delivery tag -> task
    int tag;
    public int Pending; // tasks put and not yet acknowledged
    public int Deliveries;
    public int PutBack;

    public void Put(int task)
    {
        lock (gate)
        {
            ready.Enqueue(task);
            Pending++;
            Monitor.PulseAll(gate);
        }
    }

    // Returns (tag, task), or null when every task is acknowledged.
    public (int Tag, int Task)? Get()
    {
        lock (gate)
        {
            while (ready.Count == 0 && Pending > 0) Monitor.Wait(gate, 5000);
            if (ready.Count == 0) return null;
            tag++;
            Deliveries++;
            unacked[tag] = ready.Dequeue();
            return (tag, unacked[tag]);
        }
    }

    public void Ack(int t)
    {
        lock (gate)
        {
            unacked.Remove(t);
            Pending--;
            Monitor.PulseAll(gate);
        }
    }

    // The worker went away without an ack, so the task goes back on the queue.
    public void WorkerLost(int t)
    {
        lock (gate)
        {
            ready.Enqueue(unacked[t]);
            unacked.Remove(t);
            PutBack++;
            Monitor.PulseAll(gate);
        }
    }
}

class Program
{
    const int Tasks = 10;
    const int Workers = 3;
    const int FailsOn = 4; // the first worker that takes this task fails before it does the work

    static readonly WorkQueue work = new WorkQueue();
    static readonly SortedDictionary<int, int> results = new SortedDictionary<int, int>();
    static bool failed;

    static void Worker()
    {
        while (work.Get() is (int tag, int task))
        {
            bool fail;
            lock (results)
            {
                fail = task == FailsOn && !failed;
                if (fail) failed = true;
            }
            if (fail)
            {
                work.WorkerLost(tag); // this worker stops here
                return;
            }
            lock (results) results[task] = task * task; // the work
            work.Ack(tag); // only after the work is done
        }
    }

    static void Main()
    {
        for (int task = 1; task <= Tasks; task++) work.Put(task);
        var threads = Enumerable.Range(0, Workers).Select(_ => new Thread(Worker)).ToList();
        foreach (var t in threads) t.Start();
        foreach (var t in threads) t.Join();

        bool all = results.Keys.SequenceEqual(Enumerable.Range(1, Tasks));
        Console.WriteLine("tasks put on the queue: " + Tasks);
        Console.WriteLine("workers: " + Workers);
        Console.WriteLine("deliveries: " + work.Deliveries);
        Console.WriteLine("tasks put back after a worker failed: " + work.PutBack);
        Console.WriteLine("tasks still not acknowledged: " + work.Pending);
        Console.WriteLine("every task has a result: " + (all ? "True" : "False"));
    }
}
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. A WorkQueue class on lock, Monitor.Wait and Monitor.PulseAll, with a nullable tuple for the delivery.
JavaScriptGitHub
const TASKS = 10;
const WORKERS = 3;
const FAILS_ON = 4; // the first worker that takes this task fails before it does the work

// Hands out tasks and keeps each one until a worker acknowledges it.
class WorkQueue {
  constructor() {
    this.ready = [];
    this.unacked = new Map(); // delivery tag -> task
    this.pending = 0; // tasks put and not yet acknowledged
    this.tag = 0;
    this.deliveries = 0;
    this.putBack = 0;
    this.waiters = [];
  }

  wake() {
    for (const w of this.waiters.splice(0)) w();
  }

  put(task) {
    this.ready.push(task);
    this.pending++;
    this.wake();
  }

  // Resolves to [tag, task], or null when every task is acknowledged.
  async get() {
    while (this.ready.length === 0 && this.pending > 0) {
      await new Promise((resolve) => this.waiters.push(resolve));
    }
    if (this.ready.length === 0) return null;
    this.tag++;
    this.deliveries++;
    this.unacked.set(this.tag, this.ready.shift());
    return [this.tag, this.unacked.get(this.tag)];
  }

  ack(tag) {
    this.unacked.delete(tag);
    this.pending--;
    this.wake();
  }

  // The worker went away without an ack, so the task goes back on the queue.
  workerLost(tag) {
    this.ready.push(this.unacked.get(tag));
    this.unacked.delete(tag);
    this.putBack++;
    this.wake();
  }
}

const work = new WorkQueue();
const results = new Map();
let failed = false;

async function worker() {
  let delivery;
  while ((delivery = await work.get()) !== null) {
    const [tag, task] = delivery;
    if (task === FAILS_ON && !failed) {
      failed = true;
      work.workerLost(tag); // this worker stops here
      return;
    }
    await new Promise((resolve) => setTimeout(resolve, 1)); // the work takes time
    results.set(task, task * task);
    work.ack(tag); // only after the work is done
  }
}

async function main() {
  for (let task = 1; task <= TASKS; task++) work.put(task);
  const workers = [];
  for (let i = 0; i < WORKERS; i++) workers.push(worker());
  await Promise.all(workers);

  const all = [...results.keys()].sort((a, b) => a - b).join() === Array.from({ length: TASKS }, (_, i) => i + 1).join();
  console.log("tasks put on the queue: " + TASKS);
  console.log("workers: " + WORKERS);
  console.log("deliveries: " + work.deliveries);
  console.log("tasks put back after a worker failed: " + work.putBack);
  console.log("tasks still not acknowledged: " + work.pending);
  console.log("every task has a result: " + (all ? "True" : "False"));
}

main();
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. The same WorkQueue class for async workers on one event loop. It shows the ack and the redelivery, not parallel work.
TypeScriptGitHub
const TASKS = 10;
const WORKERS = 3;
const FAILS_ON = 4; // the first worker that takes this task fails before it does the work

// Hands out tasks and keeps each one until a worker acknowledges it.
class WorkQueue {
  ready: number[] = [];
  unacked = new Map<number, number>(); // delivery tag -> task
  pending = 0; // tasks put and not yet acknowledged
  tag = 0;
  deliveries = 0;
  putBack = 0;
  waiters: (() => void)[] = [];

  wake(): void {
    for (const w of this.waiters.splice(0)) w();
  }

  put(task: number): void {
    this.ready.push(task);
    this.pending++;
    this.wake();
  }

  // Resolves to [tag, task], or null when every task is acknowledged.
  async get(): Promise<[number, number] | null> {
    while (this.ready.length === 0 && this.pending > 0) {
      await new Promise<void>((resolve) => this.waiters.push(resolve));
    }
    if (this.ready.length === 0) return null;
    this.tag++;
    this.deliveries++;
    this.unacked.set(this.tag, this.ready.shift()!);
    return [this.tag, this.unacked.get(this.tag)!];
  }

  ack(tag: number): void {
    this.unacked.delete(tag);
    this.pending--;
    this.wake();
  }

  // The worker went away without an ack, so the task goes back on the queue.
  workerLost(tag: number): void {
    this.ready.push(this.unacked.get(tag)!);
    this.unacked.delete(tag);
    this.putBack++;
    this.wake();
  }
}

const work = new WorkQueue();
const results = new Map<number, number>();
let failed = false;

async function worker(): Promise<void> {
  let delivery: [number, number] | null;
  while ((delivery = await work.get()) !== null) {
    const [tag, task] = delivery;
    if (task === FAILS_ON && !failed) {
      failed = true;
      work.workerLost(tag); // this worker stops here
      return;
    }
    await new Promise<void>((resolve) => setTimeout(resolve, 1)); // the work takes time
    results.set(task, task * task);
    work.ack(tag); // only after the work is done
  }
}

async function main(): Promise<void> {
  for (let task = 1; task <= TASKS; task++) work.put(task);
  const workers: Promise<void>[] = [];
  for (let i = 0; i < WORKERS; i++) workers.push(worker());
  await Promise.all(workers);

  const all = [...results.keys()].sort((a, b) => a - b).join() === Array.from({ length: TASKS }, (_, i) => i + 1).join();
  console.log("tasks put on the queue: " + TASKS);
  console.log("workers: " + WORKERS);
  console.log("deliveries: " + work.deliveries);
  console.log("tasks put back after a worker failed: " + work.putBack);
  console.log("tasks still not acknowledged: " + work.pending);
  console.log("every task has a result: " + (all ? "True" : "False"));
}

main();
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. The same typed WorkQueue class for async workers on one event loop. It shows the ack and the redelivery, not parallel work.
package main

import (
	"fmt"
	"sync"
)

const (
	tasks   = 10
	workers = 3
	failsOn = 4 // the first worker that takes this task fails before it does the work
)

// WorkQueue hands out tasks and keeps each one until a worker acknowledges it.
type WorkQueue struct {
	mu         sync.Mutex
	cond       *sync.Cond
	ready      []int
	unacked    map[int]int // delivery tag -> task
	pending    int         // tasks put and not yet acknowledged
	tag        int
	deliveries int
	putBack    int
}

func NewWorkQueue() *WorkQueue {
	q := &WorkQueue{unacked: map[int]int{}}
	q.cond = sync.NewCond(&q.mu)
	return q
}

func (q *WorkQueue) Put(task int) {
	q.mu.Lock()
	defer q.mu.Unlock()
	q.ready = append(q.ready, task)
	q.pending++
	q.cond.Broadcast()
}

// Get returns a tag and a task, or ok == false when every task is acknowledged.
func (q *WorkQueue) Get() (tag, task int, ok bool) {
	q.mu.Lock()
	defer q.mu.Unlock()
	for len(q.ready) == 0 && q.pending > 0 {
		q.cond.Wait()
	}
	if len(q.ready) == 0 {
		return 0, 0, false
	}
	q.tag++
	q.deliveries++
	task, q.ready = q.ready[0], q.ready[1:]
	q.unacked[q.tag] = task
	return q.tag, task, true
}

func (q *WorkQueue) Ack(tag int) {
	q.mu.Lock()
	defer q.mu.Unlock()
	delete(q.unacked, tag)
	q.pending--
	q.cond.Broadcast()
}

// WorkerLost puts the task back on the queue, because its worker went away without an ack.
func (q *WorkQueue) WorkerLost(tag int) {
	q.mu.Lock()
	defer q.mu.Unlock()
	q.ready = append(q.ready, q.unacked[tag])
	delete(q.unacked, tag)
	q.putBack++
	q.cond.Broadcast()
}

func main() {
	work := NewWorkQueue()
	for task := 1; task <= tasks; task++ {
		work.Put(task)
	}

	var mu sync.Mutex
	results := map[int]int{}
	failed := false
	var wg sync.WaitGroup
	for i := 0; i < workers; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for {
				tag, task, ok := work.Get()
				if !ok {
					return
				}
				mu.Lock()
				fail := task == failsOn && !failed
				if fail {
					failed = true
				}
				mu.Unlock()
				if fail {
					work.WorkerLost(tag) // this worker stops here
					return
				}
				mu.Lock()
				results[task] = task * task // the work
				mu.Unlock()
				work.Ack(tag) // only after the work is done
			}
		}()
	}
	wg.Wait()

	all := len(results) == tasks
	for task := 1; task <= tasks; task++ {
		if _, found := results[task]; !found {
			all = false
		}
	}
	fmt.Println("tasks put on the queue:", tasks)
	fmt.Println("workers:", workers)
	fmt.Println("deliveries:", work.deliveries)
	fmt.Println("tasks put back after a worker failed:", work.putBack)
	fmt.Println("tasks still not acknowledged:", work.pending)
	if all {
		fmt.Println("every task has a result: True")
	} else {
		fmt.Println("every task has a result: False")
	}
}
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. A WorkQueue type on sync.Mutex and sync.Cond. A plain channel forgets a value when a goroutine receives it, so it cannot put a task back.
RustGitHub
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;

const TASKS: i32 = 10;
const WORKERS: usize = 3;
const FAILS_ON: i32 = 4; // the first worker that takes this task fails before it does the work

#[derive(Default)]
struct State {
    ready: VecDeque<i32>,
    unacked: HashMap<u32, i32>, // delivery tag -> task
    pending: i32,               // tasks put and not yet acknowledged
    tag: u32,
    deliveries: u32,
    put_back: u32,
}

// Hands out tasks and keeps each one until a worker acknowledges it.
#[derive(Default)]
struct WorkQueue {
    state: Mutex<State>,
    cond: Condvar,
}

impl WorkQueue {
    fn put(&self, task: i32) {
        let mut s = self.state.lock().unwrap();
        s.ready.push_back(task);
        s.pending += 1;
        self.cond.notify_all();
    }

    // Returns (tag, task), or None when every task is acknowledged.
    fn get(&self) -> Option<(u32, i32)> {
        let mut s = self.state.lock().unwrap();
        while s.ready.is_empty() && s.pending > 0 {
            s = self.cond.wait(s).unwrap();
        }
        let task = s.ready.pop_front()?;
        s.tag += 1;
        s.deliveries += 1;
        let tag = s.tag;
        s.unacked.insert(tag, task);
        Some((tag, task))
    }

    fn ack(&self, tag: u32) {
        let mut s = self.state.lock().unwrap();
        s.unacked.remove(&tag);
        s.pending -= 1;
        self.cond.notify_all();
    }

    // The worker went away without an ack, so the task goes back on the queue.
    fn worker_lost(&self, tag: u32) {
        let mut s = self.state.lock().unwrap();
        let task = s.unacked.remove(&tag).unwrap();
        s.ready.push_back(task);
        s.put_back += 1;
        self.cond.notify_all();
    }
}

fn main() {
    let work = Arc::new(WorkQueue::default());
    for task in 1..=TASKS {
        work.put(task);
    }

    // The results, and whether a worker has failed yet.
    let shared = Arc::new(Mutex::new((BTreeMap::new(), false)));
    let threads: Vec<_> = (0..WORKERS)
        .map(|_| {
            let work = Arc::clone(&work);
            let shared = Arc::clone(&shared);
            thread::spawn(move || {
                while let Some((tag, task)) = work.get() {
                    let fail = {
                        let mut g = shared.lock().unwrap();
                        let fail = task == FAILS_ON && !g.1;
                        if fail {
                            g.1 = true;
                        }
                        fail
                    };
                    if fail {
                        work.worker_lost(tag); // this worker stops here
                        return;
                    }
                    shared.lock().unwrap().0.insert(task, task * task); // the work
                    work.ack(tag); // only after the work is done
                }
            })
        })
        .collect();
    for t in threads {
        t.join().unwrap();
    }

    let results = &shared.lock().unwrap().0;
    let all = results.keys().copied().eq(1..=TASKS);
    let s = work.state.lock().unwrap();
    println!("tasks put on the queue: {}", TASKS);
    println!("workers: {}", WORKERS);
    println!("deliveries: {}", s.deliveries);
    println!("tasks put back after a worker failed: {}", s.put_back);
    println!("tasks still not acknowledged: {}", s.pending);
    println!("every task has a result: {}", if all { "True" } else { "False" });
}
Output
tasks put on the queue: 10
workers: 3
deliveries: 11
tasks put back after a worker failed: 1
tasks still not acknowledged: 0
every task has a result: True
  • Verdict: idiom. A WorkQueue on Mutex and Condvar, shared through Arc, with Option for the delivery.

Consequences

Benefits:

  • Several workers do tasks at the same time. A long task does not stop the other workers, because a message that requires some long-running processing does not prevent other consumer service instances from processing other messages concurrently.2
  • The producer and the workers are independent. The queue functions as a buffer between application instances and consumer service instances, so it can take a sudden increase in work.2
  • The program can add or remove workers when the amount of work changes.2
  • A task is not lost when a worker fails, because the queue keeps it until the ack.

Liabilities:

  • A task can be done more than once. The message queue ensures that each message is delivered at least once,2 not exactly once. If a worker does the work and fails before the ack, the queue gives the task to another worker. Operations that can run twice must be idempotent, which minimizes the effects when a worker processes a single message more than once.2
  • The order is not fixed. The order in which consumer service instances receive messages is not guaranteed and does not necessarily show the order in which the messages were created.2
  • A bad task can fail every worker that takes it. The system should prevent such poison messages from returning to the queue indefinitely, and store their details elsewhere instead.2
  • A missing ack has a cost. It is a common mistake to miss the ack: messages are redelivered when the client quits, and RabbitMQ uses more and more memory because it cannot release any unacknowledged messages.1

In this program, the queue forgets each task when a worker takes it. This is like an ack before the work:

This code runs but gives a wrong answer on purpose.

import queue
import threading

tasks = queue.Queue()
for n in range(1, 11):
    tasks.put(n)
results = {}
failed = []
lock = threading.Lock()


def worker():
    while True:
        try:
            task = tasks.get_nowait()  # the queue forgets the task here: there is no ack
        except queue.Empty:
            return
        with lock:
            if task == 4 and not failed:
                failed.append(task)
                return  # this worker fails before it does the work
            results[task] = task * task


threads = [threading.Thread(target=worker) for _ in range(3)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("tasks with a result:", len(results))
print("lost tasks:", sorted(set(range(1, 11)) - set(results)))
Output
tasks with a result: 9
lost tasks: [4]

RabbitMQ describes the same loss: when the queue marks a message for deletion as soon as it delivers the message, the message that a terminated worker was processing is lost.1

When not to use it

Do not use a work queue when the tasks depend on each other or must run in a fixed order. The Azure guide says that the pattern might not be suitable when there is a high degree of dependence between tasks, or when tasks must run synchronously and the application logic must wait for each task to complete before it continues.2 A pipeline fits work that goes through fixed steps. If the tasks run in one process and a lost task is not a problem, a thread pool is simpler, because it needs no acks.

  • Idempotent handler. At-least-once delivery can give a worker the same task twice. The handler keeps the IDs of the tasks that it has done and ignores a second delivery of the same ID:
# Delivery is at least once: the worker that first took payment 4 failed
# after it did the work and before its ack, so the queue delivered it again.
deliveries = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (4, 40)]

balance = 0
for payment_id, amount in deliveries:
    balance += amount
print("balance, handler that is not idempotent:", balance)

balance, done = 0, set()
for payment_id, amount in deliveries:
    if payment_id in done:
        continue  # a duplicate delivery: the effect is already applied
    balance += amount
    done.add(payment_id)
print("balance, idempotent handler:", balance)
Output
balance, handler that is not idempotent: 190
balance, idempotent handler: 150
  • In-process work queue. In Python, a worker calls Queue.task_done() after each get(), which tells the queue that the processing on the task is complete, and Queue.join() blocks until all items in the queue have been gotten and processed.3 This counts the tasks that are not finished, but it does not put back a task whose worker failed.
  • Dead-letter queue. Azure Service Bus can automatically send messages to a dead-letter queue after the delivery count exceeds a configured threshold.2 This stops a poison message.
  • Result queue. A worker process can pass results back to the application logic through a dedicated message reply queue.2
  • Producer-consumer is the bounded buffer between threads that a work queue is built on. A work queue adds acks and redelivery.
  • Command objects are a common form for the tasks.

Known uses

  • RabbitMQ: the work queues tutorial distributes time-consuming tasks among multiple workers, with manual acks and basic_qos(prefetch_count=1) for fair dispatch.1
  • Azure: Service Bus queues and Azure Functions queue triggers together directly implement the Competing Consumers pattern.2
  • Python: queue.Queue with task_done() and join() is the in-process form.3

References

  1. RabbitMQ tutorial, Work Queues (using the Pika Python client), the introduction; Round-robin dispatching; Message acknowledgment; Fair dispatch
  2. Competing Consumers pattern, Azure Architecture Center, the introduction; Solution; Problems and considerations; When to use this pattern; Example
  3. queue, A synchronized queue class, Python documentation, Queue.task_done; Queue.join

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