← All lessons
How message queues work
Publish, receive, ack
Checkout
Queue
Worker
checkout.js
app.post("/orders", async (req, res) => { const order = await db.orders.insert(req.body); await queue.send("receipts", { orderId: order.id }); res.status(201).json(order); // the email happens later});worker.js
const msg = await queue.receive("receipts");// hidden from other workers until ack or timeoutawait sendReceiptEmail(msg.body.orderId);await queue.ack(msg);Run the worker yourself ack, crash, or wait
Queue: receipts t = 0 s
Worker
Dead-letter queue
Producer
Worker
Clock
Nothing moves on its own. Time passes only when you press Wait
worker.js
for (;;) { const msg = await queue.receive("receipts", { visibilityTimeout: 30, }); if (!msg) continue; try { const order = JSON.parse(msg.body); await sendReceiptEmail(order); await queue.ack(msg); } catch (err) { log.error(err); // no ack: it comes back after 30 s }}queue.js
createQueue("receipts", { visibilityTimeout: 30, redrivePolicy: { deadLetterTarget: "receipts-dlq", maxReceiveCount: 3, },});A spike hits the queue and the backlog soaks it up
Messages waiting, second by second
Each worker handles 4 messages a second
workers.js
// one worker handles about 4 messages a secondfor (let i = 0; i < WORKERS; i++) { startWorker("receipts");} // the queue absorbs bursts. Watch how long the oldest one waitssetInterval(async () => { const { depth, oldestAgeSec } = await queue.stats("receipts"); if (oldestAgeSec > 10) addWorker();}, 5000);Topics
Next: How idempotency works
Open lesson