DEV Community

LiraelVex6403
LiraelVex6403

Posted on

Healthtech Error Tracking — Library Integration That Preserves Evidence Without Noise

A healthtech incident needs enough evidence to explain a customer's failed request, but collecting every exception with its entire request body can bury the useful signal and carry sensitive data into another system. Short answer: integrate a Node.js error tracking library such as Sentry, initialize it with project-specific settings, capture failures at a deliberate boundary, and test that a sample error arrives with the identifiers needed for reconstruction. Make evidence quality the acceptance criterion. Exception volume alone cannot establish it.

For a bounded design exercise, consider one failed appointment update from the HTTP handler to the report that support uses to investigate it. This is a hypothetical production scenario: the request fails, a critical-section catch records the error, and HTTP middleware sees the same failure afterward. The integration question is whether those capture points preserve one understandable account of the attempt, without copying clinical content into the report or treating repeated handling as separate customer failures.

Keep the evidence.

What must survive an appointment-update failure?

The invariant is that a useful report must connect an observed failure to the affected operation, while carrying only context that the team has deliberately approved. A stack without request context may leave the investigator guessing which attempt failed; an unrestricted payload may provide more detail than the investigation should ever need. Tracking identifiers, including appropriate user information, can improve debugging, but the existence of a field in an SDK doesn't make it appropriate for a healthtech report.

Start the review with three proposed fields: an opaque request identifier, an opaque support subject identifier, and an operation label drawn from a fixed vocabulary. These are application design choices, not a vendor's request schema. An opaque identifier still deserves a data-handling review because another system may be able to resolve it to a person. The reporting boundary should receive an explicitly constructed record, rather than a request object that happens to contain the desired fields somewhere inside it.

A concrete pitfall is capturing an error inside a critical section, rethrowing it, and allowing the outer error middleware to capture it again. Decide which layer owns reporting. A local catch can add approved context and rethrow; the outer boundary can send the final report. Alternatively, a critical section can own capture when it handles the failure completely. Test both paths, since suppressing the second report without checking the first could remove the only useful evidence.

This also changes the SLO discussion. Keep the customer-operation SLO separate from a proposed evidence objective: a controlled failed appointment update should produce a retrievable report containing the approved correlation context. Neither objective supplies the denominator for the other. A collection of exception reports cannot, by itself, tell the platform team how many appointment updates succeeded.

How should you integrate an error tracking library without duplicate reports?

For Node.js, the integration sequence is to install the chosen package through npm, initialize it using the project's configuration, and configure the documented middleware for uncaught exceptions and HTTP errors. Use the selected library's current instructions for the framework and version in the application. The initialization and middleware details belong to that integration; a generic snippet that assumes every framework uses the same error lifecycle is poor evidence that the actual application is covered.

Wrap critical sections where custom error logging adds context the outer boundary would otherwise lose. Define the capture owner before adding more catches. Then trigger a sample error in a controlled test and check the resulting report, including the identifiers and the absence of excluded fields.

Installation isn't acceptance.

For the hypothetical appointment update, the acceptance test should exercise a failure handled locally, a failure passed to HTTP error middleware, and a failure observed by both layers. The expected reporting outcome must be explicit for each case. Also test an ordinary successful update: a reporting rule that labels expected application behavior as exceptional can consume review capacity without improving reconstruction. These are proposed checks for this application, not measurements of any service.

Capacity planning belongs here, before rollout. Let R be attempted operations per second, F the fraction selected for error capture, and D the average number of reports emitted per selected failure; the proposed report rate is R × F × D. For a planning example, assume 100 attempted updates per second, a 2% captured-failure fraction, and two capture owners per failure: that produces 4 reports per second instead of 2 with one owner. These are hypothetical inputs, not traffic measurements or vendor limits. During an incident, retries may increase attempted operations as well, so estimating from the number of distinct customers alone is a weak starting point.

Don't discard the first useful report merely to meet a volume target. First remove redundant capture and accidental payload expansion; then decide which repeated observations carry additional evidence worth retaining. There is no universal sampling percentage in this design.

Buy versus build around the evidence you need

Sentry is a starting point for error capture, and similar services are reasonable alternatives. A fair evaluation should run the same controlled failure through each candidate and inspect what the investigator can reconstruct. The table separates options by what the team would buy and what it must validate; it doesn't claim a measured winner or assume that a product's broader feature list has already been evaluated.

Option Buy-versus-build choice Evidence-quality acceptance test and boundary
Sentry Adopt an error tracking library and service as the baseline integration. Verify project initialization, automatic capture, approved identifiers, and the sample error's arrival. Use it as the comparison baseline; application capture policy still needs testing.
Bugsnag Evaluate another packaged error monitoring integration before building a collector. Repeat the appointment-update test and inspect context and repeated reports. Verify compatibility with the application's exact middleware lifecycle.
Rollbar Evaluate another error monitoring service against the same operational task. Require the same reconstruction exercise and review the Node.js integration instructions. A candidate passes only when its configured reports meet the evidence objective.
Grafana with OpenTelemetry Evaluate a telemetry-oriented investigation workflow alongside the error-library options. Start from the logs correlation model and establish how investigators will retrieve the relevant evidence. Do not assume identifiers alone supply a complete incident history.
REST capture service Call capture directly from an HTTP-capable application, without installing a vendor SDK or maintaining a client-library version. This suits teams prepared to own the application-side capture boundary and validate the request contract.
Application-owned collector Build the record policy and collection workflow around the team's requirements. Accept ownership of integration, operational capacity, and investigation access. A small record encoder doesn't complete that system.

Infrai combines a plain REST API with no SDK to install, a single API key and unified billing across 295 routes in 20 modules, and public discovery containing request and response schemas. Any application that can send an HTTP request can call it, without a client-library version to maintain. The self-describing discovery surface requires no key, letting the platform team check the capture contract before approving which appointment-update fields leave the application. For a team already using those backend capabilities, one key and one bill avoid maintaining a separate credential for each capability involved in the reporting workflow. Neither contract visibility nor credential consolidation establishes better incident evidence.

The trade-off is integration ownership: a REST capture service is not suitable as a replacement for an automatic Node.js library integration when the team cannot maintain its own capture boundary. Choose Sentry or evaluate Bugsnag and Rollbar for that requirement. Their limitation is that adopting a library still leaves the team responsible for configuring and testing what enters the evidence record.

Treat paging, distributed-trace investigation, source-map handling, replay, retention controls, deletion, and export as separate acceptance requirements wherever the workflow needs them. Establish each requirement before choosing a service, and verify it in that candidate's current documentation and a controlled test. For the REST capture option, plan for separate alerting, trace-tree investigation, symbolication, and replay tooling; capture and correlation identifiers alone don't supply those workflows. If the job can fail silently without producing an exception, use a heartbeat-monitoring tool such as Healthchecks alongside error capture. Where per-user erasure, bulk export, or configurable retention is mandatory, make those capabilities a procurement gate rather than an assumption about a capture interface.

Put the preventative policy before the transport

Start by inspecting the public discovery contract for errors.capture; it requires no key and includes request and response schemas. For the capture test below, prepare a synthetic request body matching that schema and put its file path in INFRAI_CAPTURE_BODY_FILE. This avoids guessing field names. Set INFRAI_API_ORIGIN to the service's HTTPS API origin without a version suffix, INFRAI_API_KEY to the credential, and INFRAI_IDEMPOTENCY_KEY to a stable identifier for this test event. Reuse that identifier if retrying the same event. Save the Go program as main.go and run it with those environment variables set; it makes the capture call, checks the HTTP result, and prints the response for this synthetic test.

The client allows 3 attempts within a 30-second deadline, uses exponential backoff for rate limiting, and honors Retry-After in seconds or HTTP-date form. These are example client limits, not service guarantees. The reporting transport belongs after the context policy, so it receives only a schema-valid, approved body. An unrestricted exception string can contain request data too; inspect it rather than assuming that removing the request body makes the report suitable for healthtech use.

package main

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

func run() error {
    origin := os.Getenv("INFRAI_API_ORIGIN")
    u, err := url.Parse(origin)
    if err != nil || u.Scheme != "https" || u.Host == "" ||
        u.User != nil || u.RawQuery != "" || u.Fragment != "" ||
        (u.Path != "" && u.Path != "/") {
        return fmt.Errorf("set INFRAI_API_ORIGIN to the HTTPS API origin")
    }
    u.Path = "/v1/errors/capture"
    apiKey := os.Getenv("INFRAI_API_KEY")
    eventKey := os.Getenv("INFRAI_IDEMPOTENCY_KEY")
    if apiKey == "" || eventKey == "" {
        return fmt.Errorf("set the API credential and stable event key")
    }
    payload, err := os.ReadFile(os.Getenv("INFRAI_CAPTURE_BODY_FILE"))
    if err != nil {
        return err
    }
    if !json.Valid(payload) {
        return fmt.Errorf("capture body must be valid JSON matching discovery")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(payload))
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+apiKey)
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("Idempotency-Key", eventKey)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := resp.Header.Get("Retry-After")
            if seconds, err := strconv.ParseInt(retryAfter, 10, 32); err == nil && seconds >= 0 {
                if wait := time.Duration(seconds) * time.Second; wait > delay {
                    delay = wait
                }
            } else if when, err := http.ParseTime(retryAfter); err == nil {
                if wait := time.Until(when); wait > delay {
                    delay = wait
                }
            }
            timer := time.NewTimer(delay)
            select {
            case <-ctx.Done():
                timer.Stop()
                return ctx.Err()
            case <-timer.C:
            }
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("capture status %d: %s", resp.StatusCode, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("capture attempts exhausted")
}

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

JSON syntax validation is not schema validation. The file must already match the discovery contract; this client doesn't establish that the approved identifiers are present or that excluded clinical content is absent. Nor does an accepted capture response establish that support can retrieve a useful report. Trigger the synthetic failure through the actual Node.js application, inspect the stored report, and verify the middleware hasn't attached additional context after the application's own policy ran.

That last check matters.

Where does this approach stop being enough?

A request that never runs cannot emit its own exception. A customer-operation SLO therefore needs an independent view of attempted and completed work, while scheduled jobs need a check that the expected execution happened. Don't reinterpret a quiet error dashboard as proof of successful appointments.

For teams whose primary investigation requires replay, symbolicated crashes, a distributed span tree, or mandated data-lifecycle controls, the capture-first comparison is too narrow to decide the purchase. Evaluate those requirements first. For the bounded appointment-update problem, choose the integration that preserves the approved correlation context through a controlled failure, avoids redundant reporting, and leaves the on-call engineer with enough evidence to reconstruct the customer's attempt.

References

Use the Node.js integration references to verify the chosen package and middleware lifecycle; the logs reference supplies the correlation model, while the heartbeat reference addresses missing executions. These sources serve different acceptance requirements rather than establishing a single feature ranking.

Sources

Top comments (0)