Choose custom metrics and a cron evaluator for SaaS API failure alerts when the team can operate the evaluation and delivery path, and require every alert to identify the evidence needed to reconstruct the affected agent loop. For a fintech workflow, a red dashboard is an insufficient explanation of which attempt failed, which retry completed, and where the loop spent its time.

TL;DR: Report failed_requests and job_failures, pair request failures with a matching denominator, and poll queries to evaluate thresholds before triggering Slack or email through a separate delivery system. Preserve attempt records for latency and reported call cost. An independent heartbeat monitor must cover scheduled work that never starts; a failure counter cannot report an execution that didn't happen.

The decision here is about incident reconstruction. A metric supplies the trigger, while attributable records supply the explanation, and those two obligations need separate acceptance criteria even when they share an ingestion path. The architecture decision is to accept a small threshold evaluator only if its output can be joined back to a complete investigation window. Otherwise, use a managed alerting workflow and keep the same evidence requirement.

How should custom metrics support SaaS API failure alerting and incident reconstruction?

Start at the investigation's end: someone must explain the terminal business outcome and account for the attempts that preceded it. That requires a stable loop identifier, separate attempt identifiers, outcome definitions, time boundaries, and reported call costs. These are proposed application records, not a vendor response schema. Keep identifiers in retrievable evidence rather than depending on aggregated counters to recover individual events after the fact.

Counts lose identity.

A successful retry can coexist with a failed request and a successful logical job. Counting that sequence as one failed job would change the meaning of the alert, while discarding its failed attempt would erase part of the latency and cost explanation. Define failed_requests at the attempt boundary and job_failures at the terminal workflow boundary; use total_requests from the same population and interval when calculating an error rate. A failed-request count alone has no denominator.

For the evidence store, require explicit acknowledgement, retention, and retrieval guarantees before accepting it as an incident record. Don't infer durability from a metric appearing on a dashboard. The business operation, evidence write, metric report, and notification receipt are separate events unless the application establishes a stronger relationship; a storage review should ask what remains recoverable if execution stops between any two of them. The design deliberately accepts extra record retention because an aggregate cannot later reconstruct identities it never retained.

Protect the boundary, too. OWASP's logging guidance is relevant to financial workflows: credentials, secrets, and sensitive payloads should not become permanent incident evidence merely because recording everything would make debugging convenient. Store the correlation and outcome information needed for the investigation under a documented access and retention policy.

The decision ledger begins with missing evidence

Name the failure modes before choosing an alert interface. Duplicate evidence can inflate request counts; an incomplete window can understate them; a stopped evaluator can leave a healthy-looking dashboard without a current decision. Missing delivery acknowledgement leaves notification receipt unknown. Missing attempt evidence leaves reconstruction incomplete. None of these states should silently become “healthy.”

The operational invariant is therefore a three-state evaluation: breached, clear, or unknown. A completed observation window is a prerequisite for either of the first two states. This is an application policy, not a claim that a metrics backend exposes a completeness flag. The adapter must establish the population and window semantics, and the runbook must explain what the team does when it can't.

For a lightweight implementation, Infrai provides one REST API with one key and one bill, keeping the capability contract stable when the vendor behind it changes, so a provider switch needn't change application call sites; its per-call cost, latency, vendor, and request metadata also provide inputs for agent-loop attribution. The limitation is that native alert rules and notification delivery are not supported: the application owns those responsibilities. Log correlation identifiers also don't provide a distributed tracing query or span tree. Choose Grafana Alerting or Datadog metric monitors instead when managed rule evaluation is a requirement. The consistent contract doesn't establish identical durability or retention semantics across providers.

Compare ownership at the moment evidence is missing, rather than counting dashboard features:

Option Alerting responsibility Reconstruction boundary and suitable use
Custom metrics with cron polling The application evaluates thresholds and invokes its chosen Slack or email delivery system Fits explicit error-rate and failed-job rules when the team accepts evaluator state, delivery tracking, and separate attempt evidence
Prometheus with Alertmanager Prometheus evaluates metric alert expressions; Alertmanager handles notification grouping and routing Fits teams operating a metrics alerting stack; attempt-level latency and cost records remain a separate evidence requirement
Grafana Alerting Managed rule and notification-policy workflows around configured data sources Fits teams investigating through dashboards; validate data-source behavior and missing-data handling against the intended window
Datadog metric monitors Managed metric monitoring with threshold and notification configuration Fits an existing managed monitoring workflow; check aggregation and missing-data settings, and retain records that explain a breach
Healthchecks Expected check-ins and deadline-based notification Fits scheduled work that might never start; a missing check-in doesn't attribute model-call latency or reported cost

These options can coexist. In particular, a heartbeat monitor covers a different absence from an error-rate evaluator: the job that was expected to run but emitted no request at all. Adding a heartbeat metric helps only if something independently checks its expected arrival.

Critical path: preserve the receipt before reducing the window

The following runnable Python example first makes a read-only metrics query, then models the local evaluation boundary with separate synthetic inputs. Set INFRAI_BASE_URL to the service's versioned HTTPS API base and INFRAI_API_KEY to your credential. The request has no filter parameters and prints the response without assuming an undocumented result schema. It handles rate limiting with bounded retries and honors Retry-After; no remote write needs an idempotency key.

The local records, durations, thresholds, and accounting units are synthetic inputs, not measurements or vendor prices. Integer accounting units avoid introducing a floating-point billing calculation; a production adapter would preserve the exact units and scope of the reported monetary value. Connecting the query to the evaluator requires an adapter that establishes the observation window and maps actual results into the application's evidence contract.

Two attempts belong to one logical loop. The first fails and the retry succeeds, so the window contains one failed request but zero terminal job failures. The example's 25% threshold and minimum population of two requests exist only to make that distinction inspectable. Neither is a recommended fintech production threshold.

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 def query_metrics(): base = os.environ["INFRAI_BASE_URL"].rstrip("/") if not base.startswith("https://") or not base.endswith("/v1"): raise ValueError("Configure the versioned HTTPS API base") for attempt in range(4): request = Request( base + "/metrics/query", method="GET", headers={ "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"], "Accept": "application/json", }, ) try: with urlopen(request, timeout=30) as response: if not 200 <= response.status < 300: raise RuntimeError(f"Unexpected status {response.status}") return json.load(response) except HTTPError as error: body = error.read().decode("utf-8", errors="replace") if error.code != 429 or attempt == 3: raise RuntimeError(f"HTTP {error.code}: {body}") 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) raise RuntimeError("Retry budget exhausted") def evaluate(window_id, complete, attempts, terminal_failures): if not complete: return {"window_id": window_id, "state": "unknown"} seen = set() for attempt in attempts: identity = (attempt["loop_id"], attempt["attempt_id"]) if identity in seen: raise ValueError("Duplicate attempt evidence") seen.add(identity) if type(attempt["failed"]) is not bool: raise ValueError("Attempt outcome must be boolean") for field in ("duration_ms", "reported_cost_units"): if type(attempt[field]) is not int or attempt[field] < 0: raise ValueError("Expected nonnegative integer evidence") if type(terminal_failures) is not int or terminal_failures < 0: raise ValueError("Invalid terminal failure count") total = len(attempts) failed = sum(attempt["failed"] for attempt in attempts) request_breach = total >= 2 and failed * 4 >= total breached = request_breach or terminal_failures > 0 return { "window_id": window_id, "rule_version": "example-1", "state": "breached" if breached else "clear", "failed_requests": failed, "total_requests": total, "job_failures": terminal_failures, "error_rate": failed / total if total else None, "attempt_duration_sum_ms": sum( attempt["duration_ms"] for attempt in attempts ), "reported_cost_units": sum( attempt["reported_cost_units"] for attempt in attempts ), "attempt_receipts": attempts, } print(json.dumps({"query_result": query_metrics()}, indent=2)) attempts = [ { "loop_id": "synthetic-ledger-review", "attempt_id": "attempt-1", "failed": True, "duration_ms": 800, "reported_cost_units": 3, }, { "loop_id": "synthetic-ledger-review", "attempt_id": "attempt-2", "failed": False, "duration_ms": 1200, "reported_cost_units": 5, }, ] receipt = evaluate("synthetic-window-1", True, attempts, 0) print(json.dumps(receipt, indent=2)) 

The receipt reports a 50% request error rate, 2,000 milliseconds of summed attempt duration, eight synthetic accounting units, and no terminal job failure. It preserves both attempt identities. This is arithmetic on an example, not a benchmark.

Elapsed time differs.

Queueing, validation, and retry backoff can extend loop duration beyond sequential call durations; overlapping attempts make a sum unsuitable for reconstructing wall time. Record the loop's own start and finish boundaries and distinguish those from provider-reported latency. Likewise, reported call cost has a scope: it doesn't automatically represent every expense of running the workflow.

The example prints an evaluation receipt. Production needs durable storage and an explicit delivery step before that receipt becomes an operational alert. Use the window identifier and rule version as part of a persisted notification identity, record delivery attempts separately, and decide how to retry an ambiguous send without producing uncontrolled duplicate notifications. A printed result establishes none of those guarantees.

Rejected option: let the dashboard serve as the incident record

A dashboard-only design is valid for exploratory trends and a human checking aggregate error rates. It is rejected for this fintech agent loop because the investigation must explain retry attribution and terminal outcome, and the reduced metric series cannot supply the missing attempt identities. More charts won't restore them.

Before accepting a deployment, exercise three synthetic cases: a failed attempt followed by success, a terminally failed loop, and an expected job that never starts. Require the correct threshold decision and retrievable attempt evidence for the first two; require an independent missed-deadline signal for the third. Then interrupt the evaluator and verify that its absence becomes visible. Choose a managed alerting option if maintaining that evaluation and delivery machinery exceeds the team's remit, while preserving the same investigation contract.

References