As asked
Write a Java method that creates a KafkaConsumer, subscribes to a topic called 'orders', polls in a loop, processes each record, commits offsets manually, and shuts down cleanly when a shutdown flag is set. Handle the case where commitSync may fail.
Sample answer outline
The solution should configure consumer with bootstrap.servers, group.id, key/value deserializers, and enable.auto.commit=false. The poll loop should call commitSync() inside a try-catch that logs errors without crashing the loop. A volatile boolean or CountDownLatch should signal shutdown, and the shutdown path should call consumer.wakeup() from another thread then call commitSync one final time in a finally block. The consumer must be closed in a finally block.
Reference implementation (java)
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "order-consumer");
props.put("enable.auto.commit", "false");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("orders"));
volatile boolean running = true;
try {
while (running) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
process(record);
}
// TODO: commitSync here
}
} finally {
consumer.close();
}Expect these follow-ups
- How would you add per-partition offset tracking to commit only successfully processed offsets?
- What is the difference between commitSync and commitAsync in a shutdown path?