DevLearn
Local Development

Build Kafka Applications

Learn to build production-ready Java applications with Kafka using the native Java client and Spring Boot integration.

Kafka Producer

Send messages to Kafka topics with reliability guarantees

// Kafka Producer Example (Java)
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("acks", "all");
props.put("retries", 3);
props.put("enable.idempotence", "true");

Producer<String, String> producer = new KafkaProducer<>(props);

ProducerRecord<String, String> record = new ProducerRecord<>(
    "orders",
    "order-key",
    "{\"orderId\": 123, \"amount\": 99.99}"
);

producer.send(record, (metadata, exception) -> {
    if (exception == null) {
        System.out.println("Sent to partition " + metadata.partition());
    } else {
        exception.printStackTrace();
    }
});

producer.close();

Key Producer configs

  • acks=all - Wait for all replicas
  • retries=3 - Auto retry on failure
  • enable.idempotence=true - No duplicates
  • compression.type=lz4 - Reduce size

Best Practices

  • Use async send with callbacks
  • Use idempotent producer
  • Batch messages when possible
  • Handle backpressure