Consider the following Kafka consumer code snippet in Java. What will be printed to the console?
Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "test-group"); 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("my-topic")); ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord<String, String> record : records) { System.out.println(record.key() + ":" + record.value()); } consumer.close();
Think about what happens if the topic has no messages ready during the poll.
The poll method waits up to the specified duration for messages. If no messages are available, it returns an empty ConsumerRecords object, so the loop prints nothing.
In Kafka consumer configuration, what is the role of the group.id property?
Think about how Kafka manages multiple consumers reading from the same topic.
The group.id identifies the consumer group. Kafka uses this to distribute partitions among consumers and track offsets for fault tolerance.
Examine the following Kafka consumer code snippet. Why does it throw a SerializationException at runtime?
Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "group1"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); // Missing value.deserializer configuration KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("topic1")); ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord<String, String> record : records) { System.out.println(record.key() + ":" + record.value()); } consumer.close();
Check the deserializer configurations carefully.
Kafka needs both key and value deserializers to convert bytes to objects. Missing value.deserializer causes a SerializationException when reading message values.
Which of the following code snippets correctly commits offsets synchronously after processing records?
Look for the method that commits offsets synchronously without parameters.
The commitSync() method commits offsets synchronously and throws exceptions on failure. The other methods are asynchronous or invalid.
Suppose a Kafka topic has 6 partitions and there are 3 consumers in the same consumer group subscribed to this topic. How many partitions will each consumer be assigned?
Think about how Kafka balances partitions among consumers in a group.
Kafka evenly distributes partitions among consumers in a group. With 6 partitions and 3 consumers, each gets 2 partitions.