Creating an event-driven architecture with Spring Events and Async

Spring Events offer a straightforward way to decouple business actions within a Java application. An order service can publish an event, while fulfilment, billing, and notification components react independently without calling one another directly.

Asynchronous listeners move that work away from request threads, improving response times when downstream operations take longer than a database update. This makes the approach useful for notifications, reporting, search indexing, and other secondary tasks.

Reliable event-driven design requires more than adding @Async. Transaction boundaries, bounded concurrency, duplicate delivery, and failure recovery must be considered before production workloads are introduced.

Model business events at the domain boundary

Events should describe something that has already happened in the business domain. A clear name and compact payload make consumers easier to understand and test.

public record OrderPlaced(
    String orderId,
    String customerId,
    BigDecimal totalAud
) {}

Publish the event through ApplicationEventPublisher after creating the order. Include identifiers rather than mutable entities, and avoid placing unnecessary personal information in the payload.

Run listeners away from request threads

Spring enables asynchronous method execution with @EnableAsync. Naming a dedicated executor prevents important listeners from competing with unrelated background tasks.

@EnableAsync
@Configuration
class AsyncConfig {
    @Bean("orders")
    ThreadPoolTaskExecutor orders() {
        var executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(200);
        return executor;
    }
}

An @Async and @EventListener combination routes the handler to that executor. Because the listener runs through a Spring proxy, private methods and self-invocation will not gain asynchronous behaviour. Exceptions in an asynchronous listener also do not automatically return to the original publisher.

Control concurrency and failure handling

Unbounded thread pools can exhaust memory during traffic spikes, while a single-threaded executor may process urgent work behind slow jobs. Configure core threads, maximum threads, and queue capacity according to measured workloads.

A bounded executor applies backpressure when activity exceeds capacity, but rejected tasks still need a policy. Record rejections through metrics and structured logs, and preserve the event identifier for investigation. Retries should use backoff rather than immediately repeating a failed call.

Spring’s in-memory events are lost if the process crashes. Broker-based messaging provides durable delivery and consumer offsets, making it preferable when every event must survive a restart.

Coordinate transactions and side effects

Publishing an event inside a database transaction creates a race: an asynchronous consumer could receive it before the transaction commits. Use @TransactionalEventListener with the AFTER_COMMIT phase when the event represents a committed state change.

@Async("orders")
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onOrderPlaced(OrderPlaced event) {
    reserveStock(event.orderId());
}

A failure after commit cannot roll back the original transaction. For critical integrations, write the business record and an outbox record in one transaction, then publish the outbox entry through a separate relay. Consumers should also be idempotent because retries can produce duplicate processing.

Verify asynchronous behaviour

Unit tests can verify event mapping and business decisions, while integration tests should exercise publishing, proxying, executor configuration, and transaction phases. Asynchronous assertions need a bounded wait rather than a fixed sleep.

await().atMost(2, TimeUnit.SECONDS)
    .untilAsserted(() ->
        verify(fulfilment).reserveStock("A-42"));

Test duplicate events, listener exceptions, rejected tasks, and application shutdown. Broader architecture reviews can be supported by Spring Boot consultancy when broker adoption, security, or operational ownership needs assessment.

Apply Australian operational requirements

An event contract should make its delivery and compatibility expectations explicit:

Australian deployments must also reflect local time, commerce, and privacy conditions. Sydney and Melbourne operate in the same eastern time zone, while Perth is two hours behind; store instants in UTC and localise presentation. Digital wallets, mobile banking, and app notifications are everyday habits, so customer confirmations should not wait on slower background work.

The Privacy Act 1988 and Australian Privacy Principles govern customer data, including eligible data-breach notification requirements. Audit records should support OAIC reporting without unnecessarily duplicating sensitive details. The Australian Consumer Law also makes reliable refund and cancellation handling important.

Operationally, Australian teams should:

These controls allow Spring applications to react quickly while keeping transaction boundaries, consumer expectations, and regulatory obligations visible across the delivery team.