Создание идемпотентных потребителей событий
Защитите участников саги-хореографии от дублирующихся событий и событий не по порядку с помощью идемпотентных потребителей, шаблонов Inbox и Outbox.
«Создание идемпотентных потребителей событий» — бесплатный урок Microservices Communication Patterns (Saga, Circuit Breaker) на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Microservices Communication Patterns (Saga, Circuit Breaker), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Microservices Communication Patterns (Saga, Circuit Breaker) содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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
Изучай Microservices Communication Patterns (Saga, Circuit Breaker) с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Создание идемпотентных потребителей событий» бесплатный?
Да — полный текст урока «Создание идемпотентных потребителей событий» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Microservices Communication Patterns (Saga, Circuit Breaker), подпишись на CoddyKit PRO. Курс Microservices Communication Patterns (Saga, Circuit Breaker) содержит 4 уроков всего.
Чему я научусь в уроке «Создание идемпотентных потребителей событий»?
Защитите участников саги-хореографии от дублирующихся событий и событий не по порядку с помощью идемпотентных потребителей, шаблонов Inbox и Outbox. Ты практикуешь Microservices Communication Patterns (Saga, Circuit Breaker) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Microservices Communication Patterns (Saga, Circuit Breaker)?
Предыдущий опыт не требуется. Microservices Communication Patterns (Saga, Circuit Breaker) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Создание идемпотентных потребителей событий»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Microservices Communication Patterns (Saga, Circuit Breaker)?
Да. Каждый урок Microservices Communication Patterns (Saga, Circuit Breaker) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Проектирование Саг на основе событий
- Шина событий и брокеры сообщений
- Обработка компенсаций с помощью событий
- Создание идемпотентных потребителей событий