Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TraceId propagation to virtual thread

My application to handle upstream request calls 2 downstream systems (by REST). As calls are parallelizable, I would like to use virtual threads, by StructuredTaskScope.fork() or Executors.newVirtualThreadPerTaskExecutor()

Unfortunately, traceId is not automatically propagated downstream and MDC is not present in virtual threads.

After research it seems that it is known issue without simple solution.

I would like to ask if I can expect in future support from Spring Boot in trace and MDC propagation to virtual threads or I have to manage it myself

like image 589
michaldo Avatar asked Oct 30 '25 00:10

michaldo


1 Answers

To pass MDC and traceId to VT, I created the following virtual thread factory

class MdcAndTraceVirtualThreadFactory implements ThreadFactory {

  private static final ObservationRegistry OBSERVATION_REGISTRY = ObservationRegistry.create();

  @Override
  public Thread newThread(Runnable r) {
    Map<String, String> ctx = MDC.getCopyOfContextMap();
    Observation observation = OBSERVATION_REGISTRY.getCurrentObservation();
    return Thread.ofVirtual().factory().newThread(() -> {
        MDC.setContextMap(ctx);
        if (observation != null) {
          observation.observe(r);
        } else {
          r.run();
        }
    });
   }
}

Then I can pass the factory to StructuredTaskScope or Executors.newThreadPerTaskExecutor and have MDC and tracing aware virtual thread

like image 182
michaldo Avatar answered Oct 31 '25 21:10

michaldo