Spring Boot 4 Complete Guide · Leçon

Publication transactionnelle d’événements et boîte de sortie

Garantissez la livraison des événements avec le registre de publication des événements et le modèle de boîte de sortie transactionnelle.

Leçon 3 sur 413 étapes

Publication transactionnelle d’événements et boîte de sortie est une leçon Spring Boot 4 Complete Guide gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Boot 4 Complete Guide, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Why Events Get Lost

In an event-driven Spring Modulith application, modules talk to each other by publishing application events. A module raises an event inside a transaction, and listeners in other modules react to it.

The danger: by default, when you publish an event and a listener processes it asynchronously (or in a separate transaction), the listener's work can fail after the publisher already committed. The result is a lost event — the publisher's state changed, but the downstream side effect never happened.

  • Publisher commits an Order as PAID.
  • The async listener that sends a confirmation email crashes.
  • Nobody retries — the customer never gets the email.

This lesson shows how Spring Modulith's Event Publication Registry implements the transactional outbox pattern to guarantee delivery.

The Transactional Outbox Pattern

The transactional outbox pattern solves the dual-write problem: you must atomically (1) change your business state and (2) record that an event needs to be delivered.

Instead of trying to write to the database and a message broker in one transaction (impossible without distributed transactions), you write both into the same database in the same local transaction:

  • The business change (e.g. the order row).
  • A row in an outbox table describing the event.

A separate process then reads unprocessed outbox rows and delivers them, marking each as completed. Because the outbox write shares the business transaction, an event is recorded if and only if the business change committed.

Spring Modulith's Event Publication Registry

Spring Modulith ships a ready-made outbox: the Event Publication Registry. When an event has a transactional listener (annotated with @ApplicationModuleListener), Modulith automatically:

  • Writes an event publication row before the listener runs.
  • Marks it completed when the listener finishes successfully.
  • Leaves it incomplete if the listener throws — so it can be retried.

You enable it by adding the starter and a persistence module. The registry persists publications in a table such as event_publication.

<dependency>
  <groupId>org.springframework.modulith</groupId>
  <artifactId>spring-modulith-starter-jpa</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.modulith</groupId>
  <artifactId>spring-modulith-events-jpa</artifactId>
</dependency>

@ApplicationModuleListener

The key annotation is @ApplicationModuleListener. It is a composed annotation that combines three behaviors:

  • @Async — the listener runs on a separate thread, decoupling modules.
  • @Transactional(propagation = REQUIRES_NEW) — the listener runs in its own transaction.
  • @TransactionalEventListener(phase = AFTER_COMMIT) — it fires only after the publisher's transaction commits.

Combined with the registry on the classpath, every event handled by such a listener gets an outbox entry. If the listener fails, the publication stays incomplete and survives restarts.

@Component
class OrderNotifications {

    @ApplicationModuleListener
    void on(OrderCompleted event) {
        // runs async, in a NEW transaction, after the publisher committed
        emailService.sendConfirmation(event.orderId());
    }
}

Publishing the Event

The publishing side stays simple. Inside a normal @Transactional service method you call ApplicationEventPublisher.publishEvent(...). Spring Modulith intercepts the publication and, because there is a transactional module listener, writes the outbox row in the same transaction as your business change.

Use immutable Java records for events — they are concise, serializable, and clearly value-typed.

public record OrderCompleted(String orderId) {}

@Service
class OrderService {

    private final OrderRepository orders;
    private final ApplicationEventPublisher events;

    OrderService(OrderRepository orders, ApplicationEventPublisher events) {
        this.orders = orders;
        this.events = events;
    }

    @Transactional
    public void complete(String orderId) {
        Order order = orders.findById(orderId).orElseThrow();
        order.markCompleted();          // business change
        events.publishEvent(new OrderCompleted(orderId)); // outbox row, same tx
    }
}

How the Atomicity Works

Here is the crucial sequence that guarantees delivery:

  • Your complete() method opens a transaction and changes the order.
  • publishEvent causes Modulith to INSERT an incomplete event_publication row in that same transaction.
  • The transaction commits — order change and outbox row land together, atomically.
  • After commit, the @ApplicationModuleListener runs in a new transaction.
  • On success, the publication is marked completed.

If the JVM crashes between commit and listener success, the row is still incomplete in the database, ready to be republished. No event is ever silently dropped.

The event_publication Table

The JPA persistence module stores publications in a table. Each row identifies a serialized event and its target listener, plus timestamps. Knowing the schema helps you reason about retries and monitoring.

  • id — UUID primary key.
  • listener_id — fully-qualified listener method that must handle it.
  • event_type + serialized_event — the event payload (JSON by default via Jackson).
  • publication_date — when it was created.
  • completion_date — NULL while incomplete; set when the listener succeeds.

A row with completion_date IS NULL is an outstanding event awaiting (re)delivery.

CREATE TABLE event_publication (
  id UUID NOT NULL,
  listener_id TEXT NOT NULL,
  event_type TEXT NOT NULL,
  serialized_event TEXT NOT NULL,
  publication_date TIMESTAMP WITH TIME ZONE NOT NULL,
  completion_date TIMESTAMP WITH TIME ZONE,
  PRIMARY KEY (id)
);

Republishing on Startup

Incomplete publications are useless unless something retries them. Spring Modulith can republish outstanding events on application startup, which recovers from crashes that happened mid-delivery.

Enable it in application.properties:

  • spring.modulith.republish-outstanding-events-on-restart=true

On boot, Modulith reads all incomplete event_publication rows and re-invokes their listeners. Because listeners should be idempotent, replaying a partially-processed event is safe.

# application.properties
spring.modulith.republish-outstanding-events-on-restart=true

# optional: also serialize events as JSON columns you can query
spring.modulith.events.jdbc.schema-initialization.enabled=true

Idempotent Listeners

Because an event may be delivered more than once (retry after a crash, or scheduled resubmission), the at-least-once guarantee forces your listeners to be idempotent. Processing the same event twice must produce the same end state as processing it once.

Common techniques:

  • Use a natural business key (the order id) and check whether the side effect already happened.
  • Track processed event ids in a dedup table with a unique constraint.
  • Make the operation naturally idempotent (UPSERT, or set-to-state instead of increment).
@Component
class InventoryAdjuster {

    private final ProcessedEventRepository processed;

    @ApplicationModuleListener
    void on(OrderCompleted event) {
        // skip if we've already handled this exact event
        if (!processed.markIfNew(event.orderId())) {
            return;
        }
        inventory.release(event.orderId());
    }
}

Scheduled Resubmission of Incomplete Events

Startup republishing only helps when you restart. For long-running services you also want periodic recovery of stuck publications (e.g. a listener that threw a transient error). Modulith offers a completion / resubmission scheduler.

  • spring.modulith.events.completion-mode — controls whether completed rows are deleted, archived, or updated.
  • Enable a recurring resubmission so incomplete events older than a threshold are retried automatically.

Combined with idempotency, this turns the outbox into a self-healing delivery channel without a separate message broker.

# application.properties
spring.modulith.events.republish-outstanding-events-on-restart=true
spring.modulith.events.completion-mode=update

# resubmit publications still incomplete after this interval
spring.modulith.events.republish-outstanding-events.interval=PT10M

From Outbox to External Broker

The same registry bridges to external messaging. Spring Modulith provides externalization modules (Kafka, RabbitMQ, AMQP, SQS, etc.). You annotate an event with @Externalized, and a transactional listener publishes it to the broker — backed by the very same outbox.

This means the at-least-once guarantee extends across process boundaries: the broker send is itself an event publication that is only marked complete once the message is accepted by the broker.

import org.springframework.modulith.events.Externalized;

@Externalized("orders.completed::#{orderId()}")
public record OrderCompleted(String orderId) {}

// add: spring-modulith-events-kafka
// spring.modulith routes the event to topic "orders.completed"
// keyed by orderId, only after the publishing tx commits

Quick Check

Test your understanding of the transactional outbox guarantee.

Recap

You learned how to guarantee event delivery in Spring Modulith using the transactional outbox pattern:

  • The Event Publication Registry persists an event_publication row in the same transaction as your business change — solving the dual-write problem.
  • @ApplicationModuleListener = async + REQUIRES_NEW transaction + AFTER_COMMIT, so listeners run after the publisher commits and get their own outbox entry.
  • A publication is incomplete until its listener succeeds (completion_date IS NULL); failures leave it for retry.
  • Republish on restart and scheduled resubmission recover stuck events — making delivery at-least-once.
  • Because delivery is at-least-once, listeners must be idempotent.
  • @Externalized bridges the same outbox to Kafka/RabbitMQ/SQS for cross-process guarantees.
Gratuit pour commencer

Apprends Java avec un tuteur IA — gratuit

Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.

Cours
21
Leçons
84

Questions Fréquemment Posées

La leçon « Publication transactionnelle d’événements et boîte de sortie » est-elle gratuite ?

Oui — le texte complet de « Publication transactionnelle d’événements et boîte de sortie » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Boot 4 Complete Guide, passe à CoddyKit PRO. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Publication transactionnelle d’événements et boîte de sortie » ?

Garantissez la livraison des événements avec le registre de publication des événements et le modèle de boîte de sortie transactionnelle. Tu pratiques Spring Boot 4 Complete Guide avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Spring Boot 4 Complete Guide ?

Aucune expérience préalable n'est requise. Spring Boot 4 Complete Guide sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « Publication transactionnelle d’événements et boîte de sortie » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Spring Boot 4 Complete Guide ?

Oui. Chaque leçon Spring Boot 4 Complete Guide inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Modules d’application et vérification des frontières
  2. Événements internes de l’application et écouteurs
  3. Publication transactionnelle d’événements et boîte de sortie
  4. Tests d’intégration des modules et scénarios
← Retour à Spring Boot 4 Complete Guide