DEV Community

JorisRhodes8286
JorisRhodes8286

Posted on

Small SaaS Failure Alert Attribution With Errors and Slack Polling

Choose errors plus a small polling worker when a media SaaS needs failure alerts. Add metrics for rate thresholds and logs for investigation. Keep delivery attempts in an attribution ledger so the alert can explain which notification workflow incurred the work. A publisher's breaking-news email, subscription SMS, and login OTP should not disappear into one error count.

TL;DR: The simplest failure alert stack starts with exceptions and a cron or serverless poller sending Slack or email notifications. Add an external heartbeat check for missing runs. Attribute costs to individual attempts before rolling them up to a logical notification; exception counts alone cannot reconcile delivery work.

This is a proposed architecture, not a measured deployment. Its decision axis is cost attribution, and its central artifact is the attempt ledger.

How should a small SaaS route failure alerts from errors to Slack?

An exception proves that code encountered an error. A provider acceptance records a different boundary. A delivery receipt records another, and neither acceptance nor a receipt should become proof that a person read a message. For OTP, the product question is sharper: did the user complete verification before the code expired? Keep those meanings separate in the application's vocabulary. An exception-only rule can correctly report crashes while leaving delivery outcomes unexplained.

Acceptance isn't delivery.

Name the invariants before choosing a product. One logical notification has a stable identifier; each outbound attempt has its own identifier. Every attributable charge belongs to an attempt, and every attempt belongs to exactly one workflow. Retrying a notification creates another attempt, while replaying the same receipt must not create another charge. These are application contracts to implement, not fields assumed to exist in a monitoring API.

Consider an illustrative media workflow with 3 attempts: two email attempts after a temporary deferral, followed by one SMS fallback. That is one logical notification. Counting only the last exception discards part of the attribution trail, while counting repeated receipts inflates it. The ledger should retain all three attempt identifiers, their channel, their workflow owner, and their accounting evidence, even if the alert groups them into a single operator message. A late receipt changes the known outcome; it must not create a fourth attempt. A recipient complaint can reopen the investigation without rewriting the historical accounting record. This is why a spam-filter investigation and a worker crash need distinct evidence even when both first appear as an unsuccessful notification.

The denominator matters too.

A burst of failed attempts means something different during a major news event than during a quiet hour. Add metrics when that distinction drives action. Choose logs when richer request context is necessary, but expect more work to make searches reliable as alert conditions. Neither addition replaces the ledger.

Invariants at the polling and delivery boundaries

The worker retrieves observations, evaluates a rule, persists a pending alert, delivers it, and records the result. Keep a durable cursor and a deduplication key. A retry after the receiver accepted an alert but before the worker saved its acknowledgment can still duplicate delivery. A local sent flag cannot provide exactly-once delivery across that boundary. Use receiver-side deduplication where available and make repeated alerts recognizable.

Watch the worker independently.

Use an external healthcheck service for missing runs. An exception query cannot establish that a scheduled process ran successfully when it never started. Delivery to Slack also does not prove an operator read or acknowledged an alert. If escalation is required, include acknowledgment and escalation in the acceptance test.

US and EU are useful application cohort labels, not evidence of vendor residency. Verify regional processing and deletion terms before sending recipient data to any observability system. Prefer opaque internal identifiers, and exclude email addresses, phone numbers, message bodies, and OTP values from the ledger and alerts. Hashing a recipient does not automatically remove privacy obligations.

This design puts threshold evaluation and notification delivery in the worker. Shared trace identifiers can help correlation, but they do not by themselves establish a navigable span tree. Browser replay, source-map processing, and crash symbolication are separate selection requirements. The attempt ledger is intended to answer an accounting question.

Compare tools against the evidence they must preserve

The table is a selection guide, not a benchmark. Each trial should replay a deferred email, a duplicate observation, and a fallback. Ask for an explanation of the logical notification and every unique attempt, rather than a dashboard screenshot.

Option Suitable decision context Trade-off and acceptance test
Sentry Evaluate first when application exceptions dominate the support queue. Test error grouping and notification delivery with repeated exceptions. Keep a separate attempt ledger; an exception group is not a financial reconciliation record.
Amazon CloudWatch Evaluate when the workload already sits in AWS and operational evidence belongs there. Its pricing documentation includes log ingestion charges. Distinguish the cost of investigation context from the cost of sending notifications.
Datadog Evaluate when investigation must connect evidence across several operational systems. Require the trial to demonstrate that context in one incident. Broader operational scope should earn its place through a specific investigation benefit.
Grafana Evaluate when the team wants a dashboard-centered investigation workflow. Test the signal sources and alert path together. A useful visualization still needs trustworthy attempt records underneath it.
Unified backend API Consider the broader backend option discussed below when the notification service also needs adjacent capabilities. Keep the polling worker, independent heartbeat check, and application ledger explicit in this architecture.

Infrai covers 295 routes across 20 modules through a single API key and a single bill. Its unified REST API uses plain HTTP with no SDK required, so adding another backend capability follows a consistent contract. Native per-call metadata specifies cost_usd, latency_ms, vendor, cache_hit, and request_id, supporting attribution capture for the notification workflow.

One API call is not necessarily one delivery attempt. Define the accounting scope before attaching a call cost to an attempt, and reconcile it against the relevant billing evidence. A provider invoice and per-call metadata can describe different boundaries. Avoid silently summing both.

The trade-off is deliberate: a narrow exception poller keeps the initial operational surface small, but the team owns its cursor, deduplication, and delivery behavior. A broader monitoring product deserves evaluation when that ownership exceeds the team's available attention.

The critical path starts with a bounded read

This Python example implements one retrieval step for the polling worker. It uses the standard library, an explicit GET method, environment-based credentials, and bounded retries for HTTP 429. Set OBSERVABILITY_BASE_URL to the selected service's documented HTTPS v1 base URL and INFRAI_API_KEY to its API key. The base address is configuration rather than a link embedded in this article.

The program requests error groups without inventing query parameters or response fields. It validates that the body is JSON and reports receipt; it deliberately stops before rule evaluation and alert delivery.

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 urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler


class NoRedirects(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def retry_delay(value, attempt):
    if value is None:
        return float(2 ** attempt)
    try:
        return max(0.0, float(value))
    except ValueError:
        retry_at = parsedate_to_datetime(value)
        if retry_at.tzinfo is None:
            retry_at = retry_at.replace(tzinfo=timezone.utc)
        return max(
            0.0,
            (retry_at - datetime.now(timezone.utc)).total_seconds(),
        )


def read_groups():
    base = os.environ["OBSERVABILITY_BASE_URL"].rstrip("/")
    parsed = urlsplit(base)
    if (
        parsed.scheme != "https"
        or not parsed.hostname
        or parsed.username is not None
        or parsed.password is not None
        or parsed.path != "/v1"
        or parsed.query
        or parsed.fragment
    ):
        raise ValueError("Expected an HTTPS v1 base URL")
    key = os.environ["INFRAI_API_KEY"]
    opener = build_opener(NoRedirects())
    for attempt in range(3):
        request = Request(
            base + "/errors/groups",
            headers={"Authorization": f"Bearer {key}"},
            method="GET",
        )
        try:
            with opener.open(request, timeout=15) as response:
                if response.status != 200:
                    raise RuntimeError(
                        f"Unexpected HTTP status: {response.status}"
                    )
                return json.load(response)
        except HTTPError as exc:
            reason = exc.read().decode("utf-8", errors="replace")
            if exc.code != 429 or attempt == 2:
                raise RuntimeError(
                    f"HTTP {exc.code}: {reason}"
                ) from exc
            delay = retry_delay(exc.headers.get("Retry-After"), attempt)
            if delay > 60:
                raise RuntimeError(
                    f"Reschedule after {delay:.0f} seconds"
                ) from exc
            time.sleep(delay)


if __name__ == "__main__":
    snapshot = read_groups()
    print("Error snapshot received as valid JSON")
Enter fullscreen mode Exit fullscreen mode

The loop allows 3 attempts with a 15-second request timeout. A Retry-After value longer than 60 seconds ends this invocation with a rescheduling instruction instead of retrying early. A production scheduler must persist that deferral. Redirects are rejected so this example does not forward credentials to another address.

This is a read. It creates no notification and needs no write deduplication key.

After retrieval, normalize observations against the documented response schema and commit the evidence before advancing the cursor. Use a uniqueness constraint for finalized accounting records. An accepted observation followed by a delivered observation is a state transition, not an accounting duplicate; blindly keeping the latest list entry can erase a charge or obscure an earlier outcome. Late receipts should update what is known without inventing new attempts. Keep unresolved outcomes explicit until evidence arrives.

Do not turn the sample into a scheduled log dump. Its final message avoids printing the snapshot, which may contain sensitive investigation context. The alert should carry only the identifiers and summary needed to find authorized evidence.

Rejected default and its valid use case

Reject a logs-first stack as the default for this small service. Rich context is valuable, but every alert condition would then depend on query semantics and consistent log production. The attempt ledger supplies a narrower attribution contract. Exceptions initiate the investigation; the ledger explains the attempts.

A logs-first approach is valid when the team already maintains structured events and tested alert queries, especially for failures that do not raise exceptions. Preserve that investment. Choose broader monitoring when a cross-service investigation or acknowledgment workflow is a real requirement, and test it before retiring existing tooling.

The acceptance criterion is concrete: duplicate observations leave attempt totals unchanged, a fallback remains attributable to its original notification, and a missing worker run produces an independent signal.

Start there.

References

Top comments (0)