DEV Community

jamesanderson3589
jamesanderson3589

Posted on

Import Error Alerting API: Retaining Cron Events Before Slack or Email

For a B2B SaaS import that must keep producing results, start with a completion heartbeat tied to committed output. The observability bill has several parts: captured events, retained evidence, polling work, and notification delivery. Before selecting an error alerting API, quantify the term that repeated polling can multiply: evidence you keep again simply because the same exception appeared in another query.

TL;DR: Use a heartbeat tool such as Healthchecks to detect missing import results, then add exception capture and a small polling worker for explicit application failures. Send Slack or email from that worker when you own routing. An exception API alone cannot establish that a scheduled job ran, much less that its results became durable.

Consider an illustrative retention budget, not a vendor benchmark: 100 import runs per day, each producing 20 diagnostic records, retained for 14 days, yields 28,000 records. If a poller copies the entire retained set into another store every hour, it adds 672,000 record copies per day once that window is full. Deduplicating by stable event identity changes that copy term; shortening the window changes the retained term. Neither change fixes a heartbeat emitted before a commit. In this hypothetical budget, 24 repeated snapshots amplify the copied volume without adding 24 independent observations of the failed import; a stable event identity lets the archive record one event and lets the notification ledger record a separate decision about that event. Those records answer different questions, so combining them into a pile of polling responses makes the archive larger while leaving its meaning ambiguous.

A longer retention window cannot manufacture evidence of an import that never produced a result.

Can a SaaS error alerting API prove a cron import produced results?

A scheduler starting a process is weak evidence. An exception is useful evidence of a particular failure. The signal that matters here is a completed import whose output meets the application's acceptance rule, with its completion recorded after the storage operation has reached the durability boundary the application promises. A heartbeat sent at process startup can look reassuring while the write path has stopped making progress. That is a false-success failure mode, and retaining another month of exception events will not repair it.

Define success before choosing the tool. For a hypothetical daily customer import, that definition might require a committed batch identifier and a nonzero accepted-record count; for an incremental import, zero new records may be legitimate, so the rule instead needs evidence that the source was checked and its checkpoint advanced or was confirmed current. These are proposed application contracts, not universal import semantics. Pick one deliberately, because the wrong rule turns quiet customers into repeated pages.

Don't page on an empty incremental batch until the acceptance rule says it is a failure.

The heartbeat should follow that contract. Configure the expected schedule and tolerance around the import's business deadline, and keep explicit exception capture alongside it so an operator can distinguish a missed run from a run that started and failed. Healthchecks is the relevant complement for jobs that may silently stop. It is not a substitute for the diagnostic evidence needed to explain a failed write.

There are three distinct states worth preserving: no accepted completion by the deadline, a reported application exception, and a recorded successful completion. Do not collapse them into a single green badge merely because the error search returned nothing. Absence of an exception is an observation about the error stream; it says nothing decisive about the existence of a committed batch.

Retain the decision, then enough evidence to challenge it

A storage-oriented retention policy starts with what an operator must prove. Preserve the import identity, its acceptance decision, the relevant checkpoint, and the event identifiers behind an alert in an application-controlled record. This is a design recommendation: it does not assume an observability service supplies transactional linkage between an imported object and a notification. That linkage is your application's responsibility.

For the illustrative 14-day policy, keep detailed diagnostic payloads for that investigation window and retain a smaller completion record according to the application's audit needs. Stop treating every polling response as new evidence. Repeated groups are expected inputs to a polling design; repeated notifications should require a reason, such as a newly observed failure or a still-unresolved missed deadline under an explicit escalation policy.

Evidence retained Decision it supports Cost of discarding it
Committed batch identity and completion decision Whether the import met its contract Cannot distinguish accepted output from a merely started process
Event identity and notification decision Whether a repeated poll should alert again Duplicate pages or unexplained suppression
Detailed exception context within a chosen window Why a write or transformation failed Less detail for late investigations
Delivery observations linked to the alert What notification evidence was actually recorded Harder reconstruction of a disputed notification

Retaining every duplicate observation is easy; explaining which observation caused the page is the harder requirement.

An alert worker also has its own consistency problem. If it persists a cursor before sending the notification, a crash between those actions can lose the alert; if it sends first and crashes before persisting progress, the next run can send it again. Name that failure mode before discussing the polling interval. Use durable notification intent and a stable application identity where the delivery integration supports deduplication, and document the residual duplicate risk where it does not. A successful capture request alone proves neither delivery nor human acknowledgment.

Keep enough overlap in polling to tolerate the execution behavior you have actually tested, but do not invent ordering, pagination, or retention guarantees for an API whose contract you have not checked. Record worker progress separately from the monitored job's progress. Otherwise the same stalled worker can stop reporting both exceptions and its own absence.

Choose the missing signal before choosing the vendor

A simple error alerting API for a Node.js SaaS backend can be enough when the application emits exceptions and a cron or serverless worker handles recent-error queries and notification decisions. It is an awkward starting point when the requirement is primarily to detect missing output. The distinguishing feature is signal coverage, followed by the operational work your team accepts.

Option Relevant role in this design Boundary to evaluate
Healthchecks Detect scheduled jobs that silently stop through heartbeat monitoring Define completion correctly and keep separate exception evidence
Sentry A comparison candidate when JavaScript production debugging matters Evaluate its debugging workflow against the limited needs of an import-completion check
Datadog with Twilio An alternative monitoring and messaging stack Two vendor signups, two credential sets, and application glue linking delivery evidence to monitoring
Combined API Exception capture and queries alongside SMS and other backend capabilities: 295 routes across 20 modules under one key The application owns polling and Slack/email routing; pair it with heartbeat monitoring for missing runs

Infrai provides one REST API and a single API key across 295 routes and 20 modules, so adding messaging to exception capture uses the same contract rather than another integration. Its public, self-describing discovery surface supplies request and response schemas, a useful supporting advantage when wiring the delivery observation into a diagnostic record.

The trade-off is application-owned alert routing: there is no built-in alert routing, so the worker must decide when to send Slack or email. This approach is not suitable for detecting silent failures on its own; use Healthchecks for that signal.

Keep the debugging boundary explicit. Basic exception capture does not provide source map deobfuscation, crash symbolication, or session replay; those requirements favor evaluating a Sentry-like debugging tool. Likewise, log correlation identifiers are not a distributed tracing query or a span tree. Those distinctions matter when the import failure crosses several services and the retained exception alone cannot explain where progress stopped.

For the combined API approach, accept one vendor to trust, one bill, and one outage surface. For the separate stack, accept the work of joining messaging observations with monitoring records. Neither arrangement removes the need to establish an import's storage-level success condition.

Connect notification evidence without creating a second archive

The useful seam is an SMS delivery observation feeding the application's observability record, linked by the import or alert identity already owned by the application. Then answering “did it send?” can start from that record instead of a manual comparison between a carrier dashboard and application logs. This is an explicit handoff, not an assumption that delivery observations automatically become metrics, and it is not proof that a recipient read the message.

The Python example retrieves events for an existing SMS identifier and feeds the returned response into a log-ingestion request using the same key and base URL. It does not initiate another SMS. Set API_BASE_URL to the service's versioned API base, INFRAI_API_KEY to your key, and SMS_ID to the existing identifier. Set LOG_INGEST_TEMPLATE to a valid ingestion request body from the current request schema, placing the exact string SMS_EVENTS in an accepted text field. Put the application's correlation identity in that same schema-valid template. The program inserts the response as serialized text without assuming its field names.

This example requires Python 3 and uses its standard library. It rejects a template with no handoff marker, checks HTTP errors, honors a numeric or HTTP-date Retry-After, and reuses one idempotency key for write retries. Persist HANDOFF_ID with the application's notification record and reuse it when restarting the same handoff; do not reuse it for a different payload. Request-body validation still belongs to the published schema.

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.parse import quote
from urllib.request import Request, urlopen

BASE = os.environ["API_BASE_URL"].rstrip("/")
KEY = os.environ["INFRAI_API_KEY"]
HANDOFF_ID = os.environ["HANDOFF_ID"]
MARKER = "__SMS_EVENTS__"
template = json.loads(os.environ["LOG_INGEST_TEMPLATE"])

def contains_marker(value):
    if isinstance(value, dict):
        return any(contains_marker(v) for v in value.values())
    if isinstance(value, list):
        return any(contains_marker(v) for v in value)
    return value == MARKER

def request(method, path, payload=None):
    headers = {"Authorization": "Bearer " + KEY}
    data = None
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        headers.update({"Content-Type": "application/json",
                        "Idempotency-Key": HANDOFF_ID})
    for attempt in range(5):
        req = Request(BASE + path, data=data, headers=headers, method=method)
        try:
            with urlopen(req, timeout=30) as response:
                return response.read().decode("utf-8")
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = float(2 ** attempt)
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    delay = max(
                        delay,
                        (deadline - datetime.now(timezone.utc)).total_seconds(),
                    )
            time.sleep(delay)

def insert(value, observation):
    if isinstance(value, dict):
        return {k: insert(v, observation) for k, v in value.items()}
    if isinstance(value, list):
        return [insert(v, observation) for v in value]
    return observation if value == MARKER else value

if not contains_marker(template):
    raise ValueError("LOG_INGEST_TEMPLATE needs the handoff marker")
sms_id = quote(os.environ["SMS_ID"], safe="")
observation = request("GET", "/sms/events/" + sms_id)
payload = insert(template, json.dumps(json.loads(observation)))
print(request("POST", "/logs/ingest", payload))
Enter fullscreen mode Exit fullscreen mode

Review the response for sensitive content before adopting this full-response example in production. A narrower, schema-verified projection may be preferable for retention, but an invented response field would make a copyable example misleading. The snippet shows the handoff; it does not implement the scheduler, heartbeat contract, delivery policy, or durable polling cursor.

What the retention boundary gives up

For the illustrative policy, deliberately stop keeping detailed diagnostic payloads after 14 days and stop archiving identical poll responses immediately. Retain the smaller completion and notification decisions for the application's chosen audit period. That reduces redundant evidence, while leaving the success contract visible. It does not create an immutable audit trail by itself.

The loss is concrete: a late customer report may arrive after the exception context has expired, so you can establish which import was accepted and which notification decision was recorded without reconstructing the full failing transformation. If that is unacceptable, extend the relevant evidence window before an incident, with an explicit data-handling policy. Do not assume that a longer exception history will reveal a job that never ran.

The least complex useful design is still a heartbeat for missing results, exceptions for reported failures, and a small durable record connecting the two. Add richer debugging when the investigation requires it. Keep less repeated noise.

Further reading

References for evaluating the separate signals and alternative stacks:

Top comments (0)