How do Spring application events and @Async work, and what are the pitfalls?
Application events
- Publish with
ApplicationEventPublisher.publishEvent(new OrderPlaced(id)); any object can be an event. - Listen with
@EventListenermethods. By default listeners run synchronously, in the publisher's thread and transaction, so an exception in a listener propagates to the publisher. @TransactionalEventListener(phase = AFTER_COMMIT)runs only if, and after, the surrounding transaction commits. Good for side effects such as cache eviction or notifications.- Events decouple modules inside one application (a modular monolith). Spring Modulith adds an event publication registry that persists events so they survive crashes.
@Async
- Enable with
@EnableAsync; the proxy submits the method call to aTaskExecutorand returns immediately (voidorCompletableFuture<T>). - Configure the executor explicitly (bounded queue, thread names), or in Boot 3.2+ use virtual threads.
Pitfalls
- Self-invocation bypasses the proxy, so the method runs synchronously.
- Exceptions from
voidasync methods are lost unless anAsyncUncaughtExceptionHandleris configured. - The async method runs outside the caller's transaction and without its
ThreadLocalcontext (security context, MDC, request scope) unless aTaskDecoratorpropagates it. - Data committed by the caller may not be visible yet if the async work starts before the commit; combine
@TransactionalEventListener(AFTER_COMMIT)with@Async. - In-memory async work is lost on crash or restart. Use a message broker or outbox for anything that must happen.
Example
java
@Component
class OrderNotifications {
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(OrderPlaced event) {
emailClient.sendConfirmation(event.orderId()); // runs after commit, off the request thread
}
}Follow-up questions interviewers ask
Try answering each one before you open it.
How do you propagate MDC and security context to async threads?
Register a TaskDecorator on the executor that captures the context in the calling thread and restores it in the worker:
java
executor.setTaskDecorator(task -> {
Map<String, String> mdc = MDC.getCopyOfContextMap();
SecurityContext sec = SecurityContextHolder.getContext();
return () -> {
try { if (mdc != null) MDC.setContextMap(mdc); SecurityContextHolder.setContext(sec); task.run(); }
finally { MDC.clear(); SecurityContextHolder.clearContext(); }
};
});With Micrometer Tracing, ContextPropagatingTaskDecorator handles trace context automatically.