What does "idempotency" mean in the context of events?
Idempotency in the context of events means that processing the same event several times produces the same result, without repeated side effects.
Why this is needed
In event-driven systems the same message can be delivered again, for example because of a network failure, a timeout, or a re-publication by the broker. If the consumer is not idempotent, a duplicate event can:
- create the order twice,
- charge the money twice,
- send the notification twice.
How it is achieved
- A unique event identifier (
event_id). Before processing, the system checks whether it was already processed. - Storing a history of processed events (a "processed_events" table).
- Checking the state before acting, for example "if the order is already paid, do not repeat it".
- Idempotent database operations:
INSERT ... ON CONFLICT DO NOTHING,UPSERT,SETinstead ofADD.
Example
The PaymentReceived event arrives twice.
The service checks payment_id in the table: if it was already processed, it simply ignores the duplicate.
Summary:
Idempotency protects an event-driven architecture from duplicate messages. It guarantees that even with redelivery, the result stays correct and the system stays consistent.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.