Video in progress

Strong Middle 🧭 Design patterns

What new problems appear when you make an event listener `@Async`?

The listener runs on another thread: the caller's transaction, security context and MDC log context don't carry over, and exceptions don't go back to the publisher. When the application stops, pending events can be lost, and the thread pool can fill up.

📖 Answer

In the synchronous Observer everything was in one call stack. Once @Async is added:

Transaction. The listener doesn't see the caller's transaction. If the event was published before the commit, the listener can't find the new row in the database yet (EntityNotFoundException or an empty result). The usual fix is @TransactionalEventListener(phase = AFTER_COMMIT) + @Async together. Put the ID in the event, not the entity: a lazy field on a detached entity gives a LazyInitializationException on another thread.

Exceptions. An exception in an @Async method that returns void goes back to nobody: it lands in the AsyncUncaughtExceptionHandler, which by default only writes a log entry. Without monitoring, the error can go unnoticed for weeks.

Context. SecurityContextHolder and the SLF4J MDC are thread-local. On the new thread there's neither the user nor the traceId. You have to copy them with a TaskDecorator:

@Bean
ThreadPoolTaskExecutor eventExecutor() {
    var ex = new ThreadPoolTaskExecutor();
    ex.setCorePoolSize(4);
    ex.setQueueCapacity(500);
    ex.setTaskDecorator(task -> {
        var mdc = MDC.getCopyOfContextMap();
        return () -> {
            if (mdc != null) MDC.setContextMap(mdc);
            try { task.run(); } finally { MDC.clear(); }
        };
    });
    return ex;
}

Loss. The queue is in memory. If the pod goes down during a deploy, events that haven't run yet are lost. If the event matters (payment, bonus), write it to the database first (an outbox table) and process it afterwards.

The pool. Spring Boot provides its own ThreadPoolTaskExecutor for @Async, but its queue is unbounded by default, so memory grows under load. Configure the executor explicitly yourself.