Consider this Kafka producer code in Java that sends a message with a key and value. What will be printed by the callback?
ProducerRecord<String, String> record = new ProducerRecord<>("topic1", "key1", "value1"); producer.send(record, (metadata, exception) -> { if (exception == null) { System.out.println("Sent to partition: " + metadata.partition() + ", offset: " + metadata.offset()); } else { System.out.println("Error sending message"); } });
The key determines the partition. If the topic has one partition, the message goes there with offset 0.
The producer sends the message with key "key1" to partition 0 (assuming one partition). The callback prints the partition and offset, which start at 0.
In Kafka, what does the message key control?
Think about how Kafka distributes messages across partitions.
The message key is used by Kafka's partitioner to decide which partition the message goes to, ensuring messages with the same key go to the same partition.
Given this Kafka producer code snippet, what will be the effect on partitioning?
ProducerRecord<String, String> record = new ProducerRecord<>("topic1", null, "value1"); producer.send(record);
What does Kafka do when the key is missing?
If the key is null, Kafka uses a round-robin or random partitioner to distribute messages evenly across partitions.
A Kafka consumer tries to filter messages by key but gets no results. What is the likely cause?
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000)); for (ConsumerRecord<String, String> record : records) { if (record.key() != null && record.key().equals("key1")) { System.out.println(record.value()); } }
Check if all messages have keys before calling equals.
If some messages have null keys, calling equals on null causes NullPointerException and no messages are printed.
You want to guarantee that all messages with the same key are processed in the order they were sent. Which Kafka feature helps achieve this?
Think about how Kafka guarantees order within partitions.
Kafka guarantees message order only within a partition. Using the same key ensures messages go to the same partition and are processed in order.