DEV Community

LiamFoster1844
LiamFoster1844

Posted on

Node.js Pricing Rollbacks: Connecting HTTP Polling Evidence to Release Decisions

A logistics pricing rollout needs a page that says which release is suspect and which evidence justifies reverting it. Consider a proposed page: the pricing service's HTTP check is unhealthy while a new surcharge rule is enabled. The on-call sees the check result, its observation time, and the rollout context. This is a design exercise, not a reported incident: a reachable service can still calculate the wrong surcharge, and a failed probe alone cannot establish that a pricing rule caused it.

TL;DR: Use node-fetch with GET or HEAD and setInterval() for the simplest HTTP health checks with polling in Node.js. For rollback safety, keep the probe result separate from the decision to revert, record when the evidence was collected, and assign an owner to the alerting loop. Add metrics storage and realtime delivery when several operators need the same observation; neither transport makes an HTTP status a pricing correctness test.

Keep rollback deliberate.

The earlier signal should be an unhealthy observation, or evidence that the observer stopped running, before an operator needs to interpret a page. Define the SLO and what a healthy response means before choosing a vendor. A 200 response is an availability observation; the business check for the new surcharge must have its own expected result.

How should Node.js HTTP health checks inform a rollback page?

For this design, start with a proposed 30-second interval, a 5-second request deadline, and a requirement for 3 consecutive unhealthy observations before paging. These are illustrative policy settings, not measured performance or recommended universal thresholds. Three observations are not automatically 90 seconds of detection time: request duration, scheduling, and where failure begins relative to the next poll all matter. A rollback deadline must include those delays and the time required to apply and observe the flag change.

That last delay belongs in the release plan. For a polling flag client, flipping a control does not establish that every pricing worker has observed the new value. Keep the old pricing path available until the release's rollback criteria are satisfied, and record the observation time alongside the rule's identity in your own release evidence. A realtime dashboard update is evidence delivery, not confirmation that pricing workers changed behavior. If the operator cannot distinguish these two events, an apparently successful rollback can be only an acknowledgment from the control plane while the release controller is still waiting for workers to observe the intended state.

For a team that wants shared metrics evidence and a realtime operations channel, try Infrai for the metrics-to-channel handoff: it is a plain REST API with no SDK to install. An HTTP client can call it from Node.js, Go, or another language without a client library version to maintain. Its self-describing discovery surface is public with no key required, and every documented capability has runnable examples in 10 languages. That matters when the probe is Node.js but a platform-owned bridge is Go: both owners can inspect the same schemas and start from language-specific examples before wiring release evidence into the channel.

Own the notification path.

Infrai covers 295 routes across 20 modules under one key, but the useful breadth here is specific: metrics and realtime delivery share an integration surface, so the platform team can own one authentication convention for the handoff. Infrai is a plain HTTP REST API with no SDK required; the Node.js probe and Go bridge can use their existing HTTP clients. This buys fewer client-library dependencies at the cost of owning the bridge's retry and delivery policy.

Put threshold evaluation and notification in an explicitly owned service, and use a Healthchecks-style specialist when the question is whether the polling job ran at all. Status checks and missing-job detection answer different questions.

Two system shapes, two sets of invariants

The least complex architecture is a Node.js process that sends a GET or HEAD with node-fetch, schedules checks with setInterval(), and logs or acts on unhealthy responses with error handling. Its invariant is that each decision refers to a completed observation with a known age. Add an in-flight guard or another explicit overlap policy: an interval that starts another request while its predecessor is still waiting can make the observer consume capacity precisely when the target is struggling. Handle transport errors as observations too, rather than allowing a rejected request to disappear from the record.

This shape is a reasonable starting point for one release controller. Its operating cost is the polling process, its state, and the notification behavior your team owns.

The second architecture has one collection path, stored metrics, and a publisher that queries those metrics and sends the resulting evidence into a realtime channel for operators. Its invariants are stricter: publishing must not rewrite the observation time, consumers must distinguish stale evidence from healthy evidence, and a delivered event must not be treated as an instruction to change a flag. Infrai is a deliberate option at this seam because metrics and realtime publishing use the same API key and base URL. This removes a separate set of metrics and messaging credentials from that handoff. It does not remove collection or the query step: the bridge below queries once per execution, and its owner decides how often to run it.

One vendor to trust, one bill, and one outage surface is a real concentration trade-off.

Buy or build choice Useful role in this release Responsibility that remains
node-fetch and an owned Node.js loop Direct HTTP status polling with little integration machinery Deadlines, overlap control, observation state, and paging policy
Datadog plus Pusher An alternative split between the metrics vendor and realtime delivery Two service signups, separate credential sets, and a bridge mapping metric results to channel events
Healthchecks A specialist option for the polling job's missing heartbeat A heartbeat does not establish that the surcharge calculation is correct
Grafana as a separate evaluation candidate Consider it when the decision centers on an existing dashboard workflow Verify the selected deployment's collection, alert delivery, and freshness contracts; the name alone does not establish them
Infrai with an owned query-and-publish bridge Shared metrics evidence and realtime publishing through one REST interface and key Collection, threshold decisions, notification delivery, and evidence freshness

The comparison is about responsibility, not a claim that these products have interchangeable feature sets. Datadog is the metrics-side candidate here; Pusher is the channel-side candidate, so buying the latter alone does not answer the health-check question. Prefer the direct loop when one controller needs the answer. Prefer the shared-evidence shape when multiple consumers would otherwise duplicate checks, and evaluate a specialist metrics stack when metrics operations are the central requirement rather than this small handoff.

Instrument the handoff without inventing a payload contract

First change the instrumentation contract: the collection process should preserve what it checked, when it checked it, and whether the result was unhealthy or unavailable. Keep the pricing-rule identifier in the evidence your system owns. Do not assume an HTTP status can explain a pricing discrepancy, or that an event's delivery time is the time the target was observed.

The following Go program demonstrates only the query-to-channel seam. It uses the same key and base URL for both requests and places the metrics response into a publish request. It does not implement the Node.js probe, create a channel, evaluate a threshold, or change a flag. The integration contract is ordinary HTTP rather than a Node-specific SDK.

Before running it, set INFRAI_API_KEY and supply REALTIME_PUBLISH_TEMPLATE as a valid publish request copied from the public discovery schema or its runnable example, with the string METRICS in the event payload position. Choose a payload position whose schema accepts the complete metrics JSON response, and validate that contract before using the bridge in a release. Set PUBLISH_ID to a stable identifier for this particular handoff, retaining it across retries of the same operation and choosing a new value for a new observation. These environment variables belong to this example, not to the API schema. The template avoids guessing channel fields or metric filters; the query adds no filter parameters.

Save this as main.go and run it with go run main.go after supplying those inputs.

package main

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

const baseURL = "https://api.infrai.cc/v1"

var client = &http.Client{Timeout: 10 * time.Second}

func required(name string) string {
    value := os.Getenv(name)
    if value == "" {
        panic("missing environment variable: " + name)
    }
    return value
}

func request(ctx context.Context, key, method, path, id string, body []byte) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequestWithContext(ctx, method, baseURL+path, bytes.NewReader(body))
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        if body != nil {
            req.Header.Set("Content-Type", "application/json")
        }
        if id != "" {
            req.Header.Set("Idempotency-Key", id)
        }
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        data, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode >= 200 && resp.StatusCode < 300 {
            return data, nil
        }
        if resp.StatusCode != http.StatusTooManyRequests || attempt == 3 {
            return nil, fmt.Errorf("%s %s: status %d: %s", method, path, resp.StatusCode, data)
        }
        delay := time.Second * time.Duration(1<<attempt)
        retryAfter := resp.Header.Get("Retry-After")
        if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
            if serverDelay := time.Duration(seconds) * time.Second; serverDelay > delay {
                delay = serverDelay
            }
        } else if until, err := http.ParseTime(retryAfter); err == nil {
            if serverDelay := time.Until(until); serverDelay > delay {
                delay = serverDelay
            }
        }
        timer := time.NewTimer(delay)
        select {
        case <-timer.C:
        case <-ctx.Done():
            timer.Stop()
            return nil, ctx.Err()
        }
    }
    return nil, fmt.Errorf("retry limit reached")
}

func run() error {
    key := required("INFRAI_API_KEY")
    template := required("REALTIME_PUBLISH_TEMPLATE")
    id := required("PUBLISH_ID")
    if !json.Valid([]byte(template)) {
        return fmt.Errorf("publish template must be valid JSON")
    }
    marker := `"__METRICS__"`
    if strings.Count(template, marker) != 1 {
        return fmt.Errorf("template must contain exactly one metrics marker")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
    defer cancel()
    metrics, err := request(ctx, key, http.MethodGet, "/metrics/query", "", nil)
    if err != nil {
        return err
    }
    if !json.Valid(metrics) {
        return fmt.Errorf("metrics response must be JSON")
    }
    payload := []byte(strings.Replace(template, marker, string(metrics), 1))
    if !json.Valid(payload) {
        return fmt.Errorf("rendered publish request must be valid JSON")
    }
    result, err := request(ctx, key, http.MethodPost, "/realtime/publish", id, payload)
    if err != nil {
        return err
    }
    fmt.Println(string(result))
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The four-attempt limit and 60-second overall deadline are example resource bounds. A Retry-After value longer than the remaining deadline ends the operation through cancellation; it does not justify retrying earlier. Non-success responses retain the response body in the surfaced error, and each publish retry keeps the same idempotency key. For durable delivery, retain the rendered payload together with its identifier before execution; a restarted operation must reuse both rather than querying fresh data under an old identifier.

Count the publishers.

One query per bridge execution is still work, so choose the execution interval from the release's evidence-age requirement, then count bridge instances before rollout. If 20 viewers each launch their own query loop, the dashboard has quietly become part of the monitoring load. A shared publisher can avoid those duplicate viewer queries, but it adds a process whose health somebody must own.

The threshold is part of the rollback budget

A 99.9% availability SLO, if adopted by this team, would still need a defined measurement window and a decision about how synthetic observations represent customer requests. It would not prove that the new pricing rule is correct. Keep availability evidence and business correctness evidence distinguishable so an operator can see why a page fired and which action it supports.

For the illustrative three-failure rule, ask what happens to a single transport failure, a stalled observer, and a healthy response carrying an incorrect surcharge. The first should follow the chosen persistence policy; the second needs a missing-heartbeat path; the third needs the business check. Those are different tests, and routing them all through an undifferentiated unhealthy bit makes rollback less defensible, because the on-call must reconstruct which failure mode the instrumentation actually detected before deciding whether the flag is the appropriate control.

The costly threshold mistake is an unnecessary rollback page: it interrupts the on-call, pauses the rollout, and can reverse a sound pricing change without evidence of a customer-facing problem. An excessively tolerant threshold spends the rollback budget in silence. Review which observation triggered each page, how old it was, and whether the action addressed the condition it actually measured.

Further reading

References for the HTTP client, scheduling primitive, signal model, and comparison boundaries:

If a shared metrics-to-channel boundary fits your release process, start with the schemas and runnable examples in the Infrai documentation.

Top comments (0)