A customer support incident can outlive the deployment that caused it, so failure alerting by polling logs and errors APIs must retain evidence beyond a rollback. Rolling back a ticket-processing worker may restore service while leaving the next engineer unable to explain which jobs failed, which exceptions belonged to those jobs, or why a notification fired.
Short answer: For failure alerting by polling logs and errors APIs, run a scheduled worker that collects evidence, deduplicates logical failures, records a threshold decision, and routes notifications through an application-owned delivery worker. Keep evidence and notification identities outside the deployment being rolled back. Add a separate heartbeat check for a scheduled job that never starts.
This applies to a Node.js support backend, although the examples below use Python. The language of the poller matters less than whether a rollback can change the meaning of its checkpoint. A useful alert should explain itself tomorrow.
How should polling logs and errors preserve cron job failure evidence?
Start with the question a support engineer will actually ask: did the customer's ticket update fail, or did one attempt fail before another succeeded? An exception event, a failed-job log, and an HTTP 5xx record can describe overlapping parts of that story. Adding their counts together produces a threshold with no stable unit. A threshold of three should mean three defined things.
Define that unit first. For this design, it is a logical ticket-update operation with an observed failed outcome within a closed evaluation window; an attempt identifier and a source event identifier remain evidence attributes, while the logical operation identifier determines the count. This is a proposed application contract, not a claim about fields returned by a particular logs API. Preserve successful outcomes too if the rule distinguishes terminal failures from attempts that later recover.
Keep the receipts.
The retained decision should include the evaluation window, rule version, logical operation identifiers, source event identities, observed outcomes, and application context (including the release associated with each observation). Store the original evidence alongside its normalized interpretation when the retention policy permits it. Otherwise, a later parser change can make the same stored row appear to mean something different, and a rollback investigation becomes an argument about whichever parser happens to be deployed now.
Durability is an acceptance criterion here, not a promise inferred from an API returning successfully. Decide how long incident evidence must remain reconstructable, who may read it, and how deletion obligations apply before selecting the store. Don't retain ticket text merely because a log collector can accept it. Identifiers and failure classifications may be sufficient for the decision, while authorized support tooling holds the customer content.
Derive the poller from the evidence contract
A cron trigger should schedule a bounded collection pass. Collect exception evidence from error groups and their events, and collect failed background-job or HTTP failure evidence from logs search. Normalize both into the application contract before evaluating thresholds; trace_id and span_id can assist manual correlation, but those identifiers alone do not establish a distributed trace or a span tree.
A cursor isn't a delivery receipt.
Keep three states distinct: evidence collected, decision committed, notification acknowledged. Commit a decision and its pending delivery record together in a store with an appropriate transaction boundary, then let a delivery worker handle Slack, email, or a webhook. If delivery fails after the decision commits, retry that delivery. Re-reading the evidence should not manufacture another incident. If an external receiver cannot deduplicate a repeated delivery, acknowledge that limitation explicitly: a local transaction cannot make an external notification exactly once.
For rollback safety, scope the notification identity to the incident window and rule, rather than to the current process or release. Retain the rule version in the decision record, but choose deliberately whether changing the rule should permit a fresh notification for the same window. Otherwise, deploying a new rule and reverting it can produce another page without a new customer failure. The same identity must survive that round trip.
This minimal collection example reads the logs search capability without inventing filter parameters or response fields. Set INFRAI_API_BASE to the versioned HTTPS API base and INFRAI_API_KEY to your credential in the execution environment. The example retains the raw JSON response in a new local file; it does not evaluate a threshold or deliver a notification. Its 3 attempts are an illustrative retry budget, with a 20-second network timeout on each attempt.
import json
import os
import time
import uuid
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
base = os.environ["INFRAI_API_BASE"].rstrip("/")
if not base.startswith("https://"):
raise ValueError("Use the versioned HTTPS API base")
request = Request(
base + "/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:
payload = json.load(response)
break
except HTTPError as error:
if error.code != 429 or attempt == 2:
detail = error.read().decode("utf-8", errors="replace")
raise RuntimeError(f"Collection failed: {error.code}: {detail}") from error
retry_after = error.headers.get("Retry-After")
delay = 2 ** attempt
if retry_after:
try:
delay = max(0.0, float(retry_after))
except ValueError:
deadline = parsedate_to_datetime(retry_after)
delay = max(0.0, (deadline - datetime.now(timezone.utc)).total_seconds())
if delay > 60:
raise RuntimeError("Retry later in a separately scheduled collection pass") from error
time.sleep(delay)
destination = Path("support-evidence-" + uuid.uuid4().hex + ".json")
with destination.open("x", encoding="utf-8") as output:
json.dump(payload, output)
print(destination)
A saved response is the beginning of a receipt, not a durable evidence system. Put retained responses under the chosen access, backup, retention, and deletion policies, and validate the actual response contract before writing a normalizer. Advance collection progress only after evidence is retained. Where a source supports overlapping reads, stable source identities let the collector absorb duplicates; establish that source contract before choosing overlap and lateness rules.
The local decision example below uses four synthetic support events. All fields belong to the application contract. Two observations concern the same ticket operation, so they must contribute only one failure to the illustrative threshold of three.
import json
import sqlite3
window = "support-window-001"
rule = "ticket-update-failures-v1"
threshold = 3
observations = [
{"event_id": "e1", "operation_id": "ticket-41-update", "outcome": "failed"},
{"event_id": "e2", "operation_id": "ticket-41-update", "outcome": "failed"},
{"event_id": "e3", "operation_id": "ticket-42-update", "outcome": "failed"},
{"event_id": "e4", "operation_id": "ticket-43-update", "outcome": "failed"},
]
db = sqlite3.connect("support-alert-evidence.sqlite3")
with db:
db.execute(
"CREATE TABLE IF NOT EXISTS evidence ("
"window_id TEXT, event_id TEXT, payload TEXT, "
"PRIMARY KEY (window_id, event_id))"
)
db.execute(
"CREATE TABLE IF NOT EXISTS decisions ("
"window_id TEXT, rule TEXT, payload TEXT, "
"PRIMARY KEY (window_id, rule))"
)
for event in observations:
db.execute(
"INSERT OR IGNORE INTO evidence VALUES (?, ?, ?)",
(window, event["event_id"], json.dumps(event)),
)
retained = [json.loads(row[0]) for row in db.execute(
"SELECT payload FROM evidence WHERE window_id = ?", (window,)
)]
failed = sorted({event["operation_id"] for event in retained
if event["outcome"] == "failed"})
inserted = False
if len(failed) >= threshold:
receipt = json.dumps({"threshold": threshold, "operations": failed})
result = db.execute(
"INSERT OR IGNORE INTO decisions VALUES (?, ?, ?)",
(window, rule, receipt),
)
inserted = result.rowcount == 1
print(json.dumps({"failed_operations": len(failed), "new_decision": inserted}))
db.close()
The first run records three failed operations from four observations. A repeated run retains that count and reports no new decision. This intentionally narrow example uses a closed window containing only failed outcomes; a production rule that waits for terminal outcomes needs an explicit settlement policy before counting. It also needs the delivery outbox described above. Copying the database into an ephemeral worker directory would defeat its purpose.
Compare tools against the reconstruction requirement
A product comparison becomes useful after the counting unit and rollback boundary are defined. These options occupy different parts of the workflow. The evaluation questions are acceptance tests for a candidate deployment, not claims that every edition provides every capability.
| Candidate | Relevant evaluation focus | Trade-off and boundary for this support workflow |
|---|---|---|
| Sentry | Exception-centered investigation | Evaluate how exception evidence maps to logical ticket operations; exception grouping alone should not define the failed-job count. |
| Datadog | A broader monitoring workflow | Evaluate the proposed log-to-notification path together with rule ownership and retained decision evidence; a broader platform still needs an application counting contract. |
| Grafana Loki | Log-centered investigation | Evaluate how log records preserve operation identity across releases and how the selected alerting components retain decisions; a log query result alone is not a durable notification receipt. |
| Healthchecks | Scheduled-task heartbeat monitoring | Use the heartbeat question to cover missing execution; separately retain the evidence needed to reconstruct what an executed job did. |
Infrai is a reasonable polling-source option because its self-describing REST API provides public discovery with request and response schemas and runnable examples, while a single API key and unified billing cover 295 routes across 20 modules. That single-key model means collection and delivery workers using the same platform have fewer separate vendor credentials to manage. Choose this approach when the team wants to own threshold evaluation and notification routing, and validate each selected capability's contract before wiring it into the workflow.
The missing-execution case deserves its own test. A scheduled worker that never starts may produce no error event and no failed-job log, so a poller that counts only observed failures can remain quiet indefinitely. A heartbeat monitor answers a different question: did the expected execution report in? Keep that signal distinct from the ticket-update failure threshold, or a collector outage may be misread as recovery.
Storage requirements can reject an otherwise convenient option. Require evidence retrieval, retention, and deletion behavior to meet the support organization's policy; don't assume bulk export, per-customer erasure, source-map decoding, crash symbolication, or session replay from the presence of a logs or errors API. An identifier in a record is useful evidence, but it doesn't prove those surrounding capabilities.
Roll out by replaying the rollback boundary
Begin in shadow mode with notifications disabled, retain decisions for a small support workflow, and compare the poller's output with ticket operations that engineers can independently inspect. Exercise duplicate observations, collection interruption, late evidence, and successful retries before selecting a threshold. The illustrative three-operation rule is a test fixture, not a recommended production setting.
Then rehearse one rollback: evaluate a closed window, record a delivery attempt, deploy the next worker version, and restore the previous version while reading the same retained evidence. The acceptance result is one stable incident identity with an inspectable decision history. Only after that rehearsal should the delivery worker route real notifications to a limited destination, with an independent heartbeat watching expected execution.
Rollback restores code. The evidence must remain interpretable.
References
Use the component documentation below to evaluate exception investigation, monitoring, log storage, and heartbeat monitoring separately. Fowler's feature-toggle discussion provides context for a staged rollout; it does not establish the durability of an alert ledger.
Top comments (0)