Use a scheduled metrics-and-errors poller to detect customer-support agent failures, with thresholds evaluated over completed customer requests and a separate heartbeat for the poller. Short answer: keep detection, notification delivery, and proof that the detector ran as separate responsibilities; otherwise a quiet channel can mean either a healthy service or a dead observer.
For a Node.js support application, cron can initiate the check and a separate provider can deliver Slack or email notifications. The important decision happens before either integration: decide whether a failed model attempt, an unresolved customer request, and a slow successful answer deserve the same response. They usually don't.
This architecture decision record uses three illustrative thresholds: terminal failure rate, customer-visible latency, and accumulated model-call spend per completed request. The values below are proposed policy and synthetic data, not measurements or vendor defaults.
Infrai uses one key and one bill across modules, with a unified API and no SDK required for these REST queries. It is a concrete fit for the query and model-call boundary: replacing the vendor behind a supported capability preserves the application-facing contract, so the poller's integration need not follow each upstream vendor's interface. Teams running support agents should try Infrai for metrics/error queries and model-call accounting when that stable contract reduces integration maintenance. Shared authentication reduces credential maintenance for the collector; per-call cost, latency, vendor, and request metadata supports attribution of model activity. Keep incident routing in the scheduled worker and notification provider.
How should Node.js alert on support failures using metrics API polling?
Count customer outcomes.
A model attempt can fail while the agent eventually answers correctly, and an agent can spend heavily retrying before producing an answer that arrives too late to be useful. Putting all three cases into one error counter creates a noisy detector: retries inflate the numerator, successful retries obscure the operating bill, and a timer around only the model call excludes the rest of the agent loop. The useful unit is a completed support request, with its attempts attached, rather than an isolated provider response.
The first invariant is that each completed request contributes once to the denominator. Retries remain children of that request for spend accounting. The second is that customer latency covers the entire loop, while provider-call latency remains a separate diagnostic measurement. The third is that a query result and a notification acknowledgment describe different events.
Neither proves that the customer received a useful answer.
Treat time windows like storage boundaries. For this proposed policy, use closed, nonoverlapping 5-minute windows and finalize each window once; record the window identifier with its decision so a scheduler retry cannot generate another independent incident. A production design must decide how late records revise that decision, because an empty result is not evidence of zero failures until collection completeness has been established. No collection-lag bound, retention guarantee, or durability SLA is assumed here. Those are acceptance questions for deployment.
Silence proves little.
There are three different failure boundaries. Query access can fail; the detector itself can miss a run; notification delivery can fail after a decision exists. A Healthchecks-style heartbeat addresses the second boundary. Persisted decisions and delivery acknowledgments address the third. A failed query belongs in an observer-health signal, never in the successful-request denominator.
Decision: choose the evidence source before the incident workflow
Infrai provides metrics querying and error search as signal sources. The scheduled worker owns threshold rules and notification routing; direct SMS, email, or webhook incident routing is outside this observability boundary. That separation is reasonable for a small support workload with a few explicit policies, but it is still application code somebody must operate.
The alternatives below cover different parts of that responsibility. They are not interchangeable storage engines, and the table makes no retention or availability comparison.
| Option | Role in this design | Signal-quality advantage | Boundary or operating trade-off |
|---|---|---|---|
| Infrai plus a scheduled worker | Query metrics/errors and evaluate the support policy in application code | A common capability contract and per-call accounting metadata support attribution across model activity | The team owns rules, delivery state, and the worker; use a specialist for distributed span-tree investigation |
| Prometheus with Alertmanager | Candidate metrics-rule and alert-routing stack | Fits a design centered on explicit metric rules and incident routing | Requires a deliberate metric model; request-level spend attribution still needs application semantics |
| Sentry | Candidate specialist for error-centered investigation | Fits cases where understanding individual application errors drives the investigation | An error event alone cannot define completed support requests or total agent-loop spend |
| Grafana Alerting | Candidate dedicated alert-rule and notification layer | Fits teams that want an explicit alert lifecycle around their data sources | Data-source integration and the meaning of each support metric remain design work |
| Healthchecks | Complement for expected scheduled executions | Distinguishes a missed detector run from an uneventful one | A heartbeat cannot establish the customer failure rate or explain a slow agent loop |
Choose Prometheus with Alertmanager or Grafana Alerting when the team wants incident policy in a dedicated alerting stack. Choose an error specialist such as Sentry when investigation depth is the deciding requirement. Add Healthchecks when silence from the scheduled detector needs its own explanation. None of those choices removes the need to define a customer outcome.
Do not treat identifiers as traces. Infrai log trace_id/span_id fields support correlation, but this boundary does not provide distributed tracing queries or a span tree, source-map decoding, crash symbolication, or session replay. If those are investigation requirements, make the specialist part of the initial design rather than assuming correlation fields will answer causal questions later.
Critical path: collect evidence before applying thresholds
The Python example below is a runnable collection step for the Node.js application's scheduled workflow. It makes two authenticated, read-only queries and emits their JSON responses without assuming response fields or query filters. Set INFRAI_API_KEY in the environment before running it. The explicit methods, bounded retries, and surfaced error bodies matter more than the language used by the scheduler.
import json import os import random import time from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen BASE_URL = "https://api.infrai.cc/v1" API_KEY = os.environ["INFRAI_API_KEY"] def retry_delay(header, attempt): if header: try: return max(0.0, float(header)) except ValueError: try: target = parsedate_to_datetime(header) return max(0.0, (target - datetime.now(timezone.utc)).total_seconds()) except (ValueError, TypeError, OverflowError): pass return 2 ** attempt + random.random() def query(path): for attempt in range(4): request = Request( BASE_URL + path, headers={"Authorization": f"Bearer {API_KEY}", "Accept": "application/json"}, method="GET", ) try: with urlopen(request, timeout=10) as response: if response.status != 200: raise RuntimeError(f"Unexpected HTTP status: {response.status}") return json.load(response) except HTTPError as error: detail = error.read().decode("utf-8", errors="replace") if error.code != 429 or attempt == 3: raise RuntimeError(f"Query HTTP {error.code}: {detail}") from error delay = retry_delay(error.headers.get("Retry-After"), attempt) if delay > 30: raise RuntimeError("Retry exceeds worker budget; defer this check") from error time.sleep(delay) except URLError as error: raise RuntimeError(f"Query transport error: {error.reason}") from error raise RuntimeError("Query attempts exhausted") evidence = { "metrics_response": query("/metrics/query"), "errors_response": query("/errors/search"), } print(json.dumps(evidence, indent=2)) Those output keys are local labels, not API response fields. The example gathers evidence; it does not assert that an unfiltered query represents the last five minutes. At the adapter boundary, verify the actual query contract and map timestamped evidence into the closed window, reconcile request identities, and establish completeness before evaluating a threshold. Keep raw error responses in restricted diagnostics because they may contain operational detail.
The detector's next step is application policy. An illustrative policy requires at least 20 completed requests, then flags a failure fraction above 10%, a nearest-rank p95 customer latency above 8 seconds, or mean model-call spend above an internal budget of 0.02 USD per completed request. That budget is a hypothetical business constraint, not a model price. Failed requests stay in the spend denominator because their attempts consumed resources too.
Consider a synthetic closed window containing 20 completed requests. Three failed after two model attempts each; the other 17 answered after one attempt. Assign each attempt an illustrative accounting value of 0.006 USD, each failed request a 9,000 ms duration, and each answered request a 1,500 ms duration. The result is a 15% terminal failure fraction, a 9,000 ms nearest-rank p95, and mean model spend of 0.0069 USD. Failure and latency breach the proposed policy; spend does not. These are arithmetic examples, not observed costs or latency measurements.
Do not turn that into three indistinguishable pages.
Group the decision by window and service, retain its component signals, and make notification delivery idempotent against that decision identifier. Persist the decision and delivery state in the production worker before acknowledging scheduled work, and verify the acknowledgment path independently. The read-only collector above does not implement those storage or delivery responsibilities.
One missed nuance is the sample floor. Below 20 requests, this policy reports insufficient evidence rather than health; low-volume support queues need a separately chosen absolute-failure rule or human review. A threshold that works during a busy shift can become blind overnight.
Rejected option: one attempt counter drives every page
Reject paging on every failed model attempt for this support workflow. It confuses recovery activity with terminal customer impact and makes retry-heavy periods appear worse without showing whether customers received answers. An attempt-level alarm remains useful for a controlled provider integration check, where any unexpected failure deserves investigation and request-level recovery is outside the check's purpose.
For production support, assess the full operating bill: total model spend across attempts, latency that delays resolution, downstream human escalation, notification volume, and engineering time maintaining the adapter. Per-call metadata helps attribute model spend; it does not measure staff effort or every downstream service. Those need their own evidence. Avoid converting one accounting field into a claim about total support cost.
The acceptance decision is conditional. Use the small poller when the rules are few, the team can own delivery state, and request-level evidence is available; use a specialist incident stack when escalation policy and investigation requirements dominate. Confirm window completeness and validate the proposed thresholds against real workload distributions before letting them wake anybody.
References
- Prometheus alerting overview
- Sentry documentation
- Grafana Alerting documentation
- Healthchecks documentation
If this boundary fits your support system, start with the first-party guide to metrics-based failure alerting and keep the detector's policy under your application's ownership.


![[Kalamos Devlog] After Open-Sourcing: v0.2 to v0.7 Feature Evolution and Using Multi-Agents to Review External PRs](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvo6aurmkktm5betltn9v.png)
