Video in progress

Strong Middle 🧩 Microservices

In this code that uses CompletableFuture, why does the traceId disappear from the logs?

public Summary build(long userId) {
    log.info("summary boshlandi");               // traceId present
    var orders = CompletableFuture.supplyAsync(() -> orderClient.list(userId));
    var bonus  = CompletableFuture.supplyAsync(() -> bonusClient.get(userId));
    return new Summary(orders.join(), bonus.join());
}

The trace context is stored in a ThreadLocal. CompletableFuture.supplyAsync runs on another thread of a plain pool, and the context doesn't get passed there. You need an executor that propagates the context.

📖 Answer

If you don't pass an executor, supplyAsync runs on ForkJoinPool.commonPool(). Micrometer Tracing keeps the current span in a ThreadLocal, and for logs it keeps the traceId in the MDC (also a ThreadLocal). On the new thread they are empty: the orderClient call starts a new, unlinked trace or goes out with no trace at all. The log has no traceId either.

The fix is an executor that propagates the context:

@Bean
ThreadPoolTaskExecutor appExecutor() {
    var ex = new ThreadPoolTaskExecutor();
    ex.setCorePoolSize(8);
    ex.setTaskDecorator(new ContextPropagatingTaskDecorator()); // Spring 6.1+
    ex.initialize();
    return ex;
}

var orders = CompletableFuture.supplyAsync(() -> orderClient.list(userId), appExecutor);

ContextPropagatingTaskDecorator copies ThreadLocal values (trace, MDC, and security if needed) to the new thread through the Micrometer Context Propagation library, and cleans them up when the task finishes. For executors Spring creates itself (for @Async), you can wire this up together with the spring.task.execution settings.

In Reactor (WebClient) you need Hooks.enableAutomaticContextPropagation(). Remember the rule: when the thread changes, the context doesn't travel on its own.