Producer
- Node.js course
- Advanced
- Lesson 57/83
- 5 min
Learn to add jobs to the queue with a Bull producer.
Producer
The producer is the side that adds a message to the queue. In Bull you add a message with queue.add(data). The message enters the queue and waits to be processed by a consumer.
Example: queue.add({ user: "Ayşe", action: "email" });. This call returns immediately; the producer does not wait for the email to be sent. The message is stored in Redis and picked up when a consumer is ready. queue.add also takes an optional second parameter: { priority: 1, delay: 5000 }. This sets the message's priority or delay. The producer is usually an API endpoint or a scheduler. Its only job is to drop the message into the queue; it does not do the work itself.
Producer patterns
The producer is usually called from an HTTP endpoint. The request comes in, the producer drops the message into the queue and immediately returns a response. This pushes long-running work to the background and speeds up the user experience.
Example: app.post("/signup", async (req, res) => { await queue.add({ user: req.body.name }); res.json({ message: "Signup received" }); });. As soon as the user signs up they get the Signup received response; the email is sent in the background. This pattern shortens the response time without making the user wait. The producer should be fast and lightweight; it should leave heavy work to the consumer. Multiple producers can write to the same queue; the queue stores messages in order.
Practice Write a producer call
Use the kuyruk object below. Add a message with kuyruk.add({ action: "email", user: "Ayşe" }) (use await). Then print "Message added" with console.log.
Starter code
const Bull = require("bull");
const kuyruk = new Bull("job-queue");
// Inside an async function, add a message to the queue
// write here
// Print "Message added"
// write hereSample solution
const Bull = require("bull");
const kuyruk = new Bull("job-queue");
async function addMessage() {
await kuyruk.add({ action: "email", user: "Ayşe" });
}
addMessage();
console.log("Message added");Expected output
Message added
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the queue.add call
queue.add({ action: "____" });
queue.add({ action: "email" });
Explanation: The action is set to email.
2 Match each piece to its role
| Term | Meaning |
|---|---|
queue.add |
Adds a message to the queue |
priority |
Message priority |
delay |
Delay duration |
producer |
The side that drops the message |
3 When does the producer return a response?
await queue.add(data); res.json({ok:true});- After Redis closes
- After the message is processed
- Right after dropping the message in the queue Correct answer
- After the email is sent
Explanation: The producer returns right after dropping the message.