Overview
The tracing context propagation in otel4s is built on cats.mtl.Local semantics:How Context Flows
When you create spans, the context automatically propagates through your effect: Key properties:- Each fiber maintains its own context
- Forked fibers inherit the parent’s context
- Context changes are local to the fiber
Choosing a Context Carrier
Otel4s supports two primary context carriers. In most cases, IOLocal is the preferred and efficient choice.IOLocal (Recommended)
IOLocal provides efficient, fiber-local context storage built into Cats Effect:
Kleisli
Kleisli provides context through function composition:
Context Operations
Accessing Current Context
Retrieve the current span context:Creating Child Contexts
Explicitly create a child span with a specific parent:Joining External Contexts
Extract and join context from carriers (e.g., HTTP headers):Creating Root Contexts
Start a new trace without a parent:Disabling Context
Run operations without tracing:Propagating Context Across Boundaries
HTTP Requests
Inject context into outgoing HTTP requests:Message Queues
Propagate context through message attributes:Resource Limitations
The current encoding ofcats.effect.Resource is incompatible with Local semantics. This affects tracing across resource lifecycle stages.
The Problem
You cannot automatically trace all resource stages (acquire, use, release) while staying within the resource scope:The Solution
Explicitly trace each stage:Semantic Conventions
When propagating context, use standard propagators configured via environment variables:Best Practices
- Use IOLocal for most applications - it’s efficient and well-integrated with Cats Effect
- Propagate context at boundaries - Always inject and extract context when crossing service boundaries
- Use standard propagators - Stick to W3C Trace Context unless you have specific requirements
-
Handle missing context gracefully - Use
joinOrRootto start a new trace if context extraction fails - Be explicit with resources - Manually wrap resource stages with spans for proper tracing
-
Minimize context switching - Avoid unnecessary
rootScopeorchildScopecalls - Test context propagation - Verify that trace IDs flow correctly through your system