Kafka typically delivers at least once: after a consumer crash or rebalance, records whose offsets were not committed are processed again. Idempotency makes reprocessing harmless. 1. Stable event IDs and keys - Producers include a unique eventId in every event (often from the outbox table) and use the orderId as the record key, so all events for an order go to the same partition and stay ordered. - Enable producer idempotence (enable.idempotence=true, the default in modern clients) to avoid duplicates caused by producer retries. 2. Deduplication with a processed-events table (inbox) @KafkaListener(topics = "payments") @Transactional public void onPaymentCaptured(PaymentCaptured event) { if (processedEvents.existsById(event.eventId())) return; // duplicate orderService.markPaid(event.orderId(), event.paymentId()); processedEvents.save(new ProcessedEvent(event.eventId(), Instant.now())); } - The business change and the processed-event insert happen in one database transaction. A unique constraint on eventId protects against two concurrent deliveries. - Commit Kafka offsets only after the database transaction succeeds (Spring Kafka commits after the listener returns with the default AckMode.BATCH or RECORD settings). 3. Naturally idempotent operations - Conditional state transitions: UPDATE orders SET status = 'PAID' WHERE id = ? AND status = 'PENDING'. - Upserts, and "set to value" instead of "add amount". - Version checks so older events do not overwrite newer state (store the last processed sequence per order). 4. Ordering and out-of-order events - Same key, same partition gives ordering per order, but retries with separate retry topics can reorder events. Handle missing prerequisites by retrying later or parking the event. 5. Error handling - Spring Kafka's DefaultErrorHandler with exponential backoff for transient errors, and a DeadLetterPublishingRecoverer to send poison messages to a dead-letter topic after N attempts. - Classify non-retryable exceptions (validation or deserialisation errors) to skip retries. - Monitor consumer lag and DLT volume. 6. Exactly-once semantics — when relevant - Kafka transactions provide exactly-once for read-process-write pipelines entirely within Kafka (Kafka Streams with processing.guarantee=exactly_once_v2). They do not cover side effects in external systems such as databases or payment providers, so the inbox pattern is still needed there. 7. External side effects - Pass idempotency keys to payment providers and email services so retries do not repeat charges or messages. Clean up processed-event records after a retention window longer than the maximum redelivery period.
Ravindra Wadile · · 0 likes