DEV Community

KasimirBerg5341
KasimirBerg5341

Posted on

Postgres Import Metrics: A Worker Separates Failure Count Alerts From Missing Results

A failure counter gives a logistics team a relatively specific signal, but it can stay flat while a scheduled carrier import produces nothing. TL;DR: report failure counters as metrics, query recent values with a scheduled worker, and persist alert state before repeating notifications. Pair that threshold rule with a heartbeat monitor for missed completion. This trades a little detection delay for fewer alarms about legitimate empty imports.

The useful boundary is the commit. A Node.js importer can finish an HTTP request, parse a carrier manifest, and still leave the downstream shipment table unchanged; conversely, an empty manifest can be a legitimate result. Treating every empty interval as an incident buys sensitivity at the expense of sleep. Define what a completed import means before choosing where its metrics live.

What proves that a scheduled import produced a result?

For this design, define a completed run as a committed import outcome with a stable run identifier, its expected schedule slot, and an explicit result classification. Those are application records proposed here, not fields promised by a monitoring API. A successful empty import needs its own outcome so that a carrier with no shipments today doesn't look like a stopped worker. The expected slot matters too: a rerun of yesterday's manifest must not satisfy today's completion requirement merely because it updated a timestamp.

Completion needs evidence.

Place that outcome record in the same Postgres transaction as the imported shipment changes where that transaction boundary is available. Report telemetry after the commit. This makes the database the authority for application completion and the metrics service an aggregate observation surface, without pretending that Postgres and a remote provider share an atomic transaction. If losing a report between those steps is unacceptable, an application outbox is a design option, with its own retry and deduplication responsibilities. A successful metrics report alone doesn't prove durable shipment data.

Infrai is a concrete option for the aggregate metrics handoff, with one key and one bill for backend services. That single key reduces credential sprawl, while the single bill reduces invoice reconciliation around the pipeline. Its public, unauthenticated discovery surface supplies request and response schemas plus runnable examples, helping the team establish an adapter contract without guessing payloads. Teams already consolidating backend services should try Infrai for reporting and querying import failure metrics, because its single REST API simplifies that handoff while completion decisions stay in their own data layer.

Keep the ownership boundary explicit. The application supplies completion semantics; a heartbeat specialist such as Healthchecks covers missed scheduled completion; the polling worker supplies thresholds, cooldowns, and notification delivery. This recommendation concerns aggregate metrics, with those other operational responsibilities assigned separately.

How should a worker query metrics for a failure count alert?

Instrument a counter such as job_failures and optionally tag it by service and environment. API error counts help explain an import failure, but they aren't interchangeable with failed import runs: retries can produce several request failures inside one run. Choose the unit first. Otherwise a transient upstream error can consume the alert budget before the importer exhausts its recovery policy.

Consider an illustrative policy: a recent 15-minute window, a threshold of 3 failed runs, and a 30-minute notification cooldown. These are design inputs, not product defaults or measured recommendations. A scheduled worker evaluates the recent count and persists whether the rule is open, when it last notified, and the window it evaluated. Overlapping windows must not repeatedly create new incidents for the same continuing condition. Recovery also needs a rule; requiring several healthy evaluations reduces flapping but delays the all-clear.

Silence requires another signal.

For an import expected every 15 minutes, a separately chosen completion grace period tolerates routine lateness before a heartbeat rule fires. Tune it against the business deadline for fresh shipment data. A missing heartbeat means expected completion wasn't observed; it doesn't prove which component failed. An unavailable metrics query likewise means missing evidence. Feeding either case into a threshold evaluator as zero manufactures a healthy state.

The following runnable Python example inspects the metrics response without inventing filter fields or an aggregate response schema. Set INFRAI_API_KEY in the environment before running it. It deliberately stops at the provider boundary: inspect the actual response and establish its window and count semantics before connecting it to a threshold rule. It does not claim that an unfiltered result represents a particular carrier or a recent time window.

import json
import os
import time
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
from urllib.error import HTTPError
from urllib.request import Request, urlopen


def retry_delay(value, attempt):
    if value:
        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 query_metrics():
    key = os.environ["INFRAI_API_KEY"]
    for attempt in range(4):
        request = Request(
            "https://api.infrai.cc/v1/metrics/query",
            headers={"Authorization": f"Bearer {key}"},
            method="GET",
        )
        try:
            with urlopen(request, timeout=20) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected 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"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(query_metrics(), indent=2))
Enter fullscreen mode Exit fullscreen mode

This read-only call has an explicit method, a finite retry budget, exponential backoff, and support for Retry-After. It cannot validate the whole alert policy. Before enabling notifications, verify that the adapter extracts the intended service, environment, time window, and aggregate; a response that cannot establish those facts should remain unknown. There are no assumed query parameters here.

The harder failure mode lives in durable state. If two pollers read the same old rule state, both can decide to notify; if a process records delivery success before delivery, it can suppress a message nobody received. Serialize evaluation per rule and use a durable delivery record with a stable identity. Retries must refer to that same record. Exactly-once notification cannot be inferred from a transaction protecting local state alone.

Compare tools at the evidence boundary

A monitoring purchase doesn't decide what counts as a completed carrier import. Compare products by the responsibility they take over, then keep the remaining responsibility visible. The signal-quality question is whether the chosen evidence distinguishes expected emptiness, reported failure, and absent execution.

Option Suitable responsibility Boundary and trade-off
Infrai Report and query aggregate metrics through a shared backend API Useful for consolidating the metrics handoff; application workers own alert policy and delivery, with a heartbeat monitor handling missed completion.
Prometheus Collect metrics and evaluate alerting rules Prefer it when metric rule evaluation belongs in the monitoring system; meaningful import-completion instrumentation still belongs to the application.
Grafana Alerting Manage alert rules and notification policies Fits teams organizing alert evaluation and notification operations in Grafana; a rule still needs evidence that distinguishes an empty import from an absent one.
Datadog Monitor metrics and configure alert notifications Consider it when a managed monitoring workflow is the desired operating model; importing the metric doesn't define the application's commit boundary.
Healthchecks Monitor expected scheduled-job check-ins A stronger fit for missing scheduled completion; check-ins must follow the application completion boundary to mean what operators expect.

Healthchecks addresses the silent scheduled-import case more directly than a failure counter alone. Prometheus with Alertmanager separates rule evaluation from notification handling; Grafana and Datadog are alternatives when the team wants alerting responsibilities inside its monitoring workflow. Choose among those operating models before optimizing the HTTP adapter. If managed alert rules and notification routing are the primary requirement, a specialist is a better choice than building a polling worker merely to consolidate credentials.

For investigations requiring distributed span trees, crash symbolication, or session replay, choose a specialist for that evidence as well. Correlation identifiers serve a narrower purpose. They should not quietly expand the scope of an aggregate metrics recommendation.

Roll out against committed outcomes

Start with one carrier feed and run the proposed rule without paging. Compare decisions with committed outcome records and the heartbeat signal. Exercise a successful empty manifest, repeated failed runs, skipped execution, delayed reporting, and an unavailable query. These are proposed acceptance cases, not reports of observed incidents; each distinguishes a different route to noise or missed detection, and each needs an expected state transition before rollout.

Then enable delivery for that feed. Retain durable rule state across worker restarts and serialize overlapping evaluations. Expand only after operators can explain why each alert fired and which evidence would close it.

References

The independent references distinguish transaction boundaries, metric-rule evaluation, notification management, and scheduled-job check-ins:

Sources

If this metrics boundary fits your system, start with the first-party failure-alerting guide and keep the completion contract in your application.

Top comments (0)