A Kafka producer is a client that publishes records to a topic by connecting to the cluster, serializing the key and value, and sending the record to the broker that leads the target partition.
Key Points: • The producer determines the target partition either from an explicit partition number, a hash of the record key, or round-robin/sticky assignment when no key is given. • Records with the same key always land on the same partition, which preserves ordering for that key. • The producer batches records per partition to improve throughput and can be tuned with batch.size and linger.ms. • The acks setting controls durability by defining how many replicas must confirm receipt before the send is considered successful. • Producers can be synchronous (blocking on the returned Future) or asynchronous (using a callback) depending on how much latency the application can tolerate.
Example: A KafkaProducer sending a customer's order events with the customer ID as the key ensures every event for that customer is appended to the same partition in the order it was sent, which downstream consumers can rely on.
Code Example:
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<String, String> producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<>("orders", "customer-123", "order-placed"));
producer.close();Interview Tip: A concise interview answer is:
"A producer connects to the Kafka cluster, serializes the record, and sends it to the leader broker for a partition chosen either explicitly or by hashing the record key, which is what guarantees ordering for records sharing the same key."