Queues and messaging: Resque, AMQP, MQTT and ZeroMQ™

Jennifer

Background jobs on Redis™, a RabbitMQ™ broker with acks, pub/sub for small devices, and ZeroMQ™ without any broker: four modules that ship with the interpreter.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 23

Why a queue, and four shapes

Producer and consumer no longer need to be alive, fast and correct at the same moment: decoupling, retries, load levelling, fan-out.

ModuleShapeServerTypical use
resque.jjob queueRedisbackground jobs of a web app
amqp.jbroker with exchanges and acksRabbitMQservices talking to services
mqtt.jlightweight pub/subMosquitto, ...sensors, devices, dashboards
zmq.jsockets with patternsnonepipelines, peers using libzmq

All four are bundled: import "zmq.j" as zmq; needs no jvc and no deck.

2 / 23

Resque: enqueue a job

def db as redis.Session init redis.connect(redis.Options{
    host: "127.0.0.1", port: 16380, security: transport.Security.None,
    user: "", password: "", db: 0});
resque.enqueue($db, "mail", "SendWelcome", ["ada@example.org", "en"]);
resque.enqueue($db, "high", "ResizeImage", ["photo-17.jpg", "800"]);
resque.enqueue($db, "high", "Explode", []);
io.printf("%s\n", redis.lrange($db, "resque:queue:mail", 0, 0)[0]);
queues high,mail, pending 4
{"class":"SendWelcome","args":["ada@example.org","en"]}
3 / 23

A worker is your own loop

func perform(job as resque.Job) {
    match ($job.class) {
        when "SendWelcome" { io.printf("mail %s\n", $job.args[0]); }
        when "ResizeImage" { io.printf("resize %s\n", $job.args[0]); }
        else { throw Error{kind: "job", message: "no handler"}; }
    }
}
while (true) {   # $queues is ["high", "mail"]
    def job as resque.Job init resque.reserveBlocking($db, $queues, 2);
    if ($job.class == "") { break; }   # idle for 2 s
    run($db, $job);
}
4 / 23

Failures and retries are yours

func run(db as redis.Session, job as resque.Job) {
    for (def attempt in 1..ATTEMPTS + 1) {
        try { perform($job); return; } catch (e) {
            if ($attempt == ATTEMPTS) {
                resque.fail($db, $job, $e.message);
            } else {
                time.sleep(time.fromMilliseconds(100 * $attempt));
            }
        }
    }
}
failed list: high / Explode / no handler
5 / 23

Same queue, Ruby on the other side

$ ruby interop.rb enqueue     # Resque.enqueue_to(:mail, ...)
$ jennifer run rq_interop.j
jennifer got SendWelcome [carol@example.org, fr]
jennifer got SendWelcome [dave@example.org, 7]
$ ruby interop.rb work        # Resque::Worker.new(:mail)
ruby worker: welcome erin@example.org (nl)
6 / 23

AMQP: exchange, queue, binding

def c as amqp.Conn init amqp.connect(amqp.withPort(
    amqp.options("127.0.0.1", "demo", "changeme"), 25672));
amqp.declareExchange($c, "orders", "topic");
amqp.declareQueue($c, "billing", true);            # durable
amqp.bindQueue($c, "billing", "orders", "order.*");
amqp.confirmSelect($c);
def p as amqp.Properties init amqp.Properties{persistent: true,
    contentType: "application/json", correlationId: "", replyTo: ""};
amqp.publishWith($c, "orders", "order.created", $body, $p);
io.printf("order %d confirmed: %t\n", $id, amqp.waitConfirm($c));
7 / 23

Confirms: one wait per publish

order 17 confirmed: true
order 18 confirmed: true
order 19 confirmed: true
unroutable confirmed: true
8 / 23

Pull: get, then ack or nack

while (true) {
    def m as amqp.Message init amqp.get($c, "billing", false);
    if ($m.empty) { break; }
    try {
        def v as json.Value init json.decode(text($m.body));
        io.printf("bill order %d\n", json.asInt($v, "/order"));
        amqp.ack($c, $m.deliveryTag);
    } catch (e) {   # json.decode failed: kind "runtime"
        amqp.nack($c, $m.deliveryTag, false);   # drop, or dead-letter
    }
}
bill order 20
9 / 23

Push: a consumer in its own spawn

def worker as task of int init spawn {
    def c as amqp.Conn init amqp.connect($opts);   # its own connection
    def tag as string init amqp.consume($c, "billing", false);
    for (def i in 0..3) {
        def d as amqp.Delivery init amqp.receiveDelivery($c);
        io.printf("%s redelivered=%t\n", text($d.body),
            $d.redelivered);
        amqp.ack($c, $d.deliveryTag);
    }
    amqp.cancelConsume($c, $tag);
    amqp.close($c);
    return 3;
};
10 / 23

What happens to an unacked message

$ jennifer run amqp_crash.j      # consume, take one, exit without ack
got {"order": 17}, crashing before the ack
$ rabbitmqctl list_queues name messages_ready messages_unacknowledged
billing 0       3
$ jennifer run amqp_consume.j
{"order": 17} redelivered=true
{"order": 18} redelivered=true
{"order": 19} redelivered=true
11 / 23

MQTT: topics and wildcards

def sub as mqtt.Client init open("dashboard");
$sub = mqtt.subscribe($sub, "home/+/temp");      # one level
$sub = mqtt.subscribeQos1($sub, "alarm/#");      # any depth
def pub as mqtt.Client init open("sensors");
mqtt.publish($pub, "home/kitchen/temp", "21.5");
mqtt.publish($pub, "home/kitchen/humidity", "48");
mqtt.publish($pub, "home/garage/temp", "9.0");
mqtt.publishQos1($pub, "alarm/garage/door",
    encoding.encode("utf-8", "open"), false);
home/kitchen/temp = 21.5
home/garage/temp = 9.0
alarm/garage/door = open
12 / 23

QoS 0 and QoS 1

QoS 0 (publish)QoS 1 (publishQos1)
Handshakenone, fire and forgetPUBACK from the broker
No answermessage may be goneresent with DUP, 5 tries, 5 s apart
Gives upnever knowsthrows kind "mqtt"
Guaranteeat most onceat least once
13 / 23

Retained messages and the last will

def will as mqtt.Will init mqtt.Will{topic: "status/sensor7",
    payload: encoding.encode("utf-8", "offline"),
    qos: 1, retain: true};
def sensor as mqtt.Client init mqtt.connectWith(opts("sensor7"),
    $will, true);
mqtt.publishRetain($sensor, "status/sensor7", "online", true);
def late as mqtt.Client init mqtt.connect(opts("late"));
$late = mqtt.subscribe($late, "status/+");
show($late);                    # status/sensor7 = online
net.close($sensor.conn);        # power cut: no DISCONNECT
show($late);                    # status/sensor7 = offline
14 / 23

ZeroMQ: no broker, just sockets

def l as zmq.Listener init zmq.listen("REP", "127.0.0.1:0");
def server as task of int init spawn {
    def s as zmq.Socket init zmq.accept($l);       # one peer
    def req as zmq.Message init zmq.receive($s);
    zmq.reply($s, $req, [utf8("pong " + zmq.text($req))]);
    return 1;
};
def c as zmq.Socket init zmq.connect("REQ", zmq.address($l));
zmq.sendText($c, "ping");
io.printf("%s, from a %s peer\n", zmq.text(zmq.receive($c)),
    $c.peerKind);
pong ping, from a REP peer
15 / 23

PUSH / PULL: a ventilator and its workers

func worker(addr as string) {
    def s as zmq.Socket init zmq.connect("PULL", $addr);
    def done as int init 0;
    while (true) {
        if (zmq.text(zmq.receive($s)) == "END") { return $done; }
        time.sleep(time.fromMilliseconds(100));   # the "work"
        $done = $done + 1;
    }
}
for (def w in 0..4) { $pool[] = spawn { return worker($addr); }; }
for (def w in 0..4) { $peers[] = zmq.accept($l); }   # PUSH
for (def n in 0..12) { zmq.sendText($peers[$n % 4], "job {$n}"); }
per worker [3, 3, 3, 3], 301 ms
16 / 23

PUB / SUB: prefixes, filtered by the subscriber

def s as zmq.Socket init zmq.subscribe(
    zmq.connect("SUB", $addr), "weather.");      # in a spawn
for (def i in 0..2) {
    def m as zmq.Message init zmq.receive($s);   # skips the rest
    io.printf("%s = %s\n", zmq.text($m), txt($m.frames[1]));
}
# the publisher, after zmq.accept($l):
zmq.send($pub, [b("weather.vienna"), b("12.5")]);
zmq.send($pub, [b("traffic.a23"), b("jam")]);
zmq.send($pub, [b("weatherstation.7"), b("up")]);
zmq.send($pub, [b("weather.linz"), b("9.0")]);
weather.vienna = 12.5
weather.linz = 9.0
17 / 23

Talking to libzmq, with PLAIN

$ jennifer run slowjoin.j   # SUB, 0.5 s after a pyzmq PUB started
first tick seen: 10
$ jennifer run plain.j      # REQ to a pyzmq REP with PLAIN and ZAP
python got hello
refused, peerReason 400
def o as zmq.Options init zmq.defaultOptions();
$o.mechanism = "PLAIN";      # user and password in clear text
$o.username = "ada";
$o.password = $password;
def s as zmq.Socket init zmq.connectWith("REQ", ADDR, $o);
18 / 23

Delivery guarantees compared

Lost whenTwice when
Resqueworker dies after reserve (LPOP)never by itself
AMQP, autoAck trueconsumer dies with messages in handnever
AMQP, manual ackunconfirmed publish, transient on restartconsumer dies before ack
MQTT QoS 0link drops, nobody subscribednever
MQTT QoS 1subscriber offline, no persistent sessionPUBACK lost, DUP resent
ZeroMQno peer yet, slow joiner, peer or process diesnever

At most once, or at least once and idempotent handlers. Nothing here is exactly once.

19 / 23

Errors you will actually see

CaseKindMessage, shortened
AMQP, no brokernetnet.connect: ...: connection refused
AMQP, bad passwordclosedconnection closed after 0 of 1 bytes
AMQP, no such queueamqp404 NOT_FOUND - no queue 'jobs' ...
MQTT, bad passwordmqttCONNACK code 5 (not authorized)
ZeroMQ, bad PLAIN passwordzmqpeer refused the handshake: ...
ZeroMQ, REQ to a PULLzmqa REQ socket cannot talk to a PULL peer
20 / 23

Reconnect with a backoff

func reconnect(c as mqtt.Client) {
    def pause as int init 250;
    while (true) {
        try { return mqtt.reconnect($c); } catch (e) {
            if (not ($e.kind == "net" or $e.kind == "closed"
                or $e.kind == "timeout")) { throw $e; }
            time.sleep(time.fromMilliseconds($pause));
            if ($pause < 4000) { $pause = $pause * 2; }
        }
    }
}
lost the broker (closed)
back, 1 subscription(s) restored
21 / 23

A pool of workers with spawn

func worker() {
    def db as redis.Session init redis.connect(OPTS);   # one each
    def done as int init 0;
    while (true) {
        def job as resque.Job init
            resque.reserveBlocking($db, ["thumbs"], 1);
        if ($job.class == "") { return $done; }
        time.sleep(time.fromMilliseconds(200));          # the "work"
        $done = $done + 1;
    }
}
for (def w in 0..4) { $pool[] = spawn { return worker(); }; }
per worker [3, 3, 3, 3], 1628 ms incl. 1 s idle
22 / 23

When to choose which

Docs: resque, amqp, mqtt, zmq

23 / 23