Microservices tricky interview questions must know
1.You have two microservices, Order Service and Payment Service. When an order is created, the Order Service publishes an event to Kafka, and the Payment Service listens to that event. However, the payment service sometimes processes the message twice due to retries caused by consumer failure. How would you handle idempotency to prevent duplicate processing in Payment Service?
To handle idempotency in Payment Service:
- Generate a unique identifier for each event (like
orderIdorpaymentId) fromOrder Service. - Store processed events in a database (like Redis, MongoDB, or a relational DB). Each time the
Payment Servicereceives an event, it should check if the event ID has been processed before. - Use a transactional outbox pattern: Ensure that event consumption and processing are atomic. For example, store the event processing result and commit offsets in the same transaction, ensuring either both succeed or neither.
- Kafka consumer offsets: Use manual offset commits only after the payment processing is completed successfully.
public void processPayment(Event event) {
if (!eventRepository.existsById(event.getId())) {
try {
// process payment
paymentService.process(event.getPaymentInfo());
// Save the event as processed
eventRepository.save(new ProcessedEvent(event.getId()));
} catch (Exception e) {
// Handle exception…