AsyncLocalStorage to automatically manage trace context across asynchronous operations. This enables transparent parent-child span relationships without explicit context threading.
How it works
The tracer maintains a span stack inAsyncLocalStorage, which is preserved across async boundaries like promises, callbacks, and async/await.
Context management
When you start a span, it automatically:- Detects the current parent span from the AsyncLocalStorage stack
- Inherits the
traceIdfrom the parent (or generates a new one for root spans) - Sets its
parentIdto the parent’sspanId - Inherits session information and tags from the parent
- Pushes itself onto the stack for child spans to discover
Trace lifecycle
1. Starting a trace
A trace begins when you create a root span (a span with no parent):- A new
traceIdis generated - A new
sessionIdis generated (or uses the provided one) - The span becomes the root of the trace
2. Building the trace tree
As child spans are created, they form a tree structure:3. Buffering and ordering
The tracer buffers spans by trace until the entire trace is complete:- Spans are held in trace-specific buckets (
_traceBuckets) - When the last span in a trace ends, all spans are moved to the main buffer
- Spans are ordered parent-first before flushing
- Active traces are tracked via reference counting (
_activeTraceCounts)
4. Flushing to backend
Traces are automatically flushed when:- The buffer reaches
maxSpans(default: 100) - The flush interval elapses (default: 10 seconds)
tracer.shutdown()is called
Accessing current context
You can access the currently active span at any point:Tag inheritance
Tags are automatically inherited from parent to child spans:Best practices
Use withSpan for most cases
Use withSpan for most cases
The
withSpan helper automatically handles span lifecycle and error capture:Name spans descriptively
Name spans descriptively
Use clear, hierarchical names that indicate the operation:
Let the tracer manage context
Let the tracer manage context
Don’t pass spans as function parameters. Trust AsyncLocalStorage:
Flush on shutdown
Flush on shutdown
Always flush remaining spans before your application exits: