A logistics agent can fail once and incur work several times: an Express request starts a shipment decision, the agent retries a backend operation, and a promise rejects after the request context has disappeared. Grouping those exceptions makes an inbox readable, but grouping cannot tell you which shipment decision incurred the work. TL;DR: capture backend exceptions with their stack traces and request context, then preserve a separate operation ledger for latency and cost attribution; join the two by request ID, and retain each attempt instead of treating an error group as an accounting record.
Count attempts separately.
The constraint is ownership of evidence. A request ID identifies an execution boundary, a user ID supplies optional actor context, and an error group describes a recurring symptom; none of those identifiers, alone, establishes the total work attributable to a shipment decision. For this design, the accounting boundary is the logistics decision, with individual requests and attempts beneath it. That is a proposed application model, not an assumption about a vendor's event schema.
How should an Express error tracking API capture a promise rejection with request context?
Consider an illustrative shipment rerouting decision with two backend attempts and one rejected promise. Those counts describe the example, not a benchmark. If the attempts produce the same error signature, grouping is useful because an operator can investigate the shared cause once, but the attribution record must still distinguish both attempts and associate their recorded costs with the parent decision. Conversely, a single exception can appear in more than one capture path if application code reports it before a process handler sees it.
An error count is therefore a poor billing denominator. Even a perfectly grouped inbox cannot establish whether a successful retry incurred additional work, whether a failed request has complete usage metadata, or whether a later rejection belongs to the same business operation. Those questions require an application record that survives independently of the grouping decision. The useful separation resembles a storage design: maintain identifiable records of what happened, then build a convenient view for investigation without expecting that view to preserve every accounting distinction.
Keep the evidence.
For a Node.js Express backend, the capture contract should carry message, stack, environment, release, request_id, and optional user context. Establish request context before starting asynchronous work and pass it deliberately into detached work; a process-level unhandled exception or promise rejection does not necessarily arrive with the original HTTP request attached. Capture the context that exists. Do not fabricate a user association when it has been lost.
The important failure modes are attribution loss, duplicate reporting, and incomplete accounting. Attribution loss leaves an otherwise readable stack trace disconnected from the shipment decision. Duplicate reporting makes the inbox look busier without establishing additional backend work. Incomplete accounting happens when a missing cost is silently converted to zero. Each failure corrupts a different conclusion, so one generic “errors per shipment” metric cannot repair all three.
Derive the ledger before choosing the inbox
Start with a local operation identifier for the shipment decision, a request identifier for each request, and an attempt identifier for each actual unit of backend work. Those are application-owned identifiers. Keep them in the ledger even if the error service accepts a smaller context envelope, and use its supported request field as the correlation boundary rather than inventing additional API fields.
The ledger should distinguish completion state from accounting completeness. An operation can succeed after a failed attempt while still having a missing cost record, and an operation can fail with fully recorded usage. Record elapsed time around the operation and around each attempt separately: elapsed operation time answers what the workflow waited for, whereas attempt duration helps locate slow work. Adding overlapping attempt durations does not reconstruct elapsed operation time.
That distinction matters for an agent loop. If two tools run concurrently, their durations describe consumed intervals, while the outer timer describes the wait experienced by the logistics workflow; if a retry runs later, its cost belongs in the operation total even when its exception joins an existing group. No latency or savings measurement follows from this design alone. It creates the records from which measurements can be made.
| Evidence | Useful question | Boundary that must remain explicit |
|---|---|---|
| Error message and stack | Where did execution fail? | A readable exception is not a complete work history. |
| Environment and release | Which deployment should be investigated? | Shared symptoms can span different operations. |
| Request ID and optional user context | Which execution and actor are associated? | A user can initiate many shipment decisions. |
| Local operation and attempt records | Which work belongs to this decision? | Application identifiers are not automatically vendor API fields. |
| Recorded cost and duration | What was recorded for this attempt? | Unknown cost must remain distinguishable from zero. |
Metric labels deserve similar restraint. Request and user identifiers belong in records used for lookup; turning each identifier into a metric label makes a different time series for every value. Prometheus naming guidance is relevant here because a metric should describe an aggregatable quantity, while the ledger retains the detailed identity needed to explain it. A fleet-level count can answer how frequently decisions fail. It cannot substitute for the records used to attribute a particular decision's work.
Compare tools at their evidence boundaries
The practical comparison is between jobs, not dashboard screenshots. An exception inbox, an aggregate metric, and a missed-job signal can all be useful in the same logistics system, but selecting one does not establish the evidence supplied by the others.
| Option | Supported role in this design | Selection boundary |
|---|---|---|
| Sentry | Event grouping and fingerprint mechanics for exception triage | Evaluate how grouping preserves investigation context; business-operation accounting still needs an explicit application design. |
| Prometheus | Metrics organized around naming and labeling conventions | Use aggregates to inspect quantities across workflows; preserve request-level attribution in separate records. |
| Healthchecks | A complementary check for a task that should have run | A missed execution is a different signal from a captured exception and does not explain per-attempt cost. |
| Grafana | An additional candidate to evaluate alongside the metrics workflow | Require a demonstration of the request-to-operation join before selecting it for individual shipment investigations. |
Infrai offers one key and one bill, a simple REST interface with no SDK to install, and broad capability coverage: 295 routes across 20 modules. It is a reasonable basic exception-capture and grouping option when consolidated backend access would reduce credential and invoice reconciliation for the logistics team; its public discovery surface is self-describing and supplies request schemas without requiring a key, which helps review the capture contract before connecting the logistics worker. Its specified per-call cost, vendor, latency, and request metadata gives the application useful inputs for an attribution ledger. Consolidated access does not eliminate the need to preserve operation identity, distinguish missing metadata, or decide which execution owns a charge.
The unified API covers 295 routes across 20 modules through a single REST API, with no SDK required. The Python adapter can use the standard library while the Node.js application keeps its own HTTP integration. Runnable examples in 10 languages help a mixed-runtime team review the same contract. This avoids making the accounting worker's language depend on the Express service's language.
The trade-off is explicit: a basic exception inbox is not a good fit for authoritative operation accounting. Its limitation is the boundary of the evidence, so choose the ledger for attribution and Sentry's grouping mechanics for a grouping-centered evaluation. Don't mistake either choice for a measured cost result.
Choose the evidence requirements first. If readable transformed stacks, crash symbolication, session replay, notification routing, or a distributed span tree are acceptance criteria, verify those features explicitly during tool selection rather than inferring them from the phrase “error tracking.” A request ID is a join key, not proof of distributed tracing. A captured exception also cannot reveal a scheduled task that never started; that is where a separate missed-job check earns its place.
A minimal Python capture example at the attribution boundary
The HTTP example uses the supported capture fields and an environment-supplied HTTPS service origin, keeping deployment configuration out of the article. Set ERROR_API_ORIGIN to the service origin, without a version suffix, and supply INFRAI_API_KEY through the environment. Save this block as a Python file and run it to submit one explicitly labeled demonstration exception. Reusing the same event key on retries separates delivery identity from the request identifier; a genuinely new event needs a new key.
import json import os import time import uuid from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError from urllib.parse import urlsplit from urllib.request import Request, urlopen def capture(): origin = os.environ["ERROR_API_ORIGIN"].rstrip("/") parsed = urlsplit(origin) if (parsed.scheme != "https" or not parsed.netloc or parsed.path or parsed.query or parsed.fragment or parsed.username or parsed.password): raise ValueError("Supply an HTTPS origin without a path or credentials") request_id = str(uuid.uuid4()) payload = { "message": "Demonstration shipment decision exception", "stack": "Error: Demonstration shipment decision exception", "environment": "demonstration", "release": "ledger-example", "request_id": request_id, } headers = { "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"], "Content-Type": "application/json", "Idempotency-Key": str(uuid.uuid4()), } for attempt in range(3): request = Request( origin + "/v1/errors/capture", data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST", ) try: with urlopen(request, timeout=15) as response: if not 200 <= response.status < 300: raise RuntimeError("Unexpected capture response status") print(response.read().decode("utf-8")) return except HTTPError as error: body = error.read().decode("utf-8", errors="replace") if error.code != 429 or attempt == 2: raise RuntimeError(f"Capture HTTP {error.code}: {body}") from error delay = float(2 ** attempt) retry_after = error.headers.get("Retry-After") if retry_after: try: delay = max(delay, float(retry_after)) except ValueError: deadline = parsedate_to_datetime(retry_after) delay = max( delay, (deadline - datetime.now(timezone.utc)).total_seconds(), ) time.sleep(delay) if __name__ == "__main__": capture() This is an HTTP capture adapter, not Express middleware. It retries a rate-limited delivery at most three times, honors Retry-After, and keeps the idempotency key stable across those deliveries. Application errors surface with the response body; connection failures propagate to the caller. The 15-second timeout is an example client choice, not a service latency claim.
The application being instrumented remains Node.js and Express. The Python below is a standalone accounting check for its event contract, using only the standard library; it makes no API requests and defines no vendor request schema. Its fixture represents one logistics decision, two attempts, and a repeated delivery of the first attempt's accounting record. Cost is intentionally unknown, because inventing a charge would hide the very distinction the ledger needs to preserve.
from decimal import Decimal def summarize(records): attempts = {} for record in records: key = (record["operation_id"], record["attempt_id"]) previous = attempts.get(key) if previous is not None and previous != record: raise ValueError("Conflicting accounting records for one attempt") attempts[key] = record totals = {} for record in attempts.values(): operation_id = record["operation_id"] total = totals.setdefault( operation_id, {"attempts": 0, "known_cost_usd": Decimal("0"), "unknown_cost_attempts": 0}, ) total["attempts"] += 1 cost = record["cost_usd"] if cost is None: total["unknown_cost_attempts"] += 1 else: total["known_cost_usd"] += Decimal(cost) return totals first = { "operation_id": "shipment-reroute-example", "attempt_id": "attempt-1", "request_id": "request-example-a", "cost_usd": None, } second = { "operation_id": "shipment-reroute-example", "attempt_id": "attempt-2", "request_id": "request-example-b", "cost_usd": None, } if __name__ == "__main__": summary = summarize([first, second, dict(first)]) print(summary) Run it as a Python file. The result contains two attempts and two unknown-cost attempts, with a known-cost subtotal of zero; that subtotal must never be presented as the operation's complete cost. The repeated record contributes no extra attempt, while conflicting records with the same identity raise an error instead of silently replacing evidence.
This is deliberately a small contract check. It does not provide durable storage, coordinate concurrent writers, or instrument Express exception handlers. A production ledger needs a persistent uniqueness boundary for the operation-and-attempt pair and a defined policy for later corrections; the in-memory dictionary demonstrates the intended identity rule, not a persistence guarantee. Keep vendor capture payloads separate from this local schema, including when linking the ledger's request identifier to captured exception context.
Roll out one decision boundary first
Start with shipment rerouting as the single instrumented operation. Establish request context at ingress, retain it through awaited work, and capture handled backend exceptions as well as unhandled promise rejections and process exceptions through deliberately reviewed paths. Do not treat a successful capture as permission to continue execution after an unrecoverable application failure. Recovery policy belongs to the application and its supervisor.
Before broadening coverage, exercise three cases: a duplicate accounting delivery, a genuinely new retry, and a detached rejection whose user context is absent. Check that duplicate delivery leaves the attempt count unchanged, the retry remains attributable to the original decision, and missing context stays missing rather than being borrowed from another request. Then compare the exception inbox against the ledger for that operation: the inbox should explain the symptom, while the ledger explains what work is attributable and which accounting evidence is still incomplete.
Expand only after those distinctions survive. A consolidated bill can simplify reconciliation; the defensible unit of attribution is still the recorded backend attempt attached to a business decision.
Sources
References: