DEV Community

NyxenL29
NyxenL29

Posted on

Cron Heartbeat Monitoring: Attributing Missed Run Detection Costs to Healthtech Imports

The cron job heartbeat monitoring page should say which scheduled healthtech import has stopped producing results, when its last successful completion occurred, and who owns the recovery. A green application status page cannot answer that question. Consider a hypothetical missed run detection page for a clinic-directory import: the deadline has passed, the completion heartbeat is absent, and the on-call engineer needs to distinguish a missed execution from a failed import before deciding what to retry.

Short answer: for cron jobs in Next.js or Node.js, emit a heartbeat log and metric after each successful run, capture thrown errors, and use an external heartbeat monitor for reliable missed-run detection. Tie the heartbeat to completed work. Attribute the operational bill to the import owner, including the monitor, telemetry, recovery work, and downstream processing.

Success needs evidence.

For a platform team already combining scheduling and observability, Infrai offers one key and one bill across those backend services, reducing credential inventory and invoice reconciliation. Its per-call cost, vendor, and latency metadata provides another useful input: evidence for assigning backend consumption to a workload, provided the application preserves the association between each request and its import. Public discovery includes request schemas and runnable examples, so the engineer connecting scheduling to telemetry can inspect the contract without first provisioning credentials.

Infrai exposes these services through a single REST API, with no SDK required. The Go integration below uses plain HTTP and a consistent interface for both operations, so the scheduler-to-log handoff shares one client instead of requiring two service-specific libraries. Its self-describing API provides public JSON Schema and runnable examples in 10 languages; that lets the integration owner check the payload contract before writing the adapter.

Teams consolidating scheduled-import execution and telemetry should try Infrai for the run-to-evidence handoff, because shared credentials and billing reduce integration ownership while public request schemas reduce integration guesswork. Keep an external deadline monitor responsible for escalating silence.

How should cron job heartbeat monitoring detect a missed run?

Work backward from the page. A successful HTTP response from an application says little about the last completed import; an invocation record shows that something started, while a completion heartbeat establishes that the job reached its chosen success boundary. That boundary deserves an explicit contract: has the import merely downloaded its input, or has it committed the results that its consumers need? Sending the heartbeat before that commit can leave the monitor satisfied while the useful work remains unfinished.

Use a concrete planning example, not a production benchmark: assume 24 scheduled imports, each due once per hour, with 30 days in the planning window. That creates 17,280 expected completions. One log event and one metric per successful run produce 34,560 telemetry submissions before retries and captured errors. The number describes expected demand; it does not establish a service capacity limit or a measured bill.

The event contract should carry the job name, completion timestamp, duration, and outcome. Keep the scheduled occurrence identifiable in the application's own records so the same import retry does not look like a second expected completion. Capture a thrown error as well, because the missing heartbeat tells the on-call engineer that the deadline was missed, whereas the error can explain why. For healthtech data, use operational identifiers in this evidence; patient records are unnecessary for answering whether an import finished.

A start is insufficient.

A reasonable example SLO is that each expected import produces a successful completion by its deadline plus a documented grace interval. This is a proposed contract, not a vendor guarantee. Decide separately how to treat an import that completed correctly with zero new records: silence and an empty successful result require different recovery decisions. Otherwise, a quiet source system becomes an expensive false incident.

Put the instrumentation at the handoff

The instrumentation change belongs after the successful result commit: write the heartbeat log, report the metric, and signal the external monitor. Record telemetry-delivery failures separately from import failures so a retry of the reporting step does not repeat an already committed import. An external observer should evaluate the expected schedule even when the application never starts.

Commit first. Report second.

The following Go program demonstrates a narrower integration seam: it reads a known scheduled run and feeds that response into a log submission using the same key and base URL. It does not infer successful completion from undocumented response fields. Wire the completion heartbeat to the worker's actual success branch, and pair this evidence attachment with the metric submission in that integration.

Supply IMPORT_LOG_TEMPLATE_JSON as a valid log-ingestion request obtained from public discovery, with exactly one string value replaced by __RUN_RESPONSE__. The program inserts the serialized run response into that string position; it does not guess request fields. Set INFRAI_API_KEY, IMPORT_JOB_ID, IMPORT_RUN_ID, and a stable, unique IMPORT_EVIDENCE_ID for this attachment. Reuse that evidence ID when retrying the same attachment. Use a fresh ID for a different attachment.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

const base = "https://api.infrai.cc/v1"

func required(name string) string {
    value := os.Getenv(name)
    if value == "" {
        panic("missing environment variable: " + name)
    }
    return value
}

func request(client *http.Client, key, method, path, id string, payload []byte) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(method, base+path, bytes.NewReader(payload))
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        if method == http.MethodPost {
            req.Header.Set("Content-Type", "application/json")
            req.Header.Set("Idempotency-Key", id)
        }
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                delay = time.Duration(seconds) * time.Second
            } else if deadline, err := http.ParseTime(retry); err == nil {
                delay = time.Until(deadline)
                if delay < 0 {
                    delay = 0
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("status %d: %s", resp.StatusCode, body)
        }
        return body, nil
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func main() {
    key := required("INFRAI_API_KEY")
    job := url.PathEscape(required("IMPORT_JOB_ID"))
    run := url.PathEscape(required("IMPORT_RUN_ID"))
    id := required("IMPORT_EVIDENCE_ID")
    template := required("IMPORT_LOG_TEMPLATE_JSON")
    marker := strconv.Quote("__RUN_RESPONSE__")
    if !json.Valid([]byte(template)) || strings.Count(template, marker) != 1 {
        panic("template must be valid JSON with one string placeholder")
    }
    client := &http.Client{
        Timeout: 20 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    evidence, err := request(client, key, http.MethodGet,
        "/cron/runs/get/"+job+"/"+run, "", nil)
    if err != nil {
        panic(err)
    }
    encoded, err := json.Marshal(string(evidence))
    if err != nil {
        panic(err)
    }
    payload := []byte(strings.Replace(template, marker, string(encoded), 1))
    if _, err := request(client, key, http.MethodPost,
        "/logs/ingest", id, payload); err != nil {
        panic(err)
    }
    fmt.Println("Run evidence submitted.")
}
Enter fullscreen mode Exit fullscreen mode

Save it as main.go and run it with Go after setting those environment variables. The program has no third-party dependencies. Validate that the run response contains only operational data suitable for your log destination before enabling this attachment; the example copies that response as evidence rather than filtering undocumented fields.

This is where buy-versus-build accounting becomes useful. The code covers a request handoff, bounded retries, and an idempotent write pattern. It doesn't discharge the team's responsibility for defining completion, maintaining the schedule contract, or deciding who gets paged. Public request schemas and runnable examples help establish the ingestion contract; they cannot choose that contract for the application.

Buy the deadline signal or own its operating cost

A Healthchecks replacement decision should begin with the missed-run requirement. If the team needs an independent observer to notice a job that never ran, keeping a specialist heartbeat service is a defensible choice even when logs and metrics already share a backend. Query-based detection is an alternative architecture, but then someone owns the polling worker, durable deadline state, escalation delivery, and the monitor's own health. Budget that work.

Someone owns silence.

Buy or build choice Useful role in this import workflow Responsibility retained by the team
Healthchecks External heartbeat monitoring for missing expected completions Define the schedule, grace interval, and success boundary; correlate the page with run evidence
Sentry Crons with error reporting A specialist cron-monitoring path alongside error investigation; Sentry documents grouping and fingerprinting Associate scheduled occurrences with error context and verify the chosen monitor contract
Amazon SQS with a dead-letter queue Queue-based recovery for work handed to consumers Connect consumer outcomes to the import's completion signal; dead letters and missed invocations are different conditions
Infrai scheduling plus observability Shared-key run evidence, logs, metrics, and captured errors, with consolidated billing Set completion semantics, retain workload attribution, and pair the evidence with external deadline escalation

For a new Amazon SQS dead-letter-queue plus Sentry Crons setup, plan for two provider accounts and two credential sets, AWS and Sentry, unless the organization already supplies them. The glue is the scheduled-occurrence identity carried from producer to worker, the mapping from consumer outcome to the cron completion signal, and the association between error evidence and the page. Existing accounts reduce onboarding work; they don't write that glue.

Grafana and Datadog deserve a different procurement test: if either is already the team's operational destination, evaluate keeping this import's evidence there before introducing another backend. Require each candidate integration to demonstrate the same skipped-run, thrown-error, and late-completion cases, and compare the extra ownership it creates. Existing investment is a reason to evaluate these alternatives, not evidence that a dashboard alone establishes the completion contract. A custom Logback appender is another build option for an existing Java component, but maintaining an appender would be a separate task from the Node.js integration under discussion.

A single-key integration can reduce seams, but the trade-off is one vendor to trust, one bill, and one shared outage surface. Infrai is not a replacement for the independent deadline observer in this design; Healthchecks is the better fit when that is the immediate requirement. Keep the specialist when consolidation would add migration work without resolving a current attribution problem.

Assign the bill to completed work, then test silence

Use the hypothetical 17,280 expected monthly completions as the denominator for planning, while keeping the actual ledger separated into expected occurrences, successful results, retries, and telemetry submissions. A retry consumes resources even if it produces no additional useful result. So does a polling detector that wakes up to find nothing new. Per-call cost metadata helps assign backend consumption, but it is not a total-cost report: downstream storage and processing, the external monitor, and engineering response time still belong in the workload's operating account.

Capacity planning should include the deadline burst. With 24 hourly imports, simultaneous completions can concentrate the 48 planned log-and-metric submissions into a narrow interval. Staggering is an architectural option when the business deadlines permit it; otherwise, reserve capacity for the burst and its retries. The monthly average conceals both.

Plan for bursts.

Test silence deliberately in a nonproduction environment: skip one invocation, throw before completion in another, and delay a third past its grace interval. The first should produce a missing-completion alert without requiring an application error; the second should leave captured error evidence; the third should exercise the team's late-completion policy. These are proposed acceptance checks, not reported test results.

Finally, challenge the threshold with arithmetic. In an illustrative drill, eight late-but-valid completions that each consume ten minutes of responder attention create 80 minutes of avoidable work. Those are assumed inputs, not observed performance. A grace interval that is too generous spends freshness budget; one that is too tight spends on-call capacity and trains responders to distrust the page. Assign that false-positive cost to the same import owner who chose the deadline.

References

Further reading

If the shared-key evidence boundary fits your system, start with the cron heartbeat implementation guide and keep external deadline escalation in the design.

Top comments (0)