Ask Your Question
3

How does the loss of Micrometer traceId occur when switching threads in Kotlin's coroutines?

asked 2023-02-15 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-04-18 23:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-15 11:00:00 +0000

Seen: 11 times

Last updated: Apr 18 '21