Tracing and correlation
What you will learn
A trace represents a distributed operation; spans represent portions of that work. Correlation is useful only when the context crosses the correct execution boundary and is cleaned up afterward.
- Explain trace identity, span identity, parent relationships and propagation.
- Capture and restore thread-local diagnostic context across a bounded executor.
- Separate correlation metadata from authentication and sensitive baggage.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Standalone Java 21 models; the companion telemetry configuration is source-reviewed, not executed.
Keep child spans in one synthetic trace
public class Main { record Span(String trace,String id,String parent) {} public static void main(String[] args) { var root=new Span("trace-demo","root",null); var child=new Span(root.trace(),"lookup",root.id()); System.out.println(child.trace()+":"+child.parent()+":"+child.id()); }}Expected output:
trace-demo:root:lookupThe parent ID is distinct from the trace ID. These illustrative strings are not wire-format W3C identifiers.
Trace structure and sampling
Text diagram: catalog request (root span) → inventory lookup (child span) → repository read (child of lookup). The trace ID groups all three; each span has a separate ID. A span has timing, attributes, events and status. Logs can include trace and span IDs; sampling limits recorded or exported traces, so a missing trace does not prove no request occurred. OpenTelemetry provides API, SDK, context propagators and exporters; an agent or framework integration can instrument common libraries. Use W3C trace context through approved propagators, not hand-written production header parsers. A caller-provided trace ID grants no permission.
MDC and async handoff
Mapped Diagnostic Context associates log metadata with the current execution context, often thread-local via the provider. Worker pools reuse threads, so context left behind can contaminate the next task. Capture an allowlisted snapshot when submitting; set it within the worker; restore the old context or remove it in a finally block. SLF4J exposes getCopyOfContextMap, setContextMap and clear; provider support varies. putCloseable removes a key on close, rather than restoring an overwritten value. For reactive code use framework context propagation, not an assumption that a request always stays on one thread.
Propagation boundaries and privacy
For OpenTelemetry, activate a Context with a Scope and close it in the same execution scope. End each created span in finally, including failures. Extract remote context at ingress and inject on outbound requests; validate via standard propagators and respect trust boundaries. Baggage can travel to other services, so never add passwords, tokens, personal data or authorization decisions. Sampling, exporter queues and failure handling must be bounded. The examples use fake correlation identifiers and a local ThreadLocal model, not actual telemetry exports.
Carry context into a reused worker and restore it
import java.util.concurrent.*;import java.util.function.Supplier;public class Main { static final ThreadLocal<String> CONTEXT=new ThreadLocal<>(); static <T> T scoped(String value, Supplier<T> work) { String before=CONTEXT.get(); CONTEXT.set(value); try { return work.get(); } finally { if(before==null) CONTEXT.remove(); else CONTEXT.set(before); } } public static void main(String[] args) { CONTEXT.set("request-A"); try(var pool=Executors.newSingleThreadExecutor()) { String captured=CONTEXT.get(); System.out.println(pool.submit(() -> scoped(captured, CONTEXT::get)).get(2,TimeUnit.SECONDS)); System.out.println(pool.submit(() -> String.valueOf(CONTEXT.get())).get(2,TimeUnit.SECONDS)); } catch (Exception e) { throw new IllegalStateException(e); } finally { CONTEXT.remove(); } }}Expected output:
request-AnullThe caller explicitly captures the synthetic ID. The worker uses it only during the task; the next job sees no residual value. This is a JDK model, not SLF4J MDC or OTel SDK execution.
Restore a previous scope after failure
public class Main { static final ThreadLocal<String> CONTEXT=new ThreadLocal<>(); static void scoped(String value,Runnable work) { String old=CONTEXT.get(); CONTEXT.set(value); try { work.run(); } finally { if(old==null) CONTEXT.remove(); else CONTEXT.set(old); } } public static void main(String[] args) { CONTEXT.set("outer"); try { scoped("inner", () -> { throw new IllegalStateException(); }); } catch(IllegalStateException expected) { System.out.println(CONTEXT.get()); } finally { CONTEXT.remove(); } }}Expected output:
outerRestoration works even when the nested operation fails. Clearing everything instead would erase the caller’s existing context.
Common mistakes
Do not use correlation IDs as a credential, copy the entire incoming header map into baggage, or leave diagnostic context on a reused worker. Do not assume a sampled trace captures all errors.
Practice
Create an allowlisted context snapshot from a map with trace and token keys. Mutate the original trace value afterward. Print the captured trace and whether the snapshot contains token.
Expected output:
demofalseCompare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tracing and correlation — knowledge check
Observability and reliability reasoning.
What is shared by child spans in a trace?
When capture context for an executor?
Why restore context in finally?
What belongs in baggage?
What does an absent sampled trace prove?