Sobes.tech
Senior

If your service must respond immediately to a webhook and then process asynchronously, how to avoid losing MDC context?

sobes.tech AI

Answer from AI

MDC (Mapped Diagnostic Context) in logging is used to pass context (e.g., requestId) within a single thread. During asynchronous processing, especially if it occurs in another thread or after a webhook response, the MDC context is not automatically transferred.

To preserve the MDC context during asynchronous processing, you can:

  • Explicitly copy the MDC context from the current thread and pass it to the asynchronous task. For example, save Map<String, String> contextMap = MDC.getCopyOfContextMap() and call MDC.setContextMap(contextMap) in the asynchronous thread.
  • Use special wrappers for Runnable/Callable that automatically transfer MDC (e.g., DelegatingSecurityContextRunnable in Spring Security or custom implementations).
  • In Spring, you can use TaskDecorator for ThreadPoolTaskExecutor to automatically copy MDC to new threads.

Example using context copying:

Map<String, String> contextMap = MDC.getCopyOfContextMap();
executor.submit(() -> {
    if (contextMap != null) {
        MDC.setContextMap(contextMap);
    }
    // asynchronous logic
    MDC.clear();
});

Thus, the logging context is preserved even in asynchronous processing.