Bird
0
0

You want to send a message to a Kafka topic and then immediately consume that same message in Python using kafka-python. Which approach ensures you consume the first message you just produced?

hard📝 Application Q8 of 15
Kafka - Basics and Event Streaming
You want to send a message to a Kafka topic and then immediately consume that same message in Python using kafka-python. Which approach ensures you consume the first message you just produced?
ASend the message, call <code>producer.flush()</code>, then create a consumer with <code>auto_offset_reset='earliest'</code> and read one message.
BSend the message and immediately create a consumer without flushing the producer; consume messages from the latest offset.
CCreate a consumer first, then send the message and consume without flushing the producer.
DSend the message, close the producer, then create a consumer with <code>auto_offset_reset='latest'</code> and read messages.
Step-by-Step Solution
Solution:
  1. Step 1: Ensure message is sent

    Calling producer.flush() guarantees the message is actually sent to Kafka before consuming.
  2. Step 2: Configure consumer offset

    Setting auto_offset_reset='earliest' ensures the consumer reads from the beginning if no committed offset exists.
  3. Step 3: Consume the first message

    Reading one message after these steps will retrieve the message just produced.
  4. Step 4: Eliminate incorrect options

    Send the message and immediately create a consumer without flushing the producer; consume messages from the latest offset. risks missing the message due to no flush and reading from latest offset. Create a consumer first, then send the message and consume without flushing the producer. consumes before producing, so no message is available. Send the message, close the producer, then create a consumer with auto_offset_reset='latest' and read messages. uses 'latest' offset, which may skip the message.
  5. Final Answer:

    Send message, flush producer, then consume from earliest offset. -> Option A
  6. Quick Check:

    Flush producer and set consumer to earliest offset [OK]
Quick Trick: Flush producer before consuming with 'auto_offset_reset=earliest' [OK]
Common Mistakes:
  • Not flushing producer before consuming
  • Using 'latest' offset causing missed messages
  • Starting consumer before producing message

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kafka Quizzes