Bird
Raised Fist0

What is wrong with this Kafka producer code snippet?

medium📝 Debug Q7 of Q15
Kafka - with Java/Python
What is wrong with this Kafka producer code snippet?
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer producer = new KafkaProducer<>(props);
ProducerRecord record = new ProducerRecord<>("topic", null, "value");
producer.send(record);
producer.close();
ASending a record with null key is allowed and no error occurs
BNull key causes NullPointerException
CProducerRecord constructor is incorrect
DProducer must not be closed immediately after send
Step-by-Step Solution
Solution:
  1. Step 1: Check if null keys are allowed

    Kafka allows null keys in ProducerRecord; it means no key is assigned.
  2. Step 2: Verify other options

    Constructor is correct; closing producer after send is valid (send is async but close flushes).
  3. Final Answer:

    Sending a record with null key is allowed and no error occurs -> Option A
  4. Quick Check:

    Null keys allowed in ProducerRecord [OK]
Quick Trick: Null keys are valid in Kafka producer records [OK]
Common Mistakes:
MISTAKES
  • Assuming null key causes exceptions
  • Confusing constructor parameters
  • Thinking close() must wait for send callback

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kafka Quizzes