Java producer client in Kafka - Time & Space Complexity
When sending messages with a Java Kafka producer, it is important to understand how the time to send grows as the number of messages increases.
We want to know how the work done changes when we produce more messages.
Analyze the time complexity of the following 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<String, String> producer = new KafkaProducer<>(props);
for (int i = 0; i < n; i++) {
producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), "message-" + i));
}
producer.close();
This code creates a Kafka producer and sends n messages to a topic in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sending a message with
producer.send()inside a loop. - How many times: Exactly
ntimes, once per message.
Each message send takes roughly the same amount of time, so the total work grows directly with the number of messages.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sends |
| 100 | 100 sends |
| 1000 | 1000 sends |
Pattern observation: Doubling the number of messages doubles the total sending work.
Time Complexity: O(n)
This means the time to send messages grows linearly with the number of messages you want to send.
[X] Wrong: "Sending multiple messages at once is always constant time because the producer batches them automatically."
[OK] Correct: While batching helps, each message still adds work, so total time grows with the number of messages, not stays the same.
Understanding how sending messages scales helps you design efficient data pipelines and shows you can reason about performance in real systems.
"What if we used asynchronous sends with callbacks instead of synchronous sends? How would the time complexity change?"