Back to All Articles
DevelopmentOct 15, 20268 min read

How to Build a Dead-Simple Python/Node.js Heartbeat Ping in 3 Lines of Code

You do not need an SDK to monitor your background workers. Here are the exact 3-line code snippets for Python and Node.js to implement rock-solid heartbeat monitoring.

P
Prabin Jha
Founder & Lead Architect
LinkedIn

Key Takeaways (BLUF)

Bottom Line Up Front (BLUF): Heartbeat Monitoring (Dead-Man Switches) is the only reliable way to monitor background workers, Celery queues, and cronjobs. Many APM tools force you to install heavy SDKs just to send a heartbeat. This is entirely unnecessary. A heartbeat ping is literally just an HTTP GET or POST request to a unique URL. In this guide, we provide the exact, copy-pasteable 3-line snippets you need to add heartbeat monitoring to your Python and Node.js applications with zero external dependencies.

Python: The Standard Library Approach

Python developers often default to installing the `requests` library. While `requests` is fantastic, you do not want to introduce a third-party dependency into a lightweight cron script if you can avoid it.

You can use Python's built-in `urllib` to execute the ping securely. We wrap it in a simple `try/except` block to ensure that if the monitoring service is temporarily unreachable, it does not crash your actual business logic.

import urllib.request
import urllib.error

def ping_heartbeat():
    # Replace with your unique WakeMetrics Heartbeat URL
    url = "https://ingest.wakemetrics.com/heartbeat/your-uuid"
    try:
        # Timeout set to 5 seconds to prevent hanging
        urllib.request.urlopen(url, timeout=5)
    except urllib.error.URLError:
        pass  # Fail silently so we don't crash the main application

# --- Your Main Script ---
print("Running database backup...")
# ... do work ...
print("Success!")

# Ping the monitor at the very end of the script
ping_heartbeat()

Node.js: The Native Fetch API

Historically, Node.js developers had to rely on `axios` or the clunky `http` module. However, since Node.js 18, the native `fetch` API is available globally.

Because `fetch` is Promise-based, we can fire the heartbeat request asynchronously in a "fire-and-forget" manner. We attach an empty `.catch()` block to ensure unhandled promise rejections do not crash the Node process.

// The Fire-and-Forget Heartbeat function
const pingHeartbeat = () => {
  const url = "https://ingest.wakemetrics.com/heartbeat/your-uuid";
  
  // fetch is native in Node 18+. AbortController handles the timeout.
  fetch(url, { signal: AbortSignal.timeout(5000) })
    .catch(() => {}); // Catch and ignore network errors
};

// --- Your Main Script ---
async function processQueue() {
  console.log("Processing Stripe webhooks...");
  // ... do work ...
  console.log("Queue processed successfully.");
  
  // Fire and forget at the end of the job
  pingHeartbeat();
}

processQueue();

Adding Telemetry Data (Optional)

If you want to track *how long* your script took to execute, you can easily append a query string to the URL.

For example, in Python: `url = f"https://ingest.wakemetrics.com/heartbeat/your-uuid?duration={execution_time}s"`.

WakeMetrics will automatically parse this query parameter and plot a latency trendline on your dashboard, allowing you to detect performance degradations in your cronjobs over time.

Frequently Asked Questions

Should I use GET or POST for a heartbeat?

For WakeMetrics, a simple HTTP GET is all that is required. If your payload includes extensive telemetry data (like a JSON log dump), you can use a POST request.

Why add a timeout to the HTTP request?

If the monitoring ingest server experiences an outage and drops packets instead of rejecting the connection, a request without a timeout will hang indefinitely. This could leave your cronjob locked in a running state, preventing the next iteration from starting.

What if I am still using Node.js 16?

If you are on an older Node version without native `fetch`, you should use the native `https` module to avoid installing `axios`, although the syntax is much more verbose.

Conclusion

You do not need to install heavy APM agents or third-party SDKs to get world-class observability into your background workers. A 3-line standard library HTTP request is all it takes to trigger a dead-man switch. Secure your cronjobs and Sidekiq workers today—create a free heartbeat monitor on WakeMetrics.

Ready to Upgrade from UptimeRobot?

Migrate in under 60 seconds. Get 15-second checks across 450+ global locations with zero false alerts.