enable.idempotence=true and retries=3. If the producer sends a message and a transient network error occurs causing a retry, what will be the effect on the topic?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"); props.put("enable.idempotence", "true"); props.put("retries", 3); KafkaProducer<String, String> producer = new KafkaProducer<>(props); ProducerRecord<String, String> record = new ProducerRecord<>("my-topic", "key1", "value1"); producer.send(record); producer.close();
When enable.idempotence=true, Kafka producer assigns a unique sequence number to each message. If a retry occurs, the broker recognizes duplicates and prevents them from being written multiple times. This guarantees exactly-once delivery despite retries.
Retries can cause the same message to be sent multiple times. Idempotency ensures that even if the producer retries, the broker will write the message only once, preventing duplicates.
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"); props.put("enable.idempotence", "true"); props.put("retries", -1); KafkaProducer<String, String> producer = new KafkaProducer<>(props); ProducerRecord<String, String> record = new ProducerRecord<>("my-topic", "key1", "value1"); producer.send(record); producer.close();
The retries configuration must be zero or a positive integer. Setting it to -1 is invalid and causes an exception when creating the producer.
enable.idempotence=true sending two messages with the same value but different keys. If a retry occurs for one message, what will be the result in the topic?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"); props.put("enable.idempotence", "true"); props.put("retries", 3); KafkaProducer<String, String> producer = new KafkaProducer<>(props); producer.send(new ProducerRecord<>("my-topic", "key1", "value")); producer.send(new ProducerRecord<>("my-topic", "key2", "value")); producer.close();
Idempotency prevents duplicates by tracking sequence numbers per partition and producer. Messages with different keys are treated as separate records. Even if retries occur, each message is delivered once.
Kafka uses a combination of a unique producer ID and a monotonically increasing sequence number per partition. When retries happen, the broker compares sequence numbers to detect duplicates and only writes the first occurrence, ensuring exactly-once delivery.