DEV Community

EchoF76
EchoF76

Posted on

Gaming Background Job Failure Detection — 2 Signals Beyond a Cron Heartbeat

A nightly gaming pipeline's cron background job can produce plenty of searchable logs while still leaving the most important question unanswered: did the scheduled work actually finish? TL;DR: use exception capture and error-log polling for explicit failure alerts, and an external heartbeat monitor for missed runs. Keep those signals separate so a burst of repeated errors does not drown out a job that never started.

The decision is about signal quality versus noise. Searching structured logs explains a failure that left evidence; a deadline outside the scheduled process establishes when expected evidence never arrived. This applies even when the scheduler runs a Node.js background job and the analysis starts in a Python notebook. The language does not change the distinction.

Start with evidence.

How should cron background job failure alerts distinguish errors from missed heartbeats?

For this walkthrough, imagine a gaming data pipeline that prepares nightly match summaries. The example below uses synthetic records and an illustrative deadline; neither is a production measurement. A repeated error for one run should produce one candidate incident. An absent run needs a different signal, even if the log search returns nothing alarming. Ordinary informational records should stay available for investigation without becoming pages.

The data flow is straightforward: the scheduled process emits structured records and captures exceptions, a separate polling worker searches the error and log stores, and an external heartbeat service watches the expected completion schedule. The polling worker turns explicit failure evidence into a notification through a notification channel you configure. The heartbeat service supplies missed-run detection independently of the task's own execution. Send the success heartbeat after the required work completes.

That last placement matters. A heartbeat sent at startup proves startup. It does not establish that the nightly match summaries were produced. Choose what completion means before connecting the monitor; otherwise the monitor can faithfully track the wrong event.

For a notebook-to-prod workflow, the useful first artifact is a tiny labeled fixture. It makes the paging rule inspectable before a log search, an agent, or a summary model gets involved.

Infrai offers one key, one bill, and one REST API for error/log capture and polling. A single API key covers multiple backend services; plain HTTP means no SDK to install. Its unified interface lets the application keep its capability contract when the underlying vendor changes, without rewriting application code. Its public, self-describing discovery surface requires no key, so a Python builder can inspect request and response schemas before wiring the reader into a worker. Pair that evidence retrieval with an external heartbeat monitor and a polling-driven notification worker; the comparison below separates those responsibilities.

Run the signal-selection rule locally

Start by retrieving log evidence through the actual search interface. This standard-library Python reader uses an explicit GET with no invented filter parameters. Supply the deployment's API origin through OBSERVABILITY_ORIGIN and the credential through INFRAI_API_KEY; the origin is the HTTPS API host, without a version path. The script prints the returned JSON without assuming an undocumented response envelope. Keep this raw output in a restricted development environment and adapt record extraction to the documented response schema before connecting the local rule below.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen

origin = os.environ["OBSERVABILITY_ORIGIN"].rstrip("/")
if not origin.startswith("https://"):
    raise ValueError("Use the HTTPS API origin")

request = Request(
    origin + "/v1/logs/search",
    headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
    method="GET",
)

for attempt in range(3):
    try:
        with urlopen(request, timeout=20) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected HTTP status: {response.status}")
            payload = json.load(response)
        print(json.dumps(payload, indent=2))
        break
    except HTTPError as error:
        body = error.read().decode("utf-8", errors="replace")
        if error.code != 429 or attempt == 2:
            raise RuntimeError(f"HTTP {error.code}: {body}") from error
        delay = float(2 ** attempt)
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                required = float(retry_after)
            except ValueError:
                deadline = parsedate_to_datetime(retry_after)
                required = (deadline - datetime.now(timezone.utc)).total_seconds()
            delay = max(delay, required)
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

This is a read-only request, so retrying it does not create duplicate records.

The retry budget is three attempts, with a 20-second timeout per request; an exhausted rate limit becomes a visible error rather than an empty result. These are example settings, not a service latency claim. The trade-off is deliberate: a small reader is easy to inspect, but it still needs scheduling, durable state, and notification delivery around it.

This next Python example runs with the standard library and no credentials. It models the two inputs independently: structured log records and externally observed completion state. The field names belong to this local fixture, not to a vendor API. It does not contact a monitoring service or implement a live heartbeat monitor. In deployment, the deadline signal must come from an independent service rather than this in-memory dictionary.

import json
from datetime import datetime, timezone

now = datetime(2026, 11, 30, 3, 20, tzinfo=timezone.utc)
records = [
    {
        "job": "match-summaries",
        "run_id": "nightly-a",
        "level": "error",
        "message": "Input validation failed",
    },
    {
        "job": "match-summaries",
        "run_id": "nightly-a",
        "level": "error",
        "message": "Input validation failed",
    },
    {
        "job": "match-counts",
        "run_id": "nightly-b",
        "level": "info",
        "message": "Completed",
    },
]

# Illustrative input from an independent completion monitor.
completion_state = {
    "match-summaries": {
        "run_id": "nightly-a",
        "due_at": datetime(2026, 11, 30, 3, 30, tzinfo=timezone.utc),
        "completed": False,
    },
    "match-counts": {
        "run_id": "nightly-b",
        "due_at": datetime(2026, 11, 30, 3, 10, tzinfo=timezone.utc),
        "completed": True,
    },
    "season-rollup": {
        "run_id": "nightly-c",
        "due_at": datetime(2026, 11, 30, 3, 10, tzinfo=timezone.utc),
        "completed": False,
    },
}

explicit_failures = {
    (record["job"], record["run_id"])
    for record in records
    if record["level"] == "error"
}
missed_completions = {
    (job, state["run_id"])
    for job, state in completion_state.items()
    if now > state["due_at"] and not state["completed"]
}

expected = {
    "explicit_failure": {("match-summaries", "nightly-a")},
    "missed_completion": {("season-rollup", "nightly-c")},
}
actual = {
    "explicit_failure": explicit_failures,
    "missed_completion": missed_completions,
}
assert actual == expected

print(json.dumps({
    signal: [dict(job=job, run_id=run_id) for job, run_id in sorted(runs)]
    for signal, runs in actual.items()
}, indent=2))
Enter fullscreen mode Exit fullscreen mode

The fixture yields two candidate incidents. Two identical error records collapse into one explicit failure for the same run. The season rollup produces a missed-completion candidate despite having no log record. The completed match-count job contributes neither. These are fixture expectations, not detection-rate claims.

Notice the deadline on the failing job: it has not expired yet. Error capture can surface a known failure before a completion deadline passes. Later, the same run might also miss its deadline, so the notification layer should correlate those signals instead of treating them as unrelated pages. Preserve both reasons in the incident.

A missed completion cannot, by itself, distinguish a task that never started from one that started and stalled. Use the captured records to investigate that difference.

The alert should say what the evidence supports.

Choose tools around the evidence they own

Healthchecks, Cronitor, and Better Stack are real alternatives to evaluate for scheduled-task heartbeat monitoring. Their official documentation is a better starting point than a price grid. The useful comparison is how each fits the completion signal and the operational workflow you need.

Option Relevant distinction Selection boundary
Healthchecks Centers its workflow on scheduled check-ins and missing expected signals. A focused choice when an external completion heartbeat is the main requirement; keep structured-log investigation in its own workflow.
Cronitor Documents cron-job monitoring alongside broader monitoring workflows. Evaluate it when the team wants scheduled jobs within a wider monitoring practice; verify how its schedule and alert settings match the job.
Better Stack Documents heartbeat monitoring within its uptime offering. Evaluate it when heartbeat incidents should fit an existing uptime response workflow; test the completion schedule rather than assuming a generic availability check is equivalent.
Sentry An alternative to evaluate for exception-centered investigation. Put exception context first when assessing it; do not assume that exception capture alone establishes that a scheduled task ran.

These are selection criteria, not a measured ranking. Run the same completed, failed, late, and absent-job cases against the candidate configuration. In particular, inspect what happens after an error is reported but before the deadline expires. A tool can be appropriate while the schedule you entered is wrong.

A log-only design is not suitable for missed-run detection: it cannot establish that a silent task met its deadline. Choose Healthchecks or another external heartbeat monitor for that responsibility. Conversely, a heartbeat alone doesn't explain the validation error in a failed match-summary run. That limitation is why the two signals belong together, even if the final incident view combines them.

This division avoids inventing infrastructure inside the summarizer. It also keeps the comparison fair: choose a log/error interface for evidence retrieval, then choose a heartbeat monitor for the expectation that something should have happened. Verify both connections independently.

Move the notebook rule into a quiet production workflow

The local set in the example is deliberately small. A production polling worker needs durable incident identity so overlapping polls and worker restarts do not notify repeatedly for the same job and run. Keep the run identifier stable across retries of that logical run, and decide how a deliberate rerun gets a distinct identity. Deduplication reduces noise, but an identifier reused across different nights can hide a new failure.

That is the trap.

Search parameters also deserve care. Apply the local fixture's filtering rule to records retrieved through a documented interface; its dictionary keys are not permission to invent remote query parameters. Establish what the service accepts and returns before turning the notebook into a scheduled worker. A successful empty search and an unsuccessful poll must remain distinct states.

Keep the workflow eval-driven. Extend the labeled fixture with a repeated poll, an error followed by a missed deadline for the same run, and a healthy completion whose logs include an informational warning. Assert the expected incident identities before adjusting the notification rule. Those cases test the noise boundary directly; a fluent generated summary cannot substitute for them.

Stay prompt-cost aware, too. Select and deduplicate evidence before sending anything to a summary model. The deterministic rule should establish the incident; an optional model can explain the selected evidence afterward. This makes the notebook-to-prod transition easier to review and keeps repeated log lines out of the prompt. Do not let a summary's confidence decide whether a missing run deserves attention.

Before enabling notifications, define the completion event, confirm the external monitor's schedule and deadline allowance, and exercise the absent-run case independently of the scheduled process. Then verify that repeated polls preserve one incident identity and that a failed evidence read cannot masquerade as a healthy empty result. Finally, inspect a sample notification: it should name the logical run, retain both reasons when they overlap, and link the responder's investigation to the relevant structured records. Only then tune the noise threshold against the labeled cases.

References

The sources below support the tool-selection boundaries and the recommendation to minimize sensitive data in diagnostic records. They are documentation references, not evidence of comparative performance measurements. Keep player identifiers and raw payloads out of the example's diagnostic messages unless they are necessary for the investigation.

Sources

Top comments (0)