You need to implement retry logic in Java for sending messages with KafkaProducer, retrying up to 3 times on network errors. Which code snippet correctly implements this?
hard🚀 Application Q8 of Q15
Kafka - with Java/Python
You need to implement retry logic in Java for sending messages with KafkaProducer, retrying up to 3 times on network errors. Which code snippet correctly implements this?
Dproducer.send(record).get(); // rely on Kafka's internal retries
Step-by-Step Solution
Solution:
Step 1: Understand retry requirements
Retries should occur only on retriable exceptions, with a maximum of 3 attempts.
Step 2: Analyze options
int retries = 0;
while (retries < 3) {
try {
producer.send(record).get();
break;
} catch (ExecutionException e) {
if (e.getCause() instanceof RetriableException) {
retries++;
} else {
throw e;
}
}
} correctly implements a loop with try-catch, checking for RetriableException cause and retrying accordingly.
Step 3: Evaluate other options
for (int i = 0; i < 3; i++) {
try {
producer.send(record);
break;
} catch (Exception e) {
Thread.sleep(1000);
}
} does not call get(), so exceptions may not be caught. try {
producer.send(record).get();
} catch (Exception e) {
producer.send(record).get();
} retries only once without loop. producer.send(record).get(); // rely on Kafka's internal retries relies solely on Kafka internal retries, which may not suffice.
Final Answer:
Option A implements correct retry logic with exception checking and loop -> Option A
Quick Check:
Retry on RetriableException with send().get() inside loop [OK]
Quick Trick:Retry send().get() on RetriableException up to 3 times [OK]
Common Mistakes:
MISTAKES
Not calling get() to detect send failures
Retrying on all exceptions indiscriminately
Ignoring maximum retry count
Master "with Java/Python" in Kafka
9 interactive learning modes - each teaches the same concept differently