Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The loss of Micrometer traceId can occur when switching threads in Kotlin's coroutines because Micrometer uses a thread-local variable to store the traceId. Coroutines can switch threads during their execution which can cause the traceId to be lost if the new thread does not have access to the thread-local variable where the traceId is stored.

When a coroutine is started, it is executed on a thread provided by the coroutine dispatcher. If the coroutine suspends and then resumes later, it may be re-executed on a different thread. If Micrometer's traceId is stored in a thread-local variable, then when the coroutine switches threads, the traceId may not be available on the new thread.

To avoid the loss of Micrometer traceId when switching threads in Kotlin's coroutines, it is necessary to propagate the traceId between threads. This can be achieved using a CoroutineInterceptor, which can intercept the execution of a coroutine and modify its context. The interceptor can propagate the traceId by adding it to the coroutine's context and restoring it when the coroutine resumes on a different thread.

Alternatively, Micrometer provides a ContextAwareMeterRegistry which can be used to store the traceId in a context that is propagated between threads. When using this approach, the traceId is stored in the context of the active coroutine and can be accessed from any thread that executes the coroutine.