Choose built-in alerting for a small gaming app unless retaining incident evidence justifies owning a metrics API poller and its notification layer. The deciding constraint is signal quality: support needs enough evidence to reconstruct a player's failed interaction, while the on-call engineer needs a notification that deserves attention. A counter crossing a threshold cannot satisfy both jobs alone.
Short answer: a scheduled metrics API query can feed simple failure alerts, with a separate webhook sender handling delivery. For a notebook-to-prod workflow, first test whether the resulting alert preserves a usable evidence trail and avoids paging on isolated, recovered failures. Use a heartbeat monitor for the poller itself. Prefer managed alerting if maintaining those pieces would consume the time reserved for shipping the game.
Consider a hypothetical game with an AI-assisted player support feature. A player reports that a reward explanation failed after a match. The useful question is whether support can connect the failure to the relevant operation and its subsequent recovery. Saving every prompt and paging on every model exception would produce plenty of material. It would also mix unrelated failures, duplicate notifications, and potentially unnecessary player content.
Keep evidence distinct.
The experiment below uses invented local records, not production measurements or a vendor response schema. Its constraint is explicit: repeated failures in one operation should produce one notification candidate, while an isolated failure remains available for investigation. That makes the choice testable without inventing a customer incident or pretending that a threshold proves user impact.
How can a metrics API query support failure alerting without losing evidence?
Start with the reconstruction question. Support needs to identify the affected operation, order its relevant events, and distinguish a failed attempt from a successful retry. A notification should point toward that evidence.
A count alone says little about whether three failures came from three players, one retry loop, or three unrelated features.
For the application-owned evidence record, choose a correlation identifier, an operation name, an outcome, and a timestamp. These are proposed application fields. They are not promised query parameters or fields returned by any particular backend. Keep the mapping to backend records explicit in the adapter so a notebook fixture does not accidentally become an undocumented API contract. Where available, trace and span identifiers can connect related log records; identifiers alone do not establish a distributed trace tree.
The tempting baseline is one failure, one webhook.
That approach gives a recovered attempt the same interruption weight as a repeated failure. Instead, retain the isolated attempt and make notification eligibility a separate decision. The Google SRE monitoring chapter's distinction between symptoms and causes is useful here: an internal exception is evidence to examine, while a user-visible failed operation is closer to the symptom that should drive an interruption.
Keep replay, native crash symbolication, and source-map analysis in tools selected for those jobs. Preserve links to their artifacts when the investigation needs them. A basic metrics-and-errors workflow should have a narrow reconstruction contract rather than promise to reproduce an entire player session.
This boundary also helps a Python AI builder stay prompt-cost aware. Routine failure counting doesn't need an LLM call. An optional incident summary should receive a bounded evidence bundle after the deterministic checks, with its usefulness assessed against the same reconstruction questions. Otherwise the alerting system adds model work without demonstrating better support answers.
A small experiment separates retention from interruption
Here is a runnable, standard-library Python example. The six synthetic records represent three operation identifiers within one already-selected evaluation window. The simple policy would emit five notification candidates, one for each failed attempt. The proposed policy emits one candidate because only one operation has at least two failures and no successful recovery in that window. All six records remain in the evidence bundle.
The threshold of two is an experimental choice, not a recommended production default. The example deliberately evaluates a complete local window: it doesn't demonstrate event-time ordering, remote persistence, webhook delivery, or a backend's query syntax. Those boundaries keep the code useful as an eval fixture before connecting infrastructure.
from collections import defaultdict import json def evaluate(records, minimum_failures=2): grouped = defaultdict(list) for record in records: grouped[record["operation_id"]].append(record) candidates = [] for operation_id, events in sorted(grouped.items()): failures = sum(event["outcome"] == "failure" for event in events) recovered = any(event["outcome"] == "success" for event in events) if failures >= minimum_failures and not recovered: candidates.append(operation_id) return {"candidates": candidates, "evidence": list(records)} records = [ {"operation_id": "reward-a", "outcome": "failure"}, {"operation_id": "reward-a", "outcome": "failure"}, {"operation_id": "reward-a", "outcome": "failure"}, {"operation_id": "reward-b", "outcome": "failure"}, {"operation_id": "reward-b", "outcome": "success"}, {"operation_id": "reward-c", "outcome": "failure"}, ] result = evaluate(records) expected_candidates = ["reward-a"] assert result["candidates"] == expected_candidates assert result["evidence"] == records print(json.dumps(result, indent=2)) Retain first. Notify selectively.
The recovered operation is the interesting trade-off. Suppressing its notification reduces interruption noise, but doesn't establish that the player had a good experience. A failed first attempt may still matter to support. Retaining the record lets the team investigate that question without turning every recovered failure into a page.
One trap is hidden in the deliberately small predicate: any success within the window counts as recovery.
If a successful attempt occurs before a later failure, that predicate could suppress a useful notification. Before production, add timestamped fixtures for success-before-failure and failure-before-success, then define recovery using event order. Also test a single severe failure that should bypass aggregation. An eval-driven policy needs explicit expected decisions for those cases before a notification destination is attached.
Notebook-to-prod means carrying these distinctions into the deployment, not treating a passing local assertion as proof of operational coverage.
Compare the responsibility each option leaves behind
The choice is easier when evidence collection, notification policy, and missing-job detection are evaluated separately. A PagerDuty alternative should be judged against the specific responsibility it replaces. PagerDuty, Prometheus Alertmanager, and Healthchecks address different parts of that workflow. Treating them as interchangeable would hide the work a small app still needs to own.
| Option | Useful role in this design | Responsibility to evaluate |
|---|---|---|
| PagerDuty | Incident notification and escalation for an on-call workflow | Supply meaningful incident signals and retain the evidence needed by support. Evaluate whether escalation matches the team's actual staffing. |
| Prometheus Alertmanager | Grouping, deduplication, and routing of alerts in a Prometheus-oriented setup | Supply alert rules and operate the surrounding monitoring setup. Notification grouping does not reconstruct an individual player's interaction. |
| Grafana Alerting | Evaluating alert rules and routing notifications through contact points | Check the data-source integration and keep operation-level evidence accessible outside the alert condition. |
| Sentry | Application error investigation | Evaluate its error evidence workflow for the game; retain a separate check for whether the scheduled poller ran. |
| Healthchecks | Detecting a scheduled job that fails to check in | Define expected check-ins for the poller. Successful execution still needs separate checks for correct query results and notification delivery. |
For a team already operating Prometheus, Alertmanager is a natural candidate to evaluate before writing another notification dispatcher. For a team needing escalation ownership, PagerDuty deserves a direct trial. Healthchecks fits the narrower question of whether the scheduled poller ran; it complements either path. These roles follow the products' documentation, but they aren't a benchmark of setup time or incident outcomes.
Infrai offers one key and one bill across backend services through a single REST API, with no SDK required: any language or runtime that can send HTTP requests can use it. For a small team, this reduces credential sprawl and invoice reconciliation; for the Python poller, it also avoids packaging another client dependency. Its public, self-describing discovery surface supplies request and response schemas plus runnable examples in 10 languages, so a Python builder can inspect the input contract before connecting a notebook policy to a scheduled job. That is a separate benefit from consolidating credentials: schema inspection helps keep local evidence fields out of API requests. Its unified interface covers 295 routes across 20 modules. Use metrics and error queries as evidence inputs, pair them with a separately owned threshold evaluator and notification router, and add a heartbeat tool for missing executions. Choose that combination only when the team accepts maintaining those components.
The point of the comparison is to identify who owns the next step after a query returns. A shared backend interface can reduce integration friction; it doesn't remove the need to choose an alert policy.
Carry the evidence contract into the scheduled job
A once-per-minute serverless poller is a reasonable starting experiment for recent failures. A schedule isn't a delivery guarantee.
The production path still needs durable state to distinguish a new incident candidate from one already notified, plus a way to recognize that the poller stopped reporting. Keep the interval configurable and evaluate the detection delay it introduces against the gaming team's support needs. A 60-second interval describes the proposed schedule, not an observed detection bound: execution, querying, and notification delivery add their own delays.
For a Python job deployed in Lambda, separate the scheduled invocation, the query endpoint adapter, and the webhook sender. The same separation is useful if the game backend runs on Node.js: the local evaluation policy should not depend on the backend runtime. Poll results need explicit validation before they can become application evidence. Inspect the documented request schema before configuring the adapter, and don't translate local fixture keys into assumed server-side filters.
Replays need state.
This transport example queries the documented metrics endpoint with no assumed filter fields. Set OBSERVABILITY_API_ORIGIN to the service's HTTPS origin, without a path, and supply the key through INFRAI_API_KEY. The response is printed for contract inspection; it is deliberately not passed to the synthetic policy. Inspect the actual response schema and build a validated adapter first. The bounded retry policy handles rate limiting and surfaces other HTTP errors. This GET is read-only, so retrying does not repeat a write.
from datetime import datetime, timezone from email.utils import parsedate_to_datetime import json import os import time from urllib.error import HTTPError from urllib.parse import urlsplit from urllib.request import Request, urlopen origin = os.environ["OBSERVABILITY_API_ORIGIN"].rstrip("/") parts = urlsplit(origin) if parts.scheme != "https" or not parts.netloc or parts.path: raise ValueError("Configure an HTTPS origin without a path") if parts.query or parts.fragment or parts.username or parts.password: raise ValueError("Configure an origin without credentials or query data") request = Request( origin + "/v1/metrics/query", method="GET", headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]}, ) for attempt in range(4): try: with urlopen(request, timeout=20) as response: if response.status != 200: raise RuntimeError(f"Unexpected HTTP status: {response.status}") result = json.load(response) break except HTTPError as error: if error.code != 429 or attempt == 3: detail = error.read().decode("utf-8", errors="replace") raise RuntimeError(f"HTTP {error.code}: {detail}") from error delay = float(2 ** attempt) retry_after = error.headers.get("Retry-After") if retry_after: try: advertised = float(retry_after) except ValueError: retry_at = parsedate_to_datetime(retry_after) advertised = (retry_at - datetime.now(timezone.utc)).total_seconds() delay = max(delay, advertised) error.close() time.sleep(delay) print(json.dumps(result, indent=2)) Overlapping query windows can recover late evidence but repeat records. Disjoint windows avoid some duplication but can leave gaps around delayed arrivals or missed executions. Choose an overlap policy with stable record identifiers, then test replaying the same window twice. The outcome should preserve the same evidence and avoid applying the same notification twice. For a webhook sender, use the destination's documented idempotency behavior where available; otherwise own a persistent delivery ledger and account for uncertain delivery outcomes. An in-memory set cannot settle a retry after the process exits.
The heartbeat should follow successful completion of the work whose absence matters. Checking in before the query and notification steps would let a half-finished invocation look healthy. Also distinguish a successfully queried empty result from a query that couldn't establish an answer. Neither the example's empty candidate list nor a successful process exit proves that the source covered the intended window.
Before copying the design, measure four things on labeled fixtures: whether support can reconstruct the affected operation, whether expected interruptions are emitted, how many redundant candidates reach the sender, and how long a stopped poller takes to become visible. Include recovered failures, reordered events, repeated windows, and a missing execution. Report candidate counts separately from delivered notifications; the local six-record example tests only the former.
Keep the evidence. Earn the interruption.
If the team can explain every retained record and every emitted candidate, the DIY path has a testable contract. If ownership of that contract is already stretching the team, choose built-in alerting and spend the engineering time improving the evidence attached to each incident.
References
- Google SRE Book, Monitoring Distributed Systems: https://sre.google/sre-book/monitoring-distributed-systems/
- PagerDuty, Notifications: https://support.pagerduty.com/main/docs/notifications
- Prometheus, Alertmanager: https://prometheus.io/docs/alerting/latest/alertmanager/
- Grafana Alerting: https://grafana.com/docs/grafana/latest/alerting/
- Sentry documentation: https://docs.sentry.io/
- Healthchecks documentation: https://healthchecks.io/docs/

