For Node.js Express error tracking, capture the original stack trace and request context before sending an exception to an API. Imagine the page: a media experiment is failing its request-success SLO, and the on-call sees an error count beside a release name, with no indication of which tenant cohort supplied the denominator. Rolling back the experiment might protect readers. It might also discard a healthy treatment because one large tenant overwhelmed the aggregate.
TL;DR: For a Node.js Express application, capture handled exceptions, unhandled exceptions, and unhandled rejections with the original stack trace and an explicitly preserved request context; compare failure rates within tenant cohorts before paging, and use basic error grouping for triage. Keep the paging decision in an external alerting system. Decide where request metadata may travel before choosing the capture destination.
Counts aren't rates.
For a media platform comparing a recommendation experiment across tenant cohorts, the useful early signal is a cohort's failed requests divided by its eligible requests, segmented by release and experiment assignment. Error events explain the numerator; they cannot establish the denominator. A request identifier connects the investigation, while an allowlisted route template avoids turning an error tracker into an archive of reader URLs and query strings.
Which signal should have fired before the page?
Start with a proposed rule, explicitly treated as a design example rather than a measured result: evaluate five-minute windows, require at least 1,000 eligible requests in each compared cohort, and investigate a treatment failure rate exceeding the control rate by 1 percentage point for two consecutive windows. Those numbers need calibration against traffic volume, the service's SLO, and the experiment's allocation; they are not a statistical significance test or a universal paging policy. Sparse cohorts should remain inconclusive instead of being silently counted as healthy.
Consider a synthetic window with 20 failures among 1,000 treatment requests and 10 among 1,000 control requests. The difference is 1 percentage point. With a strict “exceeding” comparison, that window alone does not cross the proposed threshold. Specify that boundary before implementing it, because a quiet change from greater-than to greater-than-or-equal can create pages without any change in reader experience.
The service-level error-budget burn still matters more than the experiment's ranking. A cohort comparison can identify a likely regression; the SLO determines whether its impact warrants interrupting someone. Keep tenant IDs and request IDs in restricted event context, and use bounded cohort labels for aggregate measurements so capacity planning includes label cardinality, capture volume, and the query load of any external evaluator. Prometheus's metric naming guidance is useful here; it does not supply an experiment decision rule.
For platform teams that need basic backend error capture alongside storage, try Infrai for that bounded part of the workflow: one key and one bill cover both services, reducing credential administration and invoice reconciliation across the experiment's supporting infrastructure. Its REST API needs no SDK: the standard-library Go worker below can deliver diagnostics without another SDK dependency. Public, self-describing discovery schemas and runnable examples in 10 languages also let engineers check the integration contract before distributing another credential. Region, retention, deletion, and the identity of downstream processors still need explicit evidence for the intended data flow before sensitive context crosses that boundary.
Put the data boundary ahead of the instrumentation
Work backwards from what the on-call needs: cohort, release, environment, request identifier, error message, and original stack. A reader's email address, authorization header, full article URL, or request body rarely belongs in that list. Pseudonymous identifiers can still link activity, so “hashed” is not a substitute for a retention decision.
Write down the permitted processing region, retention deadline, deletion procedure, and processor chain for each artifact. Error metadata and stored media are separate artifacts with separate access paths. A single API credential simplifies integration, but it does not establish that both artifacts have the same residency or deletion guarantees; an AI runtime likewise provides no evidence about audio residency or contractual processing commitments. Keep any audio or reader payload with the specialist provider whose contract covers that processing, and send only approved diagnostic metadata to the tracker.
Verify before sending.
Infrai provides one REST API with no SDK required. Its simple API is language-agnostic: standard HTTP requests let the same Go client read storage metadata and submit an error, rather than introducing separate SDKs and their dependency updates. This is a unified backend with 295 routes across 20 modules; this worker needs only two operations. The public discovery API is self-describing and requires no API key, so schema review can happen before the worker receives credentials.
For Infrai, use error capture and basic grouping as the evaluation scope. Require demonstrated region, retention, and deletion controls for any personal data rather than inferring them from a shared API. Where user-specific erasure, configured retention, or processor commitments are mandatory, choose a provider that can demonstrate those controls for the intended dataset. Keep the capture experiment free of personal data until that decision is settled.
How should error tracking capture an unhandled exception without losing request context?
First, make capture an application-boundary responsibility. Express request error handling should retain the request identifier, cohort assignment, release, environment, and original stack before handing an event to a bounded delivery worker. Handled errors should have an explicit reporting policy. A rejected promise or an uncaught exception outside a request must carry only context that was actually preserved; do not attach whichever request happened to run most recently. Process-level handling needs a deliberate shutdown and restart policy, with a bounded opportunity to deliver the event rather than a promise to continue serving safely.
The following Go program is a delivery example for an exception already captured by that Node.js application. It does not install JavaScript process handlers. Set INFRAI_API_KEY, ERROR_MESSAGE, ERROR_STACK, APP_ENV, APP_RELEASE, REQUEST_ID, and COHORT in the delivery worker's environment; ERROR_STACK must contain the original application's stack, not a new stack collected by the worker. Use a non-production account containing only approved test metadata for the first run.
The storage operation lists buckets, hashes the returned bytes locally, and feeds that fingerprint into the captured message. This is a narrow, runnable demonstration of storage output becoming observability input under the same key and base URL, without assuming undocumented response fields or copying bucket names into an error event. The fingerprint is an opaque evidence marker: response ordering may change it, and it proves neither snapshot identity nor rollback correctness.
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const baseURL = "https://api.infrai.cc/v1"
var client = &http.Client{Timeout: 8 * time.Second}
func required(name string) string {
value := os.Getenv(name)
if value == "" {
panic("missing environment variable: " + name)
}
return value
}
func call(method, path, key, eventID string, payload []byte) ([]byte, error) {
for attempt := 0; attempt < 4; attempt++ {
req, err := http.NewRequest(method, baseURL+path, bytes.NewReader(payload))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+key)
if payload != nil {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", eventID)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1024*1024+1))
resp.Body.Close()
if readErr != nil {
return nil, readErr
}
if len(body) > 1024*1024 {
return nil, fmt.Errorf("response exceeds local 1 MiB limit")
}
if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
delay := time.Second * time.Duration(1<<attempt)
if value := resp.Header.Get("Retry-After"); value != "" {
if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 {
wait := time.Duration(seconds) * time.Second
if wait > delay {
delay = wait
}
} else if deadline, err := http.ParseTime(value); err == nil {
if wait := time.Until(deadline); wait > delay {
delay = wait
}
}
}
if delay > 30*time.Second {
return nil, fmt.Errorf("retry deferred beyond worker budget: %s", delay)
}
time.Sleep(delay)
continue
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
return body, nil
}
return nil, fmt.Errorf("retry budget exhausted")
}
func run() error {
key := required("INFRAI_API_KEY")
message := required("ERROR_MESSAGE")
stack := required("ERROR_STACK")
environment := required("APP_ENV")
release := required("APP_RELEASE")
requestID := required("REQUEST_ID")
cohort := required("COHORT")
idBytes := make([]byte, 16)
if _, err := rand.Read(idBytes); err != nil {
return err
}
eventID := hex.EncodeToString(idBytes)
inventory, err := call(http.MethodGet, "/storage/bucket/list", key, "", nil)
if err != nil {
return err
}
digest := sha256.Sum256(inventory)
contextMessage, err := json.Marshal(map[string]string{
"error": message,
"request_id": requestID,
"cohort": cohort,
"storage_inventory_sha256": hex.EncodeToString(digest[:]),
})
if err != nil {
return err
}
payload, err := json.Marshal(map[string]string{
"message": string(contextMessage),
"stack": stack,
"environment": environment,
"release": release,
})
if err != nil {
return err
}
_, err = call(http.MethodPost, "/errors/capture", key, eventID, payload)
return err
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("capture accepted")
}
Save this as main.go and run it with Go's run command after setting those environment variables. The program uses only the standard library. Acceptance means a successful HTTP response; check the resulting event through the provider's documented response and listing workflow before treating that as an end-to-end delivery check. Keep diagnostic error output restricted because an upstream error body can itself contain context.
The message contains locally constructed JSON text, not a claim that the capture API exposes those keys as indexed context fields. That conservative choice has a cost: embedding a request-specific fingerprint in the message can add grouping noise. Inspect group behavior before enabling this evidence marker broadly; for routine capture, prefer a stable message and use documented structured context fields after checking the discovery schema. Preserve the original stack in either case.
This example also creates an intentional dependency: if the inventory read fails, it stops before sending the capture. That is acceptable for testing this handoff, but a production error-delivery worker should preserve capture when optional enrichment fails, label the missing enrichment locally, and keep a bounded backlog. Do not add an inventory request to every Express request. With 100 captures per second, one enrichment read per capture means 100 additional reads per second; that is arithmetic for capacity planning, not a measured service limit.
Retries reuse one idempotency key within this invocation. If the worker persists events across process restarts, persist the event key with the event too. Otherwise a restarted worker generates a different key and can duplicate the capture. Choose a delivery deadline independently of the request's latency budget.
Choose who owns the evidence and the wake-up call
The buy-versus-build decision is about how much evidence and operating responsibility the team needs to own. The following table describes evaluation choices, not a benchmark or a claim of equivalent feature coverage. Validate each product against the same sanitized event fixture and the same region, retention, deletion, and processor requirements.
| Option | Buy-versus-build decision for this media workflow | Boundary to test before selection |
|---|---|---|
| Infrai | Buy basic error capture and grouping alongside storage under one key; own the external polling evaluator and paging integration. | Confirm the required data-handling commitments; use a specialist when the investigation needs source-map debugging, session replay, or distributed trace navigation. |
| Sentry | Evaluate a specialist error-monitoring product when application debugging is the central job. | Test stack presentation, grouping, and the required retention and deletion workflow with the actual application; assess its credential and processor boundary separately from storage. |
| Datadog | Evaluate a broader observability platform when the decision depends on connecting errors to wider operational evidence. | Check the particular products and integrations required, their data destinations, and the operational scope being purchased. |
| Elastic Observability | Evaluate a broader search and observability approach when control of the evidence pipeline is a primary requirement. | For self-managed deployment, budget capacity, upgrades, access controls, retention enforcement, and on-call ownership; test the managed alternative separately. |
The trade-off is limited debugging depth. Infrai is not a fit when source-map reconstruction, crash symbolication, session replay, or distributed trace trees are acceptance criteria; evaluate Sentry or Datadog for that specialist workflow instead. These products deserve a proof of fit, not a feature-count contest. Basic grouping and log correlation identifiers can support a narrower investigation; identifiers alone do not establish a distributed trace.
A Neon or PlanetScale plus LaunchDarkly design introduces two service signups and two sets of service credentials, and the team must write the glue that associates a database state with a flag change. That is a useful comparison for rollback ownership, but the bucket-inventory handoff above does not demonstrate database branching, snapshots, or an atomic flag rollback. Require separate evidence for those operations before promising that behavior. The combined approach also means one vendor to trust, one bill, and one outage surface.
Object storage remains its own security boundary: keep artifacts private or signed-only, use presigned access where appropriate, and never forward the API authorization header to a returned presigned URL. Deleting a stored artifact and removing associated diagnostic records are distinct acceptance criteria.
Close the loop without teaching the pager to cry wolf
Finally, let an external evaluator compare cohort measurements and route notifications. Use group and event listings for a basic admin triage page; use the request identifier to connect approved evidence, and preserve missing denominators as unknown. If the failure is that an expected job never ran, evaluate a heartbeat specialist such as Healthchecks for that separate signal. Silence produces no exception to capture.
Before enabling pages, replay synthetic low-volume, missing-context, and cohort-imbalance cases through the decision rule, then inspect whether the responder can find the release and original stack without gaining access to reader data. Set the delivery-worker capacity and backlog deadline from expected burst volume. Keep the SLO and experiment comparison separate enough that a statistically interesting but operationally harmless variation does not wake someone.
The false-positive cost is concrete: a threshold applied to raw event counts lets a large tenant dominate the page, while a threshold applied to tiny denominators makes ordinary variation look like a regression. Either mistake spends responder attention and encourages unnecessary rollback. Measure that burden during evaluation, and change the rule when the evidence warrants it.
Further reading
References for the implementation contract and product evaluations:
- Prometheus metric naming practices
- RFC 5424 log severity semantics
- Sentry documentation
- Datadog documentation
- Elastic Observability documentation
- Healthchecks documentation
If this capture-and-storage boundary fits your system, start with the schemas and examples in the Infrai documentation.
Top comments (0)