The Root-Cause Ambiguity in Distributed Traces
When distributed systems emit trace data, unstructured error handling collapses nuanced system failures into a generic 500 error or uncaught exception. When an automated triage engine or an on-call engineer processes an incoming stream of spans, separating a deterministic code defect from a downstream cloud timeout or third-party rate limit often requires manual log correlation.
OpenTelemetry provides standard semantic conventions, but default instrumentation rarely captures enough context to classify failures without ambiguity. By structuring OpenTelemetry OTLP/HTTP JSON spans with precise error statuses, exceptions, and semantic attributes, telemetry pipelines can differentiate between application code bugs, infrastructure degradation, and external vendor outages.
Anatomy of an OTLP/HTTP JSON Span
OpenTelemetry traces transmitted via HTTP typically target standard ingestion endpoints like /v1/traces or custom ingestion endpoints such as AutoSRE's /v1/ingest/otlp/v1/traces. The payloads use the standard OTLP/HTTP JSON schema, wrapping resource spans, scope spans, and individual spans.
To ensure an error is properly actionable, the span must capture:
- Span Status: Explicitly set to
STATUS_CODE_ERROR(code 2) with a descriptive message. - Standardized Exception Events: Structured
exceptionevents carryingexception.type,exception.message, andexception.stacktrace. - Infrastructure Context: Attributes defining the executing container, orchestrator, or host.
- Downstream Semantics: HTTP, RPC, or database client attributes that record external vendor touchpoints.
Here is a properly structured OTLP/HTTP JSON payload distinguishing an external vendor failure from an internal code bug:
{
"resourceSpans": [
{
"resource": {
"attributes": [
{ "key": "service.name", "value": { "stringValue": "billing-api" } },
{ "key": "service.version", "value": { "stringValue": "2.4.1" } },
{ "key": "deployment.environment", "value": { "stringValue": "production" } },
{ "key": "host.id", "value": { "stringValue": "node-pool-c2-4" } }
]
},
"scopeSpans": [
{
"scope": { "name": "@opentelemetry/instrumentation-http", "version": "0.45.0" },
"spans": [
{
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"spanId": "00f067aa0ba902b7",
"parentSpanId": "5fb397be34d23b0f",
"name": "POST /v1/charges",
"kind": 3,
"startTimeUnixNano": "1711200000000000000",
"endTimeUnixNano": "1711200001500000000",
"attributes": [
{ "key": "http.request.method", "value": { "stringValue": "POST" } },
{ "key": "server.address", "value": { "stringValue": "api.stripe.com" } },
{ "key": "http.response.status_code", "value": { "intValue": 503 } },
{ "key": "peer.service", "value": { "stringValue": "stripe" } }
],
"status": {
"code": 2,
"message": "Upstream provider unavailable: HTTP 503"
},
"events": [
{
"name": "exception",
"timeUnixNano": "1711200001490000000",
"attributes": [
{ "key": "exception.type", "value": { "stringValue": "UpstreamServiceUnavailableException" } },
{ "key": "exception.message", "value": { "stringValue": "503 Service Unavailable returned from api.stripe.com" } },
{ "key": "exception.escaped", "value": { "boolValue": false } }
]
}
]
}
]
}
]
}
]
}
Isolating the Three Core Failure Modes
When trace triage algorithms classify incoming telemetry, they inspect span attributes, error taxonomy, and hierarchy. Telemetry can be structured to separate failures into three primary categories:
1. Code Bugs (Application Logic Errors)
A true code bug manifests when the executing runtime throws an unexpected exception due to logic flaws, unhandled null values, or bad type coercions.
- Attributes to check: Span kind is typically
SPAN_KIND_INTERNALorSPAN_KIND_SERVER. - Exception indicators:
exception.typematches standard runtime errors (e.g.,TypeError,NullPointerException,ReferenceError). - Span attributes: The
http.response.status_codemight be500, but no client-side spans (SPAN_KIND_CLIENT) underneath it report network disconnects or upstream latency. - Actionable output: Capturing the
exception.stacktraceattribute points directly to source repository lines, allowing tools to isolate the exact commit or file introducing the error.
2. Infrastructure Failures (Platform & Resource Saturation)
Infrastructure errors occur when the execution environment degrades or halts before the application can complete its work.
- Attributes to check: Spans report connection drops, container terminations, or resource exhaustion.
- Exception indicators: Look for runtime exceptions like
ECONNRESET,ETIMEDOUT, or POSIX signals (e.g.,SIGKILL,OOMKilled). - Resource attributes: Spans tagged with
k8s.pod.name,cloud.provider, and database connection pool states provide signal. - Pattern: An outgoing DB span (
db.system) that fails withPoolTimeoutErrorwhile container memory metrics surge indicates an infra bottleneck rather than an unhandled code bug.
3. Third-Party Vendor Issues
Modern applications rely heavily on external SaaS providers, authentication services, and payment gateways. Without explicit span tags, a partner's outage looks like an internal incident.
- Attributes to check:
span.kindmust beSPAN_KIND_CLIENT. - Target metadata: Populating
peer.service,server.address, andhttp.urlestablishes ownership. - Response codes: When
server.addresspoints outside your VPC and returns429 Too Many Requests,502 Bad Gateway, or503 Service Unavailable, this failure belongs strictly to external vendor downtime. - Sanitization requirement: Ensure bearer tokens, customer credentials, and payment card numbers are removed from outgoing payload strings before logging.
Node.js Implementation: Clean Exception Modeling
In Node.js applications, standardizing OpenTelemetry tracing ensures that raw JavaScript errors are captured with semantic precision.
import { trace, SpanStatusCode, SpanKind } from '@opentelemetry/api';
const tracer = trace.getTracer('checkout-service');
export async function callPaymentGateway(payload: unknown) {
return tracer.startActiveSpan('processPayment', { kind: SpanKind.CLIENT }, async (span) => {
span.setAttribute('peer.service', 'payment-gateway');
span.setAttribute('server.address', 'api.paymentvendor.com');
try {
const response = await fetch('https://api.paymentvendor.com/v1/charge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
span.setAttribute('http.response.status_code', response.status);
if (!response.ok) {
const err = new Error(`Payment Gateway failed with status ${response.status}`);
span.recordException(err);
span.setStatus({
code: SpanStatusCode.ERROR,
message: response.status >= 500 ? 'Third-party upstream error' : 'Third-party client error',
});
throw err;
}
return await response.json();
} catch (error: any) {
if (error.code === 'ECONNREFUSED' || error.name === 'AbortError') {
span.setAttribute('error.type', 'infrastructure_network');
} else if (!span.isRecording()) {
// Span already recorded upstream failure
} else {
span.setAttribute('error.type', 'code_bug');
}
span.recordException(error);
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
throw error;
} finally {
span.end();
}
});
}
Practical Rules for Triage-Ready Telemetry
To make spans genuinely valuable for triage pipelines:
- Do not swallow stack traces: When catching exceptions to set span statuses, always record the full error object using
span.recordException(error)rather than setting an arbitrary string message. - Deduplicate via signatures: Compute deterministic signatures across
exception.type, root stack frames, andpeer.serviceso that repeated alerts consolidate into a single investigation stream. - Enforce PII scrubbing: Strip sensitive data like authorization headers, session cookies, and authentication tokens before serializing payloads to the ingestion pipeline.
- Map downstream dependencies: Set
peer.servicefor every outbound network call. This cleanly decouples vendor downtime from internal application regressions.