Bird
Raised Fist0

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?
Aint retries = 0; while (retries < 3) { try { producer.send(record).get(); break; } catch (ExecutionException e) { if (e.getCause() instanceof RetriableException) { retries++; } else { throw e; } } }
Bfor (int i = 0; i < 3; i++) { try { producer.send(record); break; } catch (Exception e) { Thread.sleep(1000); } }
Ctry { producer.send(record).get(); } catch (Exception e) { producer.send(record).get(); }
Dproducer.send(record).get(); // rely on Kafka's internal retries
Step-by-Step Solution
Solution:
  1. Step 1: Understand retry requirements

    Retries should occur only on retriable exceptions, with a maximum of 3 attempts.
  2. 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.
  3. 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.
  4. Final Answer:

    Option A implements correct retry logic with exception checking and loop -> Option A
  5. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kafka Quizzes