Creación de consumidores de eventos idempotentes
Haga que los participantes de una saga de coreografía sean resistentes a eventos duplicados y desordenados mediante consumidores idempotentes, el patrón inbox y el patrón outbox.
Creación de consumidores de eventos idempotentes es una lección gratuita de Microservices Communication Patterns (Saga, Circuit Breaker) 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 Microservices Communication Patterns (Saga, Circuit Breaker), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Microservices Communication Patterns (Saga, Circuit Breaker) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Events Get Redelivered
In a choreography saga, services react to events from a broker. Brokers deliver at least once, so the same event can arrive twice — and sometimes out of order. Naive handlers double-charge or double-ship.
The Goal: Idempotent Consumers
An idempotent consumer can process the same event repeatedly with no extra effect. This is essential for correctness in any event-driven saga.
Track Processed Event Ids
Give every event a unique id. Before handling, check whether you have already processed that id; if so, skip and acknowledge.
if (inbox.exists(event.id())) { ack(); return; }
handle(event);
inbox.save(event.id());
ack();The Inbox Pattern
The inbox pattern stores processed event ids in a table inside the same database transaction as the business change. Insert + work commit together, so a redelivery is rejected by the unique constraint.
BEGIN;
INSERT INTO inbox(event_id) VALUES (?); -- unique
UPDATE orders SET status = 'PAID' WHERE id = ?;
COMMIT;Why Atomicity Is Key
If you ack the event but crash before committing the business change, the work is lost. Doing both in one transaction guarantees they succeed or fail together.
The Dual-Write Problem
A participant must often update its DB and publish a new event. Doing these as two separate calls risks one succeeding and the other failing — the classic dual-write problem.
The Outbox Pattern
The outbox pattern solves it: write the outgoing event into an outbox table in the same transaction as the business change. A separate relay publishes from the outbox to the broker.
BEGIN;
UPDATE orders SET status = 'SHIPPED' WHERE id = ?;
INSERT INTO outbox(payload) VALUES (?);
COMMIT;Relaying the Outbox
A poller or change-data-capture (CDC) tool like Debezium reads new outbox rows and publishes them, then marks them sent. Publishing is at-least-once, so downstream consumers must be idempotent too.
Handling Out-of-Order Events
Events may arrive out of order. Use version numbers or sequence ids and ignore stale events, or design handlers that converge to the correct state regardless of order.
if (event.version() <= current.version()) return; // staleCompensations Must Be Idempotent Too
When a saga fails, compensating events also flow through the broker and can be redelivered. A compensation (e.g. refund) must itself be idempotent, or you refund twice.
Putting It Together
A robust choreography participant: consume via the inbox (dedup), do work and write the outbox in one transaction, relay the outbox to the broker, and make every handler — including compensations — idempotent.
Quick Check
Test your event-consumer knowledge.
Recap
You hardened choreography consumers:
- Brokers deliver at-least-once, so events repeat and may reorder
- Idempotent consumers process duplicates safely
- The inbox pattern dedups within the business transaction
- The outbox pattern solves the dual-write problem; a relay/CDC publishes it
- Handle out-of-order events and make compensations idempotent too
Aprende Microservices Communication Patterns (Saga, Circuit Breaker) con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 48
Preguntas frecuentes
¿La lección «Creación de consumidores de eventos idempotentes» es gratis?
Sí — el texto completo de «Creación de consumidores de eventos idempotentes» 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 Microservices Communication Patterns (Saga, Circuit Breaker), actualiza a CoddyKit PRO. El curso de Microservices Communication Patterns (Saga, Circuit Breaker) incluye 4 lecciones en total.
¿Qué aprenderé en «Creación de consumidores de eventos idempotentes»?
Haga que los participantes de una saga de coreografía sean resistentes a eventos duplicados y desordenados mediante consumidores idempotentes, el patrón inbox y el patrón outbox. Practicas Microservices Communication Patterns (Saga, Circuit Breaker) 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 Microservices Communication Patterns (Saga, Circuit Breaker)?
No se requiere experiencia previa. Microservices Communication Patterns (Saga, Circuit Breaker) 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 «Creación de consumidores de eventos idempotentes»?
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 Microservices Communication Patterns (Saga, Circuit Breaker)?
Sí. Cada lección de Microservices Communication Patterns (Saga, Circuit Breaker) 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
- Diseño de Sagas basadas en eventos
- Bus de eventos y brokers de mensajes
- Gestión de compensaciones mediante eventos
- Creación de consumidores de eventos idempotentes