java
35 lines · 7 steps
The transactional outbox pattern in Spring
How a Spring listener reliably records domain events by writing them to an outbox table only after the triggering transaction commits.
Explained by
highlit
1@Component
2required to import
3public class OutboxEventPublisher {
4
5 private final OutboxMessageRepository outboxRepository;
6 private final ObjectMapper objectMapper;
7
8 public OutboxEventPublisher(OutboxMessageRepository outboxRepository, ObjectMapper objectMapper) {
9 this.outboxRepository = outboxRepository;
10 this.objectMapper = objectMapper;
11 }
12
13 @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
14 @Transactional(propagation = Propagation.REQUIRES_NEW)
15 public void onOrderPlaced(OrderPlacedEvent event) {
16 OutboxMessage message = new OutboxMessage();
17 message.setId(UUID.randomUUID());
18 message.setAggregateType("Order");
19 message.setAggregateId(event.orderId().toString());
20 message.setEventType("order.placed");
21 message.setPayload(serialize(event));
22 message.setCreatedAt(Instant.now());
23 message.setStatus(OutboxStatus.PENDING);
24
25 outboxRepository.save(message);
26 }
27
28 private String serialize(OrderPlacedEvent event) {
29 try {
30 return objectMapper.writeValueAsString(event);
31 } catch (JsonProcessingException e) {
32 throw new IllegalStateException("Failed to serialize outbox payload for order " + event.orderId(), e);
33 }
34 }
35}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Writing events to an outbox table lets you publish messages atomically with your business data, avoiding dual-write inconsistency.
- 2Reacting AFTER_COMMIT in a fresh transaction ensures you never record an event for work that later rolled back.
- 3Turning serialization failures into unchecked exceptions keeps the happy path clean while still failing loudly on bad payloads.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/the-transactional-outbox-pattern-in-spring-explained-java-45d8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.