How to Monitor Node.js Background Queues and Cron Tasks Using the SDK
When developers think of uptime monitoring, they usually picture active HTTP checks. These check monitors test user-facing endpoints at regular intervals to confirm they return a successful HTTP status code.
However, a huge portion of SaaS logic operates silently in the background:
- Daily database backup routines.
- Hourly synchronization scripts pushing data to accounting platforms.
- Background queue workers processing email blasts or image resizing.
If a background task fails, runs out of memory, or fails to start, your user-facing HTTP endpoints will still return 200 OK. Your primary monitors will report everything is healthy while your system operations silently break.
This guide shows you how to use passive heartbeat monitoring and the official @pingzo/sdk package to ensure your Node.js background tasks run successfully.
Understanding Heartbeat (Passive) Monitoring
Active monitors work by sending requests to your system. Passive monitoring reverses this relationship: your application sends a lightweight request to Pingzo when a background job completes.
This is commonly called a "Heartbeat" or "Dead Man's Snitch" check:
- Define a Schedule: You tell Pingzo how often your job should run (for example: every hour) and a grace period (e.g. 5 minutes).
- Report Success: Your background worker sends a ping to Pingzo at the end of every successful execution.
- Alert on Missed Pings: If Pingzo does not receive a ping within your specified time interval plus the grace period, it immediately triggers your alert channels (WhatsApp, Slack, Telegram).
Installing and Initializing @pingzoapp/sdk
To get started, install the official Pingzo client SDK dependency inside your Node.js project:
npm install @pingzoapp/sdk
Next, initialize the client using your unique monitor token (the pingSecret obtained when creating a Heartbeat monitor inside your Pingzo dashboard):
const Pingzo = require('@pingzoapp/sdk');
const pingzo = new Pingzo('your-secret-id-here');
Code Integration Examples
Example 1: Integrating with node-cron
If you use the node-cron package to schedule cron jobs in your Node.js application, wrap your execution logic in a try-catch block to handle success and failure states:
const cron = require('node-cron');
const Pingzo = require('@pingzoapp/sdk');
const pingzo = new Pingzo('your-cron-secret-id');
// Run a database backup every night at midnight
cron.schedule('0 0 * * *', async () => {
console.log('Starting daily database backup...');
try {
// Execute backup logic
await runBackupDatabase();
// Send success heartbeat to Pingzo
await pingzo.ping();
console.log('Backup completed and heartbeat sent.');
} catch (error) {
console.error('Backup failed:', error);
// Alert Pingzo programmatically about the exact failure
await pingzo.ping('fail', error.message || 'DatabaseBackupError');
}
});
Example 2: Monitoring BullMQ Queue Workers
For asynchronous task queues like BullMQ, report status check-ins directly inside your job process handler:
const { Worker } = require('bullmq');
const Pingzo = require('@pingzoapp/sdk');
const pingzo = new Pingzo('your-queue-secret-id');
const worker = new Worker('image-processing', async (job) => {
try {
await resizeImage(job.data.filePath);
// Ping on success
await pingzo.ping();
} catch (error) {
// Notify Pingzo of failure
await pingzo.ping('fail', `WorkerJobFailed: ${job.id}`);
throw error;
}
});
Best Practices for Heartbeat Monitoring
- Configure Grace Periods Carefully: Network latency and slow executions can delay your job check-in. Always add a reasonable grace period (usually 5 to 10 minutes) to prevent false alerts.
- Observe Rate Limits: Pingzo rate-limits success heartbeats to once every 30 seconds. If your task runs continuously, only trigger the ping at the end of the batch or throttle your API calls.
- Always Track Failure States: Do not just check for success. By sending a
status: 'fail'payload in your catch block, you ensure Pingzo dispatches instant alerts immediately, without waiting for the check interval to expire.
Frequently Asked Questions
1. What happens if my cron job fails to start?
If your server goes offline or the cron daemon fails to launch the task, no ping is sent. Once the scheduled interval plus the grace period expires, Pingzo will flag the monitor as missing and alert you.
2. Can I pass custom error payloads using the SDK?
Yes. The SDK's ping() method accepts two arguments: ping(status, errorMessage). You can pass 'fail' and a descriptive error string to help debug the failure.
3. How do I prevent rate limiting warnings?
If you have jobs running faster than once every 30 seconds, Pingzo will return a 429 Too Many Requests response code. The SDK handles this, and Pingzo will not count rate-limited pings as down. However, it is best practice to space out your checks.
4. Can I use the SDK in frontend client applications?
No. The SDK is designed to run in Node.js server environments. Pings require your private pingSecret, which must never be exposed to public web browsers.
5. Does the SDK support ES module imports?
Yes. The SDK provides both CommonJS (require) and ES Module (import) exports, allowing seamless integration into modern Node.js and TypeScript project environments.