OTel Fundamentals Β· OTLP Wire Format Β· Hyperscaler Differences (AWS/GCP/Azure) Β· Trace Parsing Β· Tabular Conversion Β· Normalization Β· Anomaly Detection
All three major clouds now support OTLP, but each evolved from a pre-OTel proprietary format. The differences are legacy residue β and they matter when you're:
| Cloud | Legacy Format | OTel Status 2025 |
|---|---|---|
| βοΈ AWS | X-Ray JSON | OTLP via ADOT; own trace ID format still used internally |
| π΅ Azure | App Insights SDK | Azure Monitor OTel Distro; stores spans as requests/dependencies |
| π‘ GCP | OpenCensus | Native OTLP ingestion since Sep 2025; OTel is the native path |
| π Self-hosted | Jaeger/Zipkin | Pure OTLP; closest to the spec |
Every OTLP trace export nests data in three levels. This hierarchy is the key to parsing β you need to unwrap all three to get to individual spans.
| Field | Type | Description | Gotcha |
|---|---|---|---|
| trace_id | hex string | 16-byte unique identifier for the whole distributed trace. All spans in one transaction share this. | AWS X-Ray uses a different format: 1-{hex8}-{hex24} |
| span_id | hex string | 8-byte identifier unique within a trace. Links parent β child spans. | Absent parent_span_id = root span |
| parent_span_id | hex string | The span_id of the parent span. Defines the tree structure. | Missing/empty = root (no parent) |
| name | string | Human-readable operation name. Should be low-cardinality (no IDs in names). | High-cardinality names explode storage |
| kind | enum int | 1=Internal, 2=Server, 3=Client, 4=Producer, 5=Consumer | Most LLM spans are kind=3 (Client) |
| start_time_unix_nano | uint64 | Start timestamp in nanoseconds since Unix epoch. | Divide by 1e9 for seconds, 1e6 for ms |
| end_time_unix_nano | uint64 | End timestamp. Duration = end - start (in nanos). | In JSON, stored as string (int64 overflow) |
| attributes | KeyValue[] | Key-value metadata about this operation. The rich data source for analysis. | Every value wrapped in type envelope β must unwrap |
| status.code | enum int | 0=Unset (default), 1=Ok, 2=Error | Unset β Ok. Explicitly set Ok on success. |
| status.message | string | Human-readable error description. Only set when code=Error. | Absent on success β don't error on missing |
| events | Event[] | Timestamped annotations within a span (e.g., exception stack traces, checkpoints). | Each event has its own attributes dict |
| links | Link[] | References to spans in OTHER traces. Used for message queues, batch jobs. | Rare but important for async patterns |
| resource.attributes | KeyValue[] | Describes the entity producing spans (service.name, host, k8s.pod, etc.) | Defined at Resource level, not Span level |
OTel defines standard attribute names for AI/LLM spans. Using these makes traces portable across LangSmith, Langfuse, and any OTel-compatible backend.
| Dimension | OTLP (Canonical) | AWS X-Ray | GCP Cloud Trace | Azure App Insights |
|---|---|---|---|---|
| Trace ID format | 32-char hex | 1-{8hex}-{24hex} (timestamp prefix) | 32-char hex (OTLP) | W3C format |
| Timestamp unit | nanoseconds | seconds (float) | nanoseconds | milliseconds (ISO 8601) |
| Span β table mapping | spans[] | segments / subsegments | spans | requests + dependencies (2 tables!) |
| Attributes namespace | OTEL semconv (gen_ai.*) | AWS-specific (aws.*, xray.*) | OTLP native (since Sep 2025) | App Insights SDK fields |
| Status field | status.code (0/1/2) | fault / error / throttle booleans | status.code (OTLP) | success (bool) + resultCode |
| Parent relationship | parent_span_id | parent_id on subsegment | parent_span_id (OTLP) | operation_ParentId |
| Context propagation | W3C traceparent header | X-Amzn-Trace-Id header (also W3C now) | W3C traceparent header | W3C traceparent header |
| Export format | OTLP/gRPC, OTLP/HTTP | X-Ray API JSON | OTLP (native since 2025) | Breeze protocol β Log Analytics |
| Concept | OTLP (canonical) | AWS X-Ray | GCP Cloud Trace | Azure App Insights |
|---|---|---|---|---|
| Trace ID | traceId (hex32) | trace_id (1-hex8-hex24) | in name path | operation_Id |
| Span ID | spanId (hex16) | id (hex16) | spanId | id (|prefix.hex format) |
| Parent Span ID | parentSpanId | parent_id on subsegment | parentSpanId | operation_ParentId |
| Span name | name | name | displayName.value | name |
| Start time | startTimeUnixNano (ns int) | start_time (float seconds) | startTime (RFC3339) | timestamp (ISO 8601) |
| Duration | end_nano - start_nano | end_time - start_time (seconds) | endTime - startTime | duration (HH:MM:SS.mmm string) |
| Error flag | status.code == 2 | fault==true OR error==true | status.code == "ERROR" | success == false |
| HTTP status | http.status_code attr | http.response.status | http.status_code attr | resultCode |
| Custom attrs | attributes[] (KV array) | metadata or annotations | attributes.attributeMap (map) | customDimensions (flat dict) |
| Service name | resource.service.name | name (segment level) | resource attribute | cloud_RoleName |
| Child spans | separate spans with parentSpanId | subsegments[] (nested) | separate spans | separate rows in dep table |
"""Parse OTLP JSON trace export into a flat pandas DataFrame.
Works with traces from Jaeger, Tempo, Langfuse, LangSmith,
Langfuse v3, and any OTel-compatible backend."""
import json, pandas as pd
from datetime import datetime, timezone
def extract_value(v: dict):
"""Unwrap OTLP attribute value envelope."""
if "stringValue" in v: return v["stringValue"]
if "intValue" in v: return int(v["intValue"]) # note: string in JSON!
if "doubleValue" in v: return float(v["doubleValue"])
if "boolValue" in v: return v["boolValue"]
if "arrayValue" in v:
return [extract_value(i) for i in v["arrayValue"].get("values",[])]
if "kvlistValue" in v:
return {kv["key"]: extract_value(kv["value"])
for kv in v["kvlistValue"].get("values",[])}
return None
SPAN_KIND = {0:"UNSPECIFIED",1:"INTERNAL",2:"SERVER",3:"CLIENT",4:"PRODUCER",5:"CONSUMER"}
STATUS_CODE = {0:"UNSET",1:"OK",2:"ERROR"}
def otlp_to_dataframe(otlp_json: str | dict) -> pd.DataFrame:
data = json.loads(otlp_json) if isinstance(otlp_json, str) else otlp_json
rows = []
for rs in data.get("resourceSpans", []):
# Extract resource attributes (service name, env, etc.)
res_attrs = {
kv["key"]: extract_value(kv["value"])
for kv in rs.get("resource", {}).get("attributes", [])
}
service = res_attrs.get("service.name", "unknown")
for ss in rs.get("scopeSpans", []):
scope_name = ss.get("scope", {}).get("name", "")
for span in ss.get("spans", []):
# Timestamps: nanoseconds β datetime
start_ns = int(span.get("startTimeUnixNano", 0))
end_ns = int(span.get("endTimeUnixNano", 0))
start_dt = datetime.fromtimestamp(start_ns / 1e9, tz=timezone.utc)
dur_ms = (end_ns - start_ns) / 1_000_000
# Attributes
attrs = {
kv["key"]: extract_value(kv["value"])
for kv in span.get("attributes", [])
}
status_block = span.get("status", {})
row = {
# Identity
"trace_id": span.get("traceId"),
"span_id": span.get("spanId"),
"parent_span_id": span.get("parentSpanId"),
"name": span.get("name"),
# Classification
"kind": SPAN_KIND.get(span.get("kind",0)),
"service": service,
"scope": scope_name,
# Timing
"start_time": start_dt,
"duration_ms": round(dur_ms, 3),
# Status
"status": STATUS_CODE.get(status_block.get("code",0)),
"error_msg": status_block.get("message"),
# LLM-specific (from GenAI semconv)
"llm_system": attrs.get("gen_ai.system"),
"llm_model": attrs.get("gen_ai.request.model"),
"input_tokens": attrs.get("gen_ai.usage.input_tokens"),
"output_tokens": attrs.get("gen_ai.usage.output_tokens"),
"http_status": attrs.get("http.status_code"),
# Resource metadata
"env": res_attrs.get("deployment.environment"),
"svc_version": res_attrs.get("service.version"),
# All attributes (for full mode)
"_attrs": attrs,
"_res_attrs": res_attrs,
}
rows.append(row)
df = pd.DataFrame(rows)
# Derived columns
if not df.empty and "input_tokens" in df.columns:
df["total_tokens"] = df["input_tokens"].fillna(0) + df["output_tokens"].fillna(0)
# Rough cost (claude-sonnet-4-6 pricing)
df["est_cost_usd"] = (
df["input_tokens"].fillna(0) / 1_000_000 * 3.00 +
df["output_tokens"].fillna(0) / 1_000_000 * 15.00
).round(6)
return df
# Usage:
# df = otlp_to_dataframe(open("trace.json").read())
# df[["name","duration_ms","status","total_tokens","est_cost_usd"]]
"""Normalize AWS X-Ray trace segments to canonical OTLP-style dicts.
Key conversions:
- trace_id: "1-hex8-hex24" β 32-char hex
- timestamps: float seconds β unix nanoseconds
- status: fault/error/throttle booleans β status code
- subsegments: nested dict β flat list with parent_id
"""
import re
from datetime import datetime, timezone
def xray_traceid_to_hex(xray_id: str) -> str:
"""Convert '1-67891233-abcdef012345678912345678' to 32-char hex."""
parts = xray_id.split("-")
if len(parts) == 3 and parts[0] == "1":
epoch_hex = parts[1] # 8-char hex timestamp
random_hex = parts[2] # 24-char random hex
return (epoch_hex + random_hex).ljust(32, "0")
return xray_id # already in some other format
def xray_status(segment: dict) -> str:
if segment.get("fault"): return "ERROR" # 5xx
if segment.get("error"): return "ERROR" # 4xx
if segment.get("throttle"): return "ERROR" # 429
return "OK"
def flatten_xray_segments(segment: dict, trace_id: str, parent_id: str = None) -> list:
"""Recursively flatten X-Ray segments + subsegments into a flat span list."""
start_s = segment.get("start_time", 0)
end_s = segment.get("end_time", start_s)
http = segment.get("http", {})
req = http.get("request", {})
resp = http.get("response", {})
span = {
"source": "xray",
"trace_id": xray_traceid_to_hex(trace_id),
"span_id": segment.get("id"),
"parent_span_id": parent_id,
"name": segment.get("name"),
"start_time": datetime.fromtimestamp(start_s, tz=timezone.utc),
"duration_ms": round((end_s - start_s) * 1000, 3),
"status": xray_status(segment),
"http_method": req.get("method"),
"http_status": resp.get("status"),
"url": req.get("url"),
# Annotations = user-defined key-value strings
"annotations": segment.get("annotations", {}),
# Metadata = arbitrary nested user data
"metadata": segment.get("metadata", {}),
# AWS-specific
"aws_region": segment.get("aws", {}).get("region"),
"aws_service": segment.get("aws", {}).get("operation"),
}
spans = [span]
# Recursively process subsegments (children)
for sub in segment.get("subsegments", []):
spans.extend(
flatten_xray_segments(sub, trace_id, parent_id=segment["id"])
)
return spans
def xray_trace_to_dataframe(xray_json: str | dict):
import json, pandas as pd
data = json.loads(xray_json) if isinstance(xray_json, str) else xray_json
all_spans = []
for trace in data.get("Traces", [data]): # handle single or batch
tid = trace.get("Id", "unknown")
for seg in trace.get("Segments", [trace]):
doc = seg.get("Document", seg)
if isinstance(doc, str):
import json as _j
doc = _j.loads(doc)
all_spans.extend(flatten_xray_segments(doc, tid))
return pd.DataFrame(all_spans)
"""Normalize Azure App Insights telemetry to canonical form.
Azure stores spans in TWO different tables:
- requests: SERVER spans (incoming HTTP, functions)
- dependencies: CLIENT spans (HTTP calls, DB, LLM calls)
Both must be combined for a complete trace view.
Key conversions:
- operation_Id β trace_id
- id: "|traceId.spanHex" β strip prefix
- duration: "HH:MM:SS.mmm" β milliseconds
- customDimensions β attributes dict
"""
import re, json
import pandas as pd
from datetime import datetime, timezone, timedelta
def parse_azure_duration(duration_str: str) -> float:
"""Convert Azure duration 'HH:MM:SS.mmm' or 'D.HH:MM:SS.mmm' to ms."""
# Format examples: "00:00:02.341" or "0.00:00:02.3410000"
pattern = r"(?:(\d+)\.)?(\d{2}):(\d{2}):(\d{2})\.(\d+)"
m = re.match(pattern, duration_str)
if not m:
return 0.0
days = int(m.group(1) or 0)
hours = int(m.group(2))
mins = int(m.group(3))
secs = int(m.group(4))
frac = m.group(5)
ms = float("0." + frac) * 1000 # fractional seconds to ms
total_ms = (
days * 86_400_000 +
hours * 3_600_000 +
mins * 60_000 +
secs * 1_000 +
ms
)
return round(total_ms, 3)
def clean_azure_span_id(id_str: str) -> str:
"""Strip Azure's '|traceId.' prefix from span IDs."""
if "|" in id_str:
return id_str.split(".")[-1]
return id_str
def azure_to_dataframe(rows_json: str | list) -> pd.DataFrame:
"""
Convert Azure App Insights JSON export to normalized DataFrame.
Input: list of row dicts from the requests or dependencies table.
"""
rows = json.loads(rows_json) if isinstance(rows_json, str) else rows_json
normalized = []
for row in rows:
dims = row.get("customDimensions", {})
# Handle both string and dict customDimensions
if isinstance(dims, str):
try: dims = json.loads(dims)
except: dims = {}
span = {
"source": "azure",
"trace_id": row.get("operation_Id"),
"span_id": clean_azure_span_id(row.get("id","")),
"parent_span_id": clean_azure_span_id(row.get("operation_ParentId","")),
"name": row.get("name"),
"start_time": row.get("timestamp"),
"duration_ms": parse_azure_duration(row.get("duration","0:0:0")),
"status": "OK" if row.get("success") else "ERROR",
"http_status": row.get("resultCode"),
# Span type (requests vs dependencies)
"span_type": row.get("itemType","unknown"),
# Azure-specific fields
"target": row.get("target"),
"dependency_type":row.get("type"),
"operation_name": row.get("operation_Name"),
"cloud_role": row.get("cloud_RoleName"),
# OTel attributes (landed in customDimensions)
"llm_system": dims.get("gen_ai.system"),
"llm_model": dims.get("gen_ai.request.model"),
"input_tokens": dims.get("gen_ai.usage.input_tokens"),
"output_tokens": dims.get("gen_ai.usage.output_tokens"),
}
normalized.append(span)
return pd.DataFrame(normalized)
"""Standard pandas queries for trace analysis.
df = otlp_to_dataframe(trace_json) # from snippet 1
"""
import pandas as pd
# ββ Critical Path ββββββββββββββββββββββββββββββββββββββββββββ
def critical_path(df: pd.DataFrame) -> pd.DataFrame:
"""Find the longest chain of sequential spans (the bottleneck)."""
return df.sort_values("duration_ms", ascending=False).head(5)
# ββ Token + Cost Summary βββββββββββββββββββββββββββββββββββββ
def token_cost_summary(df: pd.DataFrame) -> dict:
"""Total tokens and estimated cost across all LLM spans."""
llm_spans = df[df["llm_model"].notna()]
return {
"total_input_tokens": int(llm_spans["input_tokens"].sum()),
"total_output_tokens": int(llm_spans["output_tokens"].sum()),
"total_tokens": int(llm_spans["total_tokens"].sum()),
"estimated_cost_usd": round(llm_spans["est_cost_usd"].sum(), 6),
"llm_calls": len(llm_spans),
"models_used": llm_spans["llm_model"].unique().tolist(),
}
# ββ Error Analysis βββββββββββββββββββββββββββββββββββββββββββ
def error_summary(df: pd.DataFrame) -> pd.DataFrame:
"""All error spans with their messages."""
return df[df["status"] == "ERROR"][
["trace_id","span_id","name","duration_ms","error_msg"]
]
# ββ Latency Percentiles per Span Name βββββββββββββββββββββββ
def latency_by_operation(df: pd.DataFrame) -> pd.DataFrame:
"""p50/p95/p99 latency grouped by span name."""
return df.groupby("name")["duration_ms"].agg([
("count","count"),
("p50", lambda x: x.quantile(0.50)),
("p95", lambda x: x.quantile(0.95)),
("p99", lambda x: x.quantile(0.99)),
("max", "max"),
]).round(1).sort_values("p95", ascending=False)
# ββ Parallel vs Sequential Detection ββββββββββββββββββββββββ
def find_parallel_spans(df: pd.DataFrame) -> list:
"""Find spans that run at the same time (candidates for optimization)."""
overlapping = []
spans = df.sort_values("start_time").to_dict("records")
for i, s1 in enumerate(spans):
for s2 in spans[i+1:]:
if s2["start_time"] > s1.get("end_time", s1["start_time"]):
break
if s1["parent_span_id"] == s2["parent_span_id"]: # siblings
overlapping.append((s1["name"], s2["name"]))
return overlapping
# ββ Anomaly Detection ββββββββββββββββββββββββββββββββββββββββ
def detect_anomalies(df: pd.DataFrame, latency_threshold_ms: float = 3000) -> pd.DataFrame:
"""Flag spans that exceed latency threshold or have errors."""
return df[
(df["duration_ms"] > latency_threshold_ms) |
(df["status"] == "ERROR") |
(df["total_tokens"].fillna(0) > 10_000)
][["name","duration_ms","status","total_tokens","error_msg"]]
# ββ Waterfall Data for Visualization βββββββββββββββββββββββββ
def trace_waterfall(df: pd.DataFrame) -> pd.DataFrame:
"""Compute relative start times for waterfall chart."""
if df.empty: return df
t0 = df["start_time"].min()
df = df.copy()
df["start_rel_ms"] = (df["start_time"] - t0).dt.total_seconds() * 1000
df["end_rel_ms"] = df["start_rel_ms"] + df["duration_ms"]
df["width_pct"] = df["duration_ms"] / df["end_rel_ms"].max() * 100
return df.sort_values("start_rel_ms")
# otel-collector.yaml
# Route traces from multiple apps to multiple backends simultaneously.
# Processes: batch, filter, attribute enrichment, PII redaction.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
# Batch spans for efficient export (reduces API calls)
batch:
timeout: 5s
send_batch_size: 512
# Add environment metadata to all spans
resource/add_env:
attributes:
- key: deployment.environment
value: production
action: upsert
# Redact PII from attributes before export
attributes/redact_pii:
actions:
- key: http.request.header.authorization
action: update
value: "[REDACTED]"
- key: db.statement
action: hash # SHA256 instead of delete
# Filter out health-check spans (noise reduction)
filter/drop_healthchecks:
error_mode: ignore
traces:
span:
- 'attributes["http.route"] == "/health"'
- 'attributes["http.route"] == "/ping"'
# Memory limiter (prevent OOM in high-traffic)
memory_limiter:
check_interval: 1s
limit_percentage: 75
spike_limit_percentage: 25
exporters:
# Self-hosted Jaeger (for development)
jaeger:
endpoint: jaeger:14250
tls:
insecure: true
# Grafana Tempo (for production)
otlp/tempo:
endpoint: tempo.monitoring:4317
tls:
insecure: false
# AWS X-Ray (if AWS is your primary cloud)
awsxray:
region: us-east-1
# Azure Monitor (if Azure)
azuremonitor:
connection_string: "${APPLICATIONINSIGHTS_CONNECTION_STRING}"
# Debug logging (development only)
logging:
verbosity: detailed
service:
pipelines:
# All traces β Tempo (primary store)
traces/all:
receivers: [otlp]
processors: [memory_limiter, resource/add_env, attributes/redact_pii, filter/drop_healthchecks, batch]
exporters: [otlp/tempo]
# LLM traces only β separate pipeline with LLM-specific processing
traces/llm:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo, azuremonitor]
telemetry:
logs:
level: warn
"""Instrument any Anthropic API call with OTel tracing.
Produces spans with GenAI semantic conventions (gen_ai.* attributes)
that work with LangSmith, Langfuse v3, Jaeger, Tempo, and X-Ray."""
import os, time
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from anthropic import Anthropic
# ββ Setup TracerProvider ββββββββββββββββββββββββββββββββββββββ
resource = Resource.create({
"service.name": os.getenv("SERVICE_NAME", "my-llm-app"),
"service.version": "1.0.0",
"deployment.environment": os.getenv("ENV", "development"),
})
provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(
endpoint=os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"),
insecure=True,
)
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("my-llm-app", "1.0.0")
client = Anthropic()
def traced_llm_call(
system: str,
user_message: str,
model: str = "claude-sonnet-4-6",
max_tokens: int = 800,
parent_context=None,
) -> tuple[str, dict]:
"""
Make an Anthropic API call with full OTel instrumentation.
Returns (response_text, telemetry_dict).
"""
ctx = parent_context or trace.get_current_span().get_span_context()
with tracer.start_as_current_span(
"anthropic.messages.create",
kind=trace.SpanKind.CLIENT,
) as span:
# Set GenAI semantic convention attributes
span.set_attribute("gen_ai.system", "anthropic")
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", model)
span.set_attribute("gen_ai.request.max_tokens", max_tokens)
t0 = time.perf_counter()
try:
response = client.messages.create(
model=model,
max_tokens=max_tokens,
system=system,
messages=[{"role": "user", "content": user_message}],
)
latency_ms = (time.perf_counter() - t0) * 1000
# Record usage metrics
span.set_attribute("gen_ai.usage.input_tokens", response.usage.input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", response.usage.output_tokens)
span.set_attribute("gen_ai.response.model", response.model)
span.set_attribute("gen_ai.response.finish_reason", response.stop_reason)
span.set_attribute("http.status_code", 200)
# Cost estimate (adjust per model pricing)
cost = (response.usage.input_tokens / 1_000_000 * 3.00 +
response.usage.output_tokens / 1_000_000 * 15.00)
span.set_attribute("gen_ai.usage.cost_usd", round(cost, 6))
span.set_status(trace.StatusCode.OK)
return response.content[0].text, {
"trace_id": format(span.get_span_context().trace_id, "032x"),
"span_id": format(span.get_span_context().span_id, "016x"),
"latency_ms": round(latency_ms, 1),
"input_tokens": response.usage.input_tokens,
"output_tokens": response.usage.output_tokens,
"cost_usd": round(cost, 6),
}
except Exception as e:
span.set_status(trace.StatusCode.ERROR, str(e))
span.record_exception(e)
raise
embed, retrieve, llm_call, tool_invoke so bottlenecks are visible.http.url vs http.target), clock skew across regions, and sampling differences. Build a mapping layer once, validate with golden traces from each cloud, and store canonical OTLP in your observability backend (Grafana Tempo, Datadog, etc.).