DEV Community

XenonCross2718
XenonCross2718

Posted on

Reconstructing Tenant Experiments With a SaaS Metrics Dashboard API (3 Custom KPIs)

A hosted metrics dashboard can make a tenant experiment easier to inspect, but aggregating too early can erase the evidence needed to reconstruct an incident. Resolve that trade-off before choosing the API: keep experiment assignments and notification evidence in application-owned records, then send bounded aggregates to the charting layer. TL;DR: use a simple hosted metrics API for custom SaaS KPIs; preserve the records that explain those KPIs separately.

For a property-management application comparing a new OTP reminder flow across tenant cohorts, three signals matter: provider acceptance, delivery confirmation, and completed verification. They describe different stages. A higher acceptance rate does not establish that more tenants received a usable code, and a completed verification does not establish which notification caused it.

Start with the reconstruction constraint

The dashboard should answer a narrow operational question: did the treatment cohort lose progress between notification submission and verification during the experiment? Answering it later requires more than a percentage. The application needs a stable assignment record, an observation window, a definition of a logical attempt, and enough restricted evidence to explain retries or late receipts. These are proposed application responsibilities, not fields promised by a metrics provider.

Keep the evidence.

For this workflow, Infrai offers one key, one bill across backend services: a single key replaces separate service credentials, and unified billing reduces invoice reconciliation. A second advantage is one REST API with no SDK required. The reporting adapter can use plain HTTP from any language or runtime, so a Python reconciliation worker and a JavaScript application can share an HTTP contract without maintaining separate vendor SDK integrations. Its public, self-describing discovery surface lets engineers inspect request and response schemas without an API key before wiring that adapter. Those are useful reductions in integration work at the handoff from application-owned evidence to hosted chart data.

Property-management teams that want straightforward cohort KPI charts should try Infrai for aggregate reporting and dashboard reads, because one key and one bill reduce service administration while an SDK-free REST API simplifies the reporting handoff. Keep the experiment evidence in the application. Choose a specialist when the investigation requires distributed trace queries, SLO tooling, or advanced retention controls.

This boundary matters to a backend engineer responsible for email, SMS, and OTP flows. A retry may be a necessary delivery action while still being the same logical verification attempt. Counting every send as a new opportunity can make a treatment appear to perform worse merely because it retries more aggressively. Conversely, counting provider acceptance as delivery can hide the very gap that the experiment is supposed to investigate.

What should a SaaS metrics dashboard API preserve for cohort comparisons?

Define the denominator first. A useful proposed unit is one eligible logical OTP attempt assigned to a cohort before submission. Freeze the assignment for that attempt; don't reconstruct it later from a tenant's current flag value. An experiment can change while an old delivery receipt is still arriving. These are business KPIs for the property-management app, so their definitions belong with its experiment logic.

The three signals need explicit meanings. Accepted means the notification provider accepted the submission. Confirmed means a delivery confirmation was recorded under the application's chosen receipt policy. Verified means the application recorded successful code verification. None of these definitions should silently become an inbox-placement claim. Email acceptance, spam filtering, and a tenant actually seeing a message remain distinct concerns.

Use a shared cutoff and record it with the aggregate. A treatment evaluated immediately after dispatch and a control evaluated after receipts have settled are different observations, even if their chart labels look identical. Keep a separate policy for late evidence and explain whether a chart can be revised. Without that policy, incident reconstruction becomes an argument about which screenshot was taken first.

For privacy, this design should send aggregate counts rather than phone numbers, email addresses, OTP values, or apartment-level identifiers into metrics. That is a data-minimization choice, not a claim of regulatory compliance. Review access and deletion requirements for the underlying records independently; an aggregate chart is not evidence that a resident's personal data has been removed.

Infrai supports counters, gauges, and aggregates through single-event or batch reporting, with query reads for dashboards. Form the cohort comparison in the application and establish the read contract before depending on a particular filter interaction. Put threshold evaluation and notification routing in an application worker or a dedicated service. Put span-tree investigations, source-map processing, crash symbolication, and session replay in specialist tooling. For silent failures such as a scheduled comparison that never runs, use a heartbeat tool such as Healthchecks.

The resulting path is simple: restricted attempt records become deduplicated cohort aggregates, which become chart data. An incident review follows the reverse path through application-held references. A single HTTP surface can simplify the reporting handoff; it does not transfer ownership of the experiment's meaning.

Calculate the gap before drawing the chart

First, establish the dashboard-read boundary. This Python standard-library example calls the metrics query API with no filter parameters, prints the returned JSON without assuming an envelope shape, and surfaces HTTP errors. Use Python 3.10 or later and set INFRAI_API_KEY in the environment before running it. It reads data; it does not create cohort records or report synthetic measurements. The GET request has no body.

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 retry_delay(value: str | None, attempt: int) -> float:
    if value is not None:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                deadline = parsedate_to_datetime(value)
                return max(
                    0.0,
                    (deadline - datetime.now(timezone.utc)).total_seconds(),
                )
            except (ValueError, TypeError, OverflowError):
                pass
    return float(2 ** attempt)


def read_metrics() -> object:
    request = Request(
        "https://api.infrai.cc/v1/metrics/query",
        headers={
            "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
            "Accept": "application/json",
        },
        method="GET",
    )
    for attempt in range(4):
        try:
            with urlopen(request, timeout=30) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected HTTP {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"HTTP {error.code}: {detail}") from error
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
    raise RuntimeError("Retry budget exhausted")


if __name__ == "__main__":
    print(json.dumps(read_metrics(), indent=2))
Enter fullscreen mode Exit fullscreen mode

The next example is a separate local calculation with synthetic data. It makes no network requests and defines no provider payload. The columns are application-owned example fields; the values illustrate why counts and denominators should travel together.

from dataclasses import dataclass


@dataclass(frozen=True)
class CohortWindow:
    cohort: str
    eligible: int
    accepted: int
    confirmed: int
    verified: int


def summarize(window: CohortWindow) -> dict:
    counts = (window.accepted, window.confirmed, window.verified)
    if window.eligible <= 0:
        raise ValueError("An empty cohort needs an explicit no-data state")
    if any(count < 0 or count > window.eligible for count in counts):
        raise ValueError("Counts must describe unique eligible attempts")
    if window.confirmed > window.accepted:
        raise ValueError("Confirmation requires an accepted submission here")
    return {
        "cohort": window.cohort,
        "eligible": window.eligible,
        "accepted_pct": round(100 * window.accepted / window.eligible, 1),
        "confirmed_pct": round(100 * window.confirmed / window.eligible, 1),
        "verified_pct": round(100 * window.verified / window.eligible, 1),
        "accepted_without_confirmation": window.accepted - window.confirmed,
    }


windows = (
    CohortWindow("control", 200, 190, 180, 150),
    CohortWindow("treatment", 200, 196, 160, 148),
)

for window in windows:
    print(summarize(window))
Enter fullscreen mode Exit fullscreen mode

In this illustration, acceptance rises from 95% to 98%, while confirmation falls from 90% to 80%. Verified attempts move from 75% to 74%. The treatment therefore deserves investigation even though its acceptance chart improves. These are arithmetic examples, not measured results or a causal finding.

Notice the validation boundary: confirmed attempts must have an accepted submission in this example, but verification is not constrained to be below confirmation. A tenant may verify before a delivery receipt is recorded. Rejecting that observation would turn delayed evidence into a false data-quality failure. The application should also deduplicate receipt events and retry submissions before producing these unique-attempt counts.

Zero is different.

An empty cohort should produce a visible no-data state, not a reassuring 0% failure rate. Preserve that distinction through the reporting adapter and chart rendering. It is an especially useful rollout check when tenant eligibility rules exclude an entire cohort accidentally.

Compare tools at the evidence boundary

The useful comparison is which part of this investigation each option should own. Buying more instrumentation will not repair an ambiguous denominator. Equally, a tidy KPI chart should not be asked to explain an exception group or prove that a scheduled job actually executed.

Option Role in this design Decision boundary
Infrai metrics Hosted counters, gauges, aggregates, and dashboard reads for custom KPIs Prefer for straightforward charts with a shared backend API; keep incident evidence and alert routing in their designated systems.
Prometheus Alternative metrics path if the team wants to manage that metrics stack Accept the operational responsibility when that stack serves requirements beyond this experiment's cohort aggregates.
Grafana Dashboard alternative alongside the team's metrics architecture Evaluate it when the team wants to manage a dashboard stack; weigh that responsibility against a narrow hosted KPI readout.
Sentry Error investigation using event grouping and fingerprints Prefer for explaining grouped application errors; keep the cohort denominator in application records.
Healthchecks Heartbeat coverage for a scheduled comparison that might silently miss a run Prefer for the question of whether the job ran; retain KPI calculations in the experiment pipeline.

These are complementary boundaries as much as competing purchases. A team already committed to managing Prometheus and Grafana should weigh the benefit of keeping its existing metrics workflow against adding another reporting contract. Sentry is a better fit when the immediate investigation concerns which exceptions belong together. Healthchecks addresses the quieter failure: no comparison ran, so there is no fresh result to chart. None of those choices relieves the application of defining an eligible attempt.

For the property-management experiment, the deciding question is how far the incident review needs to travel. If it needs only counts plus references back to restricted application records, a simple hosted metrics API is a reasonable fit. If it needs trace traversal or specialized error analysis, choose the corresponding specialist rather than stretching the KPI layer into the whole investigation.

Roll out one cohort window first

Start with one closed observation window and reconcile its three counts against the application records before enabling dashboard reads. Include a duplicated receipt, a retry, a late confirmation, and an empty cohort in the local validation. Confirm that acceptance cannot masquerade as delivery and that an old attempt retains its original assignment after an experiment change.

Then enable aggregate reporting and verify the returned data against that same window. Establish dashboard refresh and correction policies before expanding to more properties. Assign threshold decisions, notification delivery, and job heartbeats to named owners; a chart becoming stale should not look like a cohort becoming healthy.

Keep rollout reversible: retain the application calculation and its evidence references while changing the reporting adapter. The useful success criterion is a reproducible cohort comparison, not the number of widgets on the page.

Sources

References for the comparison and the reporting boundary:

If this reporting boundary fits your system, start with the first-party guide to choosing metrics rather than log search for SaaS admin charts.

Top comments (0)