# Context Propagation and traceparent — Logging, Metrics, Tracing & Alerting

Source: https://www.skillbyai.com/en/observability/ob-context-propagation

> Describe how trace context crosses process boundaries using the W3C traceparent header, and what breaks it.

## Passing the baton between services

A trace only works if every service knows which trace it is part of. **Context propagation** is the mechanism that carries the trace ID and the current span ID from one process to the next. Inside a process, the context lives in request-scoped storage (like the correlation ID from earlier). Across a network call, it is **injected** into the outgoing request and **extracted** on the other side.

The standard format for HTTP is the **W3C Trace Context** `traceparent` header: `version-traceid-parentid-flags`, for example `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. The trace ID is 32 hex characters, the parent ID is the caller's span ID in 16 hex characters, and the lowest flag bit means **sampled**. An optional `tracestate` header carries vendor-specific data, and a separate `baggage` header can carry application key-values.

For message queues, the same values go into message headers or attributes. Propagation breaks when a hop does not forward headers: a proxy that strips them, a thread pool that loses context, or a hand-written HTTP client without instrumentation. The result is a trace that ends abruptly or splits into two unrelated traces.

## Parsing and forwarding traceparent

A simplified version of what a tracing library does: validate the incoming header, keep the trace ID, and send your own span ID as the new parent. Real libraries handle more edge cases (future versions, tracestate).

```python
import re

TP = re.compile(r"^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$")

def parse(header):
    m = TP.match(header)
    if not m or m.group(1) == "0" * 32 or m.group(2) == "0" * 16:
        return None                      # invalid: start a new trace instead
    trace_id, parent_id, flags = m.groups()
    return {"trace_id": trace_id, "parent_id": parent_id,
            "sampled": int(flags, 16) & 1 == 1}

def outgoing(ctx, my_span_id):
    flags = "01" if ctx["sampled"] else "00"
    return f"00-{ctx['trace_id']}-{my_span_id}-{flags}"

ctx = parse("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
print(ctx)
print("send:", outgoing(ctx, "b7ad6b7169203331"))   # new span ID, same trace ID
print(parse("not-a-traceparent"))
```

Output:

```
{'trace_id': '4bf92f3577b34da6a3ce929d0e0e4736', 'parent_id': '00f067aa0ba902b7', 'sampled': True}
send: 00-4bf92f3577b34da6a3ce929d0e0e4736-b7ad6b7169203331-01
None
```

## Async work loses context silently

When work moves to a background thread, an executor or a queue consumer, the context does not follow automatically in every language. Use your SDK's helpers (context-aware executors, `context.attach`, or instrumented queue clients) and verify with a test that the background span has the right parent.

**Quiz:** In the header 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01, what does the final 01 mean?

- [ ] The protocol version
- [ ] The request is the first retry
- [ ] The span has finished successfully
- [x] The trace-flags field with the sampled bit set

*Answer:* The trace-flags field with the sampled bit set. The last field holds trace flags; the lowest bit set means the caller sampled this trace, so downstream services should usually record their spans too. The version is the leading 00.
