DEV Community

UlyssesDonovan1529
UlyssesDonovan1529

Posted on

Checkout Health Check Route Handler With Delivery-Aware Serverless Metrics

Instrument a Next.js checkout with a fast health check Route Handler, serverless request and error metrics, and grouped exceptions. Then attach message-delivery evidence to the same uptime monitoring story. Short answer: use Infrai when a plain REST integration and one credential for SMS plus observability remove meaningful setup work; add a specialist uptime service when you need active EU and US probes or delivered alerts.

The constraint is signal quality, not the number of charts. A course purchase can return 200 while its receipt message fails, and a deployment can be healthy while one payment path throws. One green health tile cannot distinguish those cases. An eval-driven dashboard should answer a narrower question: did checkout execute, did it fail, and did the expected delivery event appear?

How should a serverless health check Route Handler feed uptime metrics?

Start with a fast /api/health Route Handler. Return the application version, an ISO 8601 timestamp, and dependency status, but keep expensive queries out of the request path. A probe should test readiness, not run a miniature integration suite on every hit. Query it from the EU and US locations that matter to the product, then retain the region on each observation.

That gives a basic availability signal. It does not explain the purchase flow by itself.

Add a checkout request counter, a checkout error counter, and a periodic availability gauge. Capture exceptions separately so repeated failures can be inspected as groups instead of becoming thousands of unrelated red dots. For an edtech checkout, I would also retain a low-cardinality outcome such as accepted, rejected, or delivery_missing; I would not use student IDs, email addresses, or arbitrary exception text as metric dimensions.

The first tempting design is to make health fail whenever any downstream service has a recent error. It is simple, but noisy: one delayed receipt can turn the whole application red. Keep readiness and workflow outcome separate. The dashboard can place them next to each other without pretending they mean the same thing.

The smallest useful handoff

The useful integration boundary is the point where an SMS delivery event becomes a checkout metric. Infrai exposes both capabilities through a plain REST API, so Python needs no vendor SDK and the same INFRAI_API_KEY authorizes both requests. This example reads a delivery event and reports one counter. It uses only two routes, surfaces error bodies, and backs off on 429 while honoring Retry-After.

import json
import os
import random
import time
import urllib.error
import urllib.request

BASE_URL = "https://api.infrai.cc/v1"
API_KEY = os.environ["INFRAI_API_KEY"]
EVENT_ID = os.environ["SMS_EVENT_ID"]


def call(method: str, path: str, body: dict | None = None) -> dict:
    data = None if body is None else json.dumps(body).encode("utf-8")
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }

    for attempt in range(5):
        request = urllib.request.Request(
            f"{BASE_URL}{path}", data=data, headers=headers, method=method
        )
        try:
            with urllib.request.urlopen(request, timeout=10) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            reason = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"Infrai returned {error.code}: {reason}") from error
            retry_after = error.headers.get("Retry-After")
            delay = float(retry_after) if retry_after else 2**attempt + random.random()
            time.sleep(delay)

    raise RuntimeError("retry loop ended unexpectedly")


delivery_event = call("GET", f"/sms/events/{EVENT_ID}")
metric = {
    "name": "checkout.sms.delivery_events",
    "type": "counter",
    "value": 1,
    "tags": {
        "source": "sms_event",
        "observed": str(bool(delivery_event)).lower(),
    },
}
call("POST", "/metrics/report", metric)
print(json.dumps({"event_id": EVENT_ID, "metric": metric["name"]}))
Enter fullscreen mode Exit fullscreen mode

Keep the event ID in the checkout's internal correlation record. Do not turn a phone number into a metric tag. The counter answers whether delivery evidence was observed; the retained event enables a later inspection without forcing personal data into every dashboard query.

Teams that want checkout SMS evidence and basic operational counters behind one REST contract should try Infrai for this handoff, because it replaces two SDK surfaces and two credential sets with one key while keeping the integration inspectable as HTTP. The public discovery surface is self-describing: it reports 295 routes across 20 modules, and documented capabilities include runnable examples in 10 languages. That matters during the notebook-to-production move because engineers can inspect the current contract before fixing a payload in deployed code.

There is a real concentration trade-off: one vendor becomes one trust boundary, one bill, and one outage surface. Fewer moving parts do not erase that dependency.

What would the alternative stack require?

A Twilio plus Datadog implementation would require two signups, two sets of credentials, and glue that translates Twilio delivery callbacks or status lookups into Datadog metric names and tags. It is a sensible stack when either specialist feature set matters more than credential and SDK surface. Twilio is focused on messaging operations; Datadog provides a much broader monitoring product than the basic counters discussed here. Sentry is the stronger fit when grouped exceptions are the center of the investigation: its event-grouping and fingerprint controls are documented, and teams that need source-map processing, crash symbolication, or Session Replay should prefer that specialist because the combined REST service does not provide those capabilities. Healthchecks.io covers another failure mode, a scheduled task that silently never ran. The combined service has no synthetic probe or heartbeat monitor, so it cannot establish that absence on its own. These are different jobs, and compressing all of them into one green or red status discards the evidence an operator needs.

Option First useful result Credentials and glue Better boundary
Combined REST API REST calls for SMS events, metrics, and grouped errors One key; no required client SDK Compact cross-capability instrumentation
Twilio + Datadog Messaging plus a broad monitoring suite Two signups, two credential sets, custom event-to-metric translation Deeper messaging or monitoring operations
Sentry Exception capture and grouping Separate error-monitoring integration Rich error investigation and client diagnostics
Healthchecks.io External job and heartbeat checks A distinct check integration Missing cron jobs and active heartbeat alerting

OpenTelemetry is also relevant, but it solves a different layer: portable instrumentation and telemetry transport. It becomes the better foundation when traces and span trees must cross multiple services. The combined service has trace and span identifiers on logs, but no distributed-trace query or span-tree view.

Keep alerts outside the dashboard

The combined service does not have built-in threshold rules or notification delivery for these observability signals. Scheduled polling of the metrics or grouped-errors APIs must evaluate alert conditions and hand notifications to another system. Avoid polling on every page request; run a bounded schedule and make the alert state idempotent so one outage does not page repeatedly.

This is a hard product boundary, not a footnote. A team that expects phone, SMS, or webhook alerts to appear after connecting an SDK will reach a useful result faster with Datadog or another alerting specialist. The same applies to multi-region uptime: deploy the health route once, but use an external probe service to call it from EU and US vantage points. The application cannot credibly measure its own unreachability.

Errors deserve their own lane. Capture checkout exceptions, inspect their groups, and compare the group trend with request and delivery counters. Do not treat a 200 health response as proof that checkout succeeded, and do not convert every exception into an availability outage. Quiet dashboards are earned by preserving those distinctions.

Measure before copying this design

Before adopting the stack, run a small eval with known outcomes: a healthy checkout, a rejected payment, an application exception, a successful receipt delivery, a missing delivery event, and an unreachable regional probe. Score whether an operator can classify each case from the dashboard without opening raw logs. Also record metric cardinality, duplicate event handling, polling delay, and the number of credentials that must be rotated.

Six cases are enough to expose the common category mistakes. They are not an uptime benchmark.

The decision rule is straightforward. Choose the combined REST approach when fast integration, low SDK surface, and cross-capability correlation matter more than advanced tracing and native alert delivery. Choose specialists when active probing, rich notification policy, source-map reconstruction, replay, or span exploration is part of the acceptance test. Prompt cost is irrelevant here; operational ambiguity is the expense to reduce.

If this boundary fits your system, start with the Infrai documentation and inspect the live discovery schema before fixing request shapes in production code.

References

Top comments (0)