El patrón Transactional Outbox
Aprenda cómo el patrón transactional outbox conecta de forma fiable una transacción de base de datos con la publicación en Kafka, evitando inconsistencias de escritura dual en Spring Boot.
El patrón Transactional Outbox es una lección gratuita de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Advanced Spring Boot 4: Event-Driven Architecture (Kafka), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Dual-Write Problem
A common bug: a service updates its database and publishes a Kafka event in two separate operations. If one succeeds and the other fails, the system becomes inconsistent.
The transactional outbox pattern eliminates this risk.
Core Idea
Instead of publishing directly, write the event into an outbox table within the same database transaction as your business change.
A separate process then reads the outbox and publishes to Kafka.
The Outbox Table
The outbox table stores serialized events plus metadata.
CREATE TABLE outbox (
id UUID PRIMARY KEY,
aggregate_type VARCHAR(255),
aggregate_id VARCHAR(255),
event_type VARCHAR(255),
payload JSONB,
created_at TIMESTAMP DEFAULT now(),
published BOOLEAN DEFAULT false
);Writing in One Transaction
Both the domain entity and the outbox row are saved inside one @Transactional method, so they commit or roll back together.
@Transactional
public void placeOrder(Order order) {
orderRepository.save(order);
outboxRepository.save(OutboxEvent.from(order));
}Atomicity Guarantee
Because both writes share the database transaction, there is no window where the order exists without its event recorded. This is the key correctness property.
The Relay Process
A background relay polls unpublished outbox rows and sends them to Kafka, marking them published on success.
@Scheduled(fixedDelay = 500)
public void relay() {
for (OutboxEvent e : outboxRepository.findUnpublished()) {
kafkaTemplate.send(e.getTopic(), e.getPayload());
e.markPublished();
}
}At-Least-Once Publishing
If the relay crashes after sending but before marking published, the event is sent again. Consumers must therefore be idempotent, often using the event id as a dedup key.
Change Data Capture Alternative
Instead of polling, tools like Debezium tail the database transaction log and stream outbox inserts to Kafka automatically — lower latency and no polling load.
Cleaning Up the Outbox
Periodically delete or archive published rows to keep the table small and queries fast.
DELETE FROM outbox WHERE published = true AND created_at < now() - INTERVAL '7 days';When to Use It
Use the outbox when you must keep a database state change and an event publication consistent. It is simpler and more portable than spanning a Kafka transaction across an external database.
Putting It Together
The outbox pattern turns two unreliable writes into one atomic database commit plus a reliable relay. Combine it with idempotent consumers for end-to-end consistency.
Quick Check
Test your understanding of the outbox pattern.
Recap
You learned the transactional outbox pattern.
- Avoids dual-write inconsistency by using one DB transaction.
- An outbox table stores pending events.
- A relay (polling or CDC) publishes to Kafka.
- Consumers must be idempotent due to at-least-once delivery.
Preguntas frecuentes
¿La lección «El patrón Transactional Outbox» es gratis?
Sí — el texto completo de «El patrón Transactional Outbox» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Advanced Spring Boot 4: Event-Driven Architecture (Kafka), actualiza a CoddyKit PRO. El curso de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) incluye 4 lecciones en total.
¿Qué aprenderé en «El patrón Transactional Outbox»?
Aprenda cómo el patrón transactional outbox conecta de forma fiable una transacción de base de datos con la publicación en Kafka, evitando inconsistencias de escritura dual en Spring Boot. Practicas Advanced Spring Boot 4: Event-Driven Architecture (Kafka) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?
No se requiere experiencia previa. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «El patrón Transactional Outbox»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?
Sí. Cada lección de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Comprensión de las transacciones de Kafka
- Implementación de productores transaccionales
- Semántica de procesamiento exactamente una vez
- El patrón Transactional Outbox