Book › DDD

Publishing domain events and handling them in Spring

Use Kotlin and Spring to publish domain events, run handlers at the right transaction phase, and choose between async listeners, brokers, and an Outbox.

Publishing domain events and handling them in Spring

Canceling an order can trigger refunds, notifications, and changes in other bounded contexts. While revisiting Chapter 10 of Choi Beom-gyun’s Getting Started with Domain-Driven Development, I used this example to compare Spring’s synchronous listeners, post-commit async handlers, and a transactional Outbox.

The examples use Kotlin 1.9, Java 21, Spring Boot 3.x, and Spring Data JPA with Hibernate 6.

Why an order cancellation becomes tightly coupled

Suppose CancelOrderService calls Order.cancel() and then invokes a remote RefundService.refund() and a notification sender. A refund timeout leaves the service to decide whether the cancellation should roll back. Worse, the payment provider might already have accepted the refund. Rolling back the local transaction cannot undo that remote side effect.

The wait can also tie up a database connection. If the transaction has already acquired row locks, it holds them while the remote calls finish. Every new reaction, such as reversing loyalty points or updating analytics, adds another dependency to the cancellation service.

A domain event expresses a fact that already happened in the model. The order reports OrderCanceledEvent, and the refund and notification handlers decide how to respond. That change removes the direct calls from CancelOrderService. The dispatch and transaction settings still determine whether a slow handler can block the order transaction.

Publishing an event from the order aggregate

The aggregate creates the event, ApplicationEventPublisher dispatches it, and handlers subscribe to the payload type. The event carries an order number and a timestamp. An identifier lets an async consumer load the data it needs in its own transaction. Passing a managed JPA entity across the boundary can expose lazy associations after the persistence context closes or introduce cycles during serialization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// com/example/shop/common/event/Events.kt
package com.example.shop.common.event

import org.springframework.context.ApplicationEventPublisher

interface Event {
    val timestamp: Long
}

object Events {
    private var publisher: ApplicationEventPublisher? = null

    fun setPublisher(publisher: ApplicationEventPublisher) {
        this.publisher = publisher
    }

    fun raise(event: Any) {
        publisher?.publishEvent(event)
    }

    fun reset() {
        publisher = null
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// com/example/shop/common/event/EventsConfiguration.kt
package com.example.shop.common.event

import org.springframework.beans.factory.InitializingBean
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class EventsConfiguration(
    private val applicationContext: ApplicationContext,
) {
    @Bean
    fun eventsInitializer(): InitializingBean = InitializingBean {
        Events.setPublisher(applicationContext)
    }
}
1
2
3
4
5
6
7
8
9
// com/example/shop/order/domain/OrderCanceledEvent.kt
package com.example.shop.order.domain

import com.example.shop.common.event.Event

data class OrderCanceledEvent(
    val orderNumber: String,
    override val timestamp: Long = System.currentTimeMillis(),
) : Event
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
// com/example/shop/order/domain/Order.kt (excerpt)
package com.example.shop.order.domain

import com.example.shop.common.event.Events
import com.example.shop.common.model.Money
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.Table

@Entity
@Table(name = "purchase_order")
class Order(
    @EmbeddedId
    val number: OrderNo,

    @Enumerated(EnumType.STRING)
    var state: OrderState,

    var totalAmounts: Money,
) {
    fun cancel() {
        verifyNotYetShipped()
        this.state = OrderState.CANCELED
        Events.raise(OrderCanceledEvent(number.number))
    }

    private fun verifyNotYetShipped() {
        check(state == OrderState.PAYMENT_WAITING || state == OrderState.PREPARING) {
            "Cannot cancel an order in state $state."
        }
    }
}

The Events holder keeps bean injection out of the entity. It brings global state, so tests that install a publisher should call Events.reset() in teardown. The nullable publisher lets a standalone domain test call cancel() without a Spring context. A test that expects publication must install a publisher first.

Spring Data also supports repository-triggered publication through @DomainEvents and AbstractAggregateRoot. If you use that approach, make sure the application calls a repository method that publishes the aggregate’s events. JPA dirty checking alone does not trigger that repository callback.

What Spring does at publication and commit

With the default SimpleApplicationEventMulticaster, a regular @EventListener runs inline on the publishing thread. If the publisher is inside a database transaction, the listener runs within that transaction’s scope. A slow refund call delays publishEvent(), and an uncaught listener exception reaches the caller. The usual Spring rollback rules still determine whether the order transaction rolls back.

For thread-bound transactions, TransactionalApplicationListenerMethodAdapter registers a synchronization through TransactionSynchronizationManager when it receives the event. Spring invokes BEFORE_COMMIT while the transaction can still persist changes. It invokes AFTER_COMMIT only after a successful commit. A transaction-bound listener skips events published without an active transaction unless you opt in to fallbackExecution.

A synchronous AFTER_COMMIT listener can still see resources from the completed transaction. If it needs to save refund history, call a separate Spring-managed method with @Transactional(propagation = Propagation.REQUIRES_NEW) so that write has its own commit. An @Async worker runs on another thread and does not inherit the publisher’s transaction.

Three ways to run work asynchronously

StrategyImplementation effortWhere events can be lostReplay and orderingFit
AFTER_COMMIT with @AsyncLowThe process can exit before the queued task runsRequires a separate mechanismBest-effort notifications, cache invalidation, or logs
Direct publish to Kafka or RabbitMQModerateThe database can commit before the broker accepts the messageDepends on broker retention, acknowledgments, and consumer setupFan-out across services when the database-to-broker handoff is addressed
Event store with a relay or polling APIHigherA pending event survives process restarts once the database commitsStored entries support replay. Ordering comes from the relay and consumer design.Payments, refunds, and settlement

For best-effort work, I’d register a dedicated eventExecutor bean, enable async handling with @EnableAsync, and attach the listener to AFTER_COMMIT. The handler below illustrates the timing with the same refund call. A refund that must eventually run needs the durable path in the next section.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// com/example/shop/order/infra/OrderCanceledEventHandler.kt
package com.example.shop.order.infra

import com.example.shop.order.domain.OrderCanceledEvent
import com.example.shop.order.domain.OrderNo
import com.example.shop.order.domain.RefundService
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import org.springframework.transaction.event.TransactionPhase
import org.springframework.transaction.event.TransactionalEventListener

@Component
class OrderCanceledEventHandler(
    private val refundService: RefundService,
) {
    @Async("eventExecutor")
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    fun handle(event: OrderCanceledEvent) {
        refundService.refund(OrderNo(event.orderNumber))
    }
}

An async pool isolates the request thread from slow handlers, but it can fill under load. I’d bound the pool and queue explicitly and decide how to handle rejections. The executor that Spring Boot auto-configures depends on the application settings. A Unit-returning @Async handler cannot return its exception to the caller, so configure an AsyncUncaughtExceptionHandler for visibility. If a failed task must be retried after a process restart, store it durably or use a broker retry and dead-letter policy.

Keeping the refund event in the same commit

The transactional Outbox moves the handoff into the database. A BEFORE_COMMIT listener writes an event_entry row in the same transaction and database as the purchase_order update. If that write fails, the cancellation can roll back with it. If the commit succeeds, EventForwarder can poll the stored events later with @Scheduled. It can publish them to a broker or expose them through a polling API.

flowchart TD
    S["Begin order transaction"] --> O["Cancel order"]
    O --> E["Store event before commit"]
    E --> DB["Commit both writes"]
    DB -.-> F["Poll pending events"]
    F --> MQ["Deliver to refund consumer"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// com/example/shop/common/event/EventStoreHandler.kt
package com.example.shop.common.event

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.stereotype.Component
import org.springframework.transaction.event.TransactionPhase
import org.springframework.transaction.event.TransactionalEventListener

@Component
class EventStoreHandler(
    private val eventEntryRepository: EventEntryRepository,
    private val objectMapper: ObjectMapper,
) {
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    fun store(event: Event) {
        val entry = EventEntry(
            type = event::class.java.name,
            contentType = "application/json",
            payload = objectMapper.writeValueAsString(event),
            timestamp = event.timestamp,
        )
        eventEntryRepository.save(entry)
    }
}

The relay can still crash after the broker accepts a message and before it advances its offset. Plan for at-least-once delivery. Reuse the same event ID on retries and enforce uniqueness on the consumer’s processed-event record. If a remote refund API supports idempotency keys, pass that same stable ID so a crash between sending the refund and recording it locally cannot cause a second refund. My Transactional Outbox write-up shows the polling relay and duplicate-handling details for an HTTP integration.

Checks before enabling refunds

  • Commit. Call the cancellation service through its Spring proxy and let the transaction commit. For the Outbox variant, verify in a separate transaction that the canceled order and its event row are both visible.
  • Rollback. Force an unchecked exception after Order.cancel(). The event row should roll back and the AFTER_COMMIT handler should stay idle. A plain @EventListener with @Async could otherwise issue a refund before the order transaction rolls back.
  • Retry. Interrupt the relay after delivery and before it records progress. Replay the same event and verify that the consumer issues a single refund.
  • Saturation. Fill the async executor queue in a test and check that rejected tasks and listener exceptions surface through the configured error handling.

References

Chapter 10 of the original Korean book covers events. Hanbit Media’s book listing

As of Spring 4.2, the listener of an event can be bound to a phase of the transaction. The typical example is to handle the event when the transaction has completed successfully. Doing so lets events be used with more flexibility when the outcome of the current transaction actually matters to the listener.
In the absence of an Executor bean in the context, Spring Boot auto-configures an AsyncTaskExecutor. When virtual threads are enabled (using Java 21+ and spring.threads.virtual.enabled set to true) this will be a SimpleAsyncTaskExecutor that uses virtual threads. Otherwise, it will be a ThreadPoolTaskExecutor with sensible defaults.
This post is licensed under CC BY 4.0 by the author.