El patrón Outbox para publicar eventos de forma fiable
Aprenda cómo el patrón transactional outbox garantiza la coherencia entre las escrituras en la base de datos y los eventos de Kafka, evitando la pérdida de datos por escritura dual.
El patrón Outbox para publicar eventos de forma fiable es una lección gratuita de Apache Kafka & Stream Processing Fundamentals 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 Apache Kafka & Stream Processing Fundamentals, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Apache Kafka & Stream Processing Fundamentals 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 service often needs to update its database and publish a Kafka event. Doing both as separate steps risks one succeeding and the other failing.
This dual-write problem leaves the database and Kafka inconsistent.
Why You Can't Just Try-Catch
If you commit the DB then publish, a crash in between loses the event.
If you publish then commit, a failed commit emits a phantom event. There is no atomic transaction spanning a relational DB and Kafka by default.
The Outbox Idea
The outbox pattern records the event in the same database transaction as the business change, in a dedicated outbox table.
One atomic commit now contains both the state change and the intent to publish.
The Outbox Table
A typical outbox schema captures everything needed to build the Kafka record.
CREATE TABLE outbox (
id UUID PRIMARY KEY,
aggregate_type VARCHAR,
aggregate_id VARCHAR,
event_type VARCHAR,
payload JSONB,
created_at TIMESTAMP DEFAULT now()
);Writing Atomically
Within one transaction, write the business row and the outbox row together.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'a1';
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload)
VALUES (gen_random_uuid(), 'account', 'a1', 'DebitMade',
'{"amount":100}');
COMMIT;Relaying to Kafka
A separate relay reads new outbox rows and publishes them to Kafka.
Two common approaches: poll the table, or use Change Data Capture to stream the inserts.
CDC + Debezium
Debezium has a dedicated Outbox Event Router SMT. It tails the DB transaction log, picks up outbox inserts, and routes each to the right Kafka topic — no polling, low latency.
At-Least-Once Delivery
The relay guarantees at-least-once delivery: an event is never lost, but it may be published more than once after a crash and retry.
Therefore consumers must be idempotent.
Idempotent Consumers
Use the event id (or aggregate id + version) to deduplicate downstream.
// Pseudocode
if (alreadyProcessed(event.id)) {
return; // skip duplicate
}
apply(event);
markProcessed(event.id);Ordering & Partitioning
To preserve per-aggregate order, use the aggregate_id as the Kafka message key.
All events for one account then land on the same partition and are consumed in order.
Pros & Cons
Pros: no dual-write loss, works with any DB, decouples publishing.
Cons: extra table and relay, at-least-once duplicates, slight latency. Still the standard solution for reliable event publishing.
Quick Check
Test your understanding of the outbox pattern.
Recap
You learned the outbox pattern.
- Solves the dual-write problem by committing state + event atomically.
- A relay (polling or CDC/Debezium) publishes outbox rows to Kafka.
- Delivery is at-least-once, so consumers must be idempotent.
- Key by aggregate id to preserve ordering.
Preguntas frecuentes
¿La lección «El patrón Outbox para publicar eventos de forma fiable» es gratis?
Sí — el texto completo de «El patrón Outbox para publicar eventos de forma fiable» 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 Apache Kafka & Stream Processing Fundamentals, actualiza a CoddyKit PRO. El curso de Apache Kafka & Stream Processing Fundamentals incluye 4 lecciones en total.
¿Qué aprenderé en «El patrón Outbox para publicar eventos de forma fiable»?
Aprenda cómo el patrón transactional outbox garantiza la coherencia entre las escrituras en la base de datos y los eventos de Kafka, evitando la pérdida de datos por escritura dual. Practicas Apache Kafka & Stream Processing Fundamentals 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 Apache Kafka & Stream Processing Fundamentals?
No se requiere experiencia previa. Apache Kafka & Stream Processing Fundamentals 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 Outbox para publicar eventos de forma fiable»?
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 Apache Kafka & Stream Processing Fundamentals?
Sí. Cada lección de Apache Kafka & Stream Processing Fundamentals 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
- Event sourcing con Kafka
- Captura de cambios de datos (CDC)
- Patrones de comunicación entre microservicios
- El patrón Outbox para publicar eventos de forma fiable