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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With