Node.js
Retry and backoff
Learn Bull retry and backoff strategies.
Retry and backoff
If an error occurs while processing a message, Bull automatically retries. Backoff is the wait time between retries. It can be fixed or exponential. This lets temporary errors be overcome automatically.
Example: queue.add(data, { attempts: 3, backoff: { type: "exponential", delay: 1000 } });. The job is retried at most 3 times; the wait grows exponentially (1s, 2s, 4s). Without backoff, a failing job would be retried immediately and stress the system. Backoff is ideal for temporary network errors or service outages. attempts and backoff are used together; attempts sets the count, backoff sets the wait. If all retries fail, the job is permanently failed and queue.on("failed", ...) fires.
Backoff types
There are two backoff types: fixed (a constant wait between retries) and exponential (the wait grows exponentially). Exponential protects the system; each retry waits longer.
Example: { type: "fixed", delay: 2000 } waits 2 seconds between each retry. { type: "exponential", delay: 1000 } grows as 1s, 2s, 4s, 8s. Exponential does not stress the system during long outages; early retries are fast, later ones slow. Fixed is suitable when you want a short, predictable wait. The backoff delay is in milliseconds. Bull also lets you define custom backoff strategies, but fixed and exponential are enough for most cases.
Exercise Add retry and backoff
Use the kuyruk object below. Add a message with retry and backoff using kuyruk.add({ action: "email" }, { attempts: 3, backoff: { type: "exponential", delay: 1000 } }) (use await). Print "Retry set" with console.log.
Show example solution
const Bull = require("bull");
const kuyruk = new Bull("job-queue");
async function add() {
await kuyruk.add({ action: "email" }, { attempts: 3, backoff: { type: "exponential", delay: 1000 } });
}
add();
console.log("Retry set");
Test yourself
-
Complete the attempts value
queue.add(data, { ____: 3, backoff: { type: "exponential", delay: 1000 } });
Show answer
queue.add(data, { attempts: 3, backoff: { type: "exponential", delay: 1000 } });
-
Match each type to its trait
- fixed
- Constant wait
- exponential
- Exponentially growing wait
- attempts
- Retry count
- delay
- Wait duration (ms)
-
Why use backoff?
{ attempts: 3, backoff: { type: "exponential" } }
- To back up Redis
- To respond faster
- To automatically overcome temporary errors
- To update the user interface
Show answer
To automatically overcome temporary errors — Backoff overcomes temporary errors automatically.
Next lesson: Summary - Message queue