Spring › Wanted-Challenge

Propagating MDC through Spring async domain events

Publish notification events after commit, carry SLF4J MDC into async workers, and handle executor, scheduler, and delivery failure modes.

Propagating MDC through Spring async domain events

A comment write used to depend directly on notification storage and SSE delivery. I moved that work behind a Spring domain event, and copied logging context into the async executor so the follow-up remained traceable.

The examples use Spring Boot 3.5, Kotlin 1.9, and Java 21.

Publishing a snapshot from the article domain

If CommentCommandService calls NotificationCommandService directly, the article domain takes a compile-time dependency on notification code. It also keeps the comment operation open while another service persists and delivers the alert. An independent subscriber can own those operations once the comment write has succeeded.

I publish immutable snapshots through ApplicationEventPublisher. The payload contains scalar data the listener needs, such as article IDs and display names. Passing a JPA entity would make the async handler depend on a persistence context that belongs to another thread.

1
2
3
4
5
6
7
8
9
10
11
12
// article/domain/event/CommentCreateEvent.kt
package org.project.portfolio.article.domain.event

data class CommentCreateEvent(
    val articleId: Long,
    val articleTitle: String,
    val articleAuthorId: Long,
    val commentId: Long,
    val commentAuthorId: Long,
    val commentAuthorName: String,
    val content: String,
)
1
2
3
4
5
6
7
8
// article/domain/event/ArticleEditDeadlineApproachingEvent.kt
package org.project.portfolio.article.domain.event

data class ArticleEditDeadlineApproachingEvent(
    val articleId: Long,
    val articleTitle: String,
    val authorId: Long,
)

After saving a comment, the command compares the comment author’s ID with the article author’s ID. It publishes CommentCreateEvent only when another person commented. The scheduler can also publish an article-edit deadline event without importing notification code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// article/application/CommentCommandService.kt
@Service
@Transactional
class CommentCommandService(
    private val articleRepository: ArticleRepository,
    private val commentRepository: CommentRepository,
    private val userRepository: UserRepository,
    private val eventPublisher: ApplicationEventPublisher,
) {
    fun createComment(
        email: String,
        articleId: Long,
        content: String,
    ): CommentResponse {
        val article = articleRepository.findByIdOrNull(articleId)
            ?: throw NotFoundException(Article::class.java, mapOf("articleId" to articleId))

        val user: User = userRepository.findByEmail(email)
            ?: throw NotFoundException(User::class.java, mapOf("email" to email))

        val comment = commentRepository.save(
            Comment.create(
                content = content,
                authorId = user.id,
                articleId = articleId,
            ),
        )

        if (article.authorId != user.id) {
            eventPublisher.publishEvent(
                CommentCreateEvent(
                    articleId = article.id,
                    articleTitle = article.title,
                    articleAuthorId = article.authorId,
                    commentId = comment.id,
                    commentAuthorId = user.id,
                    commentAuthorName = user.name,
                    content = comment.content,
                ),
            )
        }

        return CommentResponse.from(
            comment = comment,
            author = UserSummaryResponse.from(user),
        )
    }
}

Scheduling the listener after commit

A regular @EventListener can execute before the comment transaction finishes. A notification sent before a rollback would describe a comment that the user cannot retrieve. I attached the listener to AFTER_COMMIT to put successful completion ahead of scheduling.

flowchart TD
  A["HTTP trace setup"] --> B["Save and publish"]
  B -->|"Commit"| C["AFTER_COMMIT"]
  C -->|"Copy MDC"| D["Async worker"]
  D --> E["Store and send"]

The transaction-bound listener registers synchronization with TransactionSynchronizationManager. On a successful commit, Spring invokes the listener adapter, which dispatches the method through @Async("taskExecutor") and AsyncExecutionInterceptor. The worker has a separate thread-bound context. @Transactional(propagation = REQUIRES_NEW) gives notification writes their own transaction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// notification/application/ArticleNotificationEventListener.kt
@Component
class ArticleNotificationEventListener(
    private val notificationCommandService: NotificationCommandService,
) {
    @Async("taskExecutor")
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    fun handleCommentCreated(event: CommentCreateEvent) {
        notificationCommandService.sendNotification(
            notificationRequestDto = NotificationRequestDto(
                title = "New comment",
                content = "${event.commentAuthorName} commented on '${event.articleTitle}'.",
                receiver = event.articleAuthorId,
                sender = "system",
            ),
            sender = "system",
        )
    }

    @Async("taskExecutor")
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    fun handleArticleEditDeadlineApproaching(event: ArticleEditDeadlineApproachingEvent) {
        notificationCommandService.sendNotification(
            notificationRequestDto = NotificationRequestDto(
                title = "Article editing deadline",
                content = "You can edit '${event.articleTitle}' until tomorrow.",
                receiver = event.authorId,
                sender = "system",
            ),
            sender = "system",
        )
    }
}

For deadline events, fallbackExecution = true also handles publications made without an active transaction. That setting runs the listener without waiting for a commit when there is no transaction to observe. I keep it specific to the scheduler path where the publisher may run outside a transaction. See domain events and transaction phases for the two completion paths.

Carrying the trace into worker logs

LoggingFilter assigns TRACE_ID and requestId to SLF4J MDC for the HTTP request and clears them in a finally block. A request-scoped log context is useful only if the later worker logs can be linked to it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// config/LoggingFilter.kt
class LoggingFilter : OncePerRequestFilter() {
    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain,
    ) {
        val traceId = UUID.randomUUID().toString()
        val requestId = request.getHeader(REQUEST_ID) ?: "unknown"
        val query: String? = request.queryString?.takeIf { it.isNotEmpty() }

        try {
            MDC.put(TRACE_ID, traceId)
            MDC.put(REQUEST_ID, requestId)
            MDC.put("uri", request.requestURI)
            MDC.put("method", request.method)
            if (query != null) {
                MDC.put("query", query)
            }
            response.setHeader(TRACE_ID, traceId)
            filterChain.doFilter(request, response)
        } finally {
            MDC.clear()
        }
    }

    companion object {
        const val TRACE_ID = "TRACE_ID"
        const val REQUEST_ID = "requestId"
    }
}

MDC is backed by thread-local state. An executor that reuses worker threads needs to install the caller’s snapshot before it runs the submitted task. MdcTaskDecorator captures MDC.getCopyOfContextMap(), installs the context, and clears it at the end. Clearing it is essential when a worker can later handle a different request.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// config/AsyncConfig.kt
@Configuration
@EnableAsync
class AsyncConfig : AsyncConfigurer {
    @Bean(name = ["taskExecutor"])
    override fun getAsyncExecutor(): Executor {
        return ThreadPoolTaskExecutor().apply {
            corePoolSize = 4
            maxPoolSize = 16
            queueCapacity = 100
            setThreadNamePrefix("async-")
            setTaskDecorator(MdcTaskDecorator())
            setWaitForTasksToCompleteOnShutdown(true)
            setAwaitTerminationSeconds(30)
            initialize()
        }
    }

    override fun getAsyncUncaughtExceptionHandler(): AsyncUncaughtExceptionHandler {
        return AsyncUncaughtExceptionHandler { ex, method, params ->
            logger.error(ex) {
                "Uncaught async error in ${method.declaringClass.simpleName}.${method.name}(${params.joinToString()})"
            }
        }
    }

    class MdcTaskDecorator : TaskDecorator {
        override fun decorate(runnable: Runnable): Runnable {
            val contextMap = MDC.getCopyOfContextMap()
            return Runnable {
                try {
                    if (contextMap != null) {
                        MDC.setContextMap(contextMap)
                    } else {
                        MDC.clear()
                    }
                    runnable.run()
                } finally {
                    MDC.clear()
                }
            }
        }
    }

    companion object {
        private val logger = KotlinLogging.logger {}
    }
}

Exceptions from a Unit-returning async function do not travel back to the HTTP caller. I configured AsyncUncaughtExceptionHandler to log the target class, method, and arguments. Review those arguments for secrets or personal data before logging them. The executor can wait for queued work during shutdown, with a configured 30-second limit. Process crashes and forced termination still drop memory-only work.

Scheduling the ninth-day reminder

An hourly scheduler calls the command service to locate articles that need an editing deadline reminder. The command owns the query and event creation. A separate scheduler makes the time trigger visible and lets the service behavior be tested independently.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// article/application/scheduler/ArticleDeleteNotificationScheduler.kt
@Component
class ArticleDeleteNotificationScheduler(
    private val articleCommandService: ArticleCommandService,
) {
    @Scheduled(cron = "0 0 * * * *", zone = "Asia/Seoul")
    fun sendArticleUpdateNotification() {
        logger.info { "Starting the article editing reminder job" }
        articleCommandService.sendArticleUpdateNotification()
        logger.info { "Finished the article editing reminder job" }
    }

    companion object {
        private val logger: KLogger = KotlinLogging.logger {}
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// article/application/ArticleCommandService.kt (excerpt)
@Transactional(readOnly = true)
fun sendArticleUpdateNotification(
    start: Instant = Instant.now(clock).minusSeconds(9 * 24 * 60 * 60 + 1 * 60 * 60),
    end: Instant = Instant.now(clock).minusSeconds(9 * 24 * 60 * 60),
) {
    val articles: List<Article> = articleRepository.findByCreatedAtBetween(start, end)
    logger.debug { "Articles eligible for a day-nine reminder: ${articles.size}" }
    articles.forEach { article ->
        eventPublisher.publishEvent(
            ArticleEditDeadlineApproachingEvent(
                articleId = article.id,
                articleTitle = article.title,
                authorId = article.authorId,
            ),
        )
    }
}

The cron expression runs in Asia/Seoul, even if the container defaults to UTC. I inject a Clock so tests can select a fixed instant. In a multi-instance deployment, every replica schedules its own job. Use a distributed scheduler lock or durable recipient-and-event deduplication to keep a single reminder from becoming several. If a time window covers more than one scheduler execution, deduplication also protects repeat runs on one replica.

Choosing a delivery guarantee

AspectSpring Event with @AsyncTransactional Outbox and broker
InfrastructureIn-process dispatch and an executorDatabase table, relay, and broker
Process failureVolatile pending work can disappearStored work can be delivered again after restart
Typical useBest-effort notifications, logs, and countersPayment, settlement, and order state synchronization

I keep the in-memory path for secondary notifications that can tolerate a miss. A transactional Outbox can record delivery work with the domain write when the application needs a post-crash retry.

A self-invocation bypasses the async proxy. A full queue of 100 tasks with all 16 workers occupied can also raise TaskRejectedException. Decide how to surface saturation before depending on this path under load.

  • Roll back a comment write and check that the subscriber does not persist an alert.
  • Check that the same trace ID appears in request and worker logs. Then run an untraced task on a reused worker to verify that no previous context leaks.
  • Force an async handler to fail and inspect its error log.
  • Run the reminder with two instances and confirm the chosen scheduling or deduplication policy.
This post is licensed under CC BY 4.0 by the author.