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
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 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.