Apache Kafka is a distributed event streaming platform capable of handling trillions of events a day. To effectively design and scale Kafka-based applications, it is essential to understand how Topics, Partitions, and Consumer Groups interact.
1. Kafka Topics
A topic is a logical category or feed name to which records are published. Topics in Kafka are always multi-subscriber; that is, a topic can have zero, one, or many consumers that subscribe to the data written to it.
2. Partitions for Scalability
Topics are divided into partitions, which are the fundamental unit of parallelism and scalability in Kafka. Each partition is an ordered, immutable sequence of records that is continually appended to.
- Ordering: Messages within a single partition are strictly ordered by their offset.
- Distribution: Partitions are distributed across brokers in a Kafka cluster.
3. Consumer Groups
A consumer group consists of one or more consumers that work together to consume messages from a set of partitions. Kafka automatically rebalances partition assignments among consumers in the group when consumers join or leave.
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "user-analytics-group");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("user-events"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.printf("Partition = %d, Offset = %d, Key = %s, Value = %s%n",
record.partition(), record.offset(), record.key(), record.value());
}
}Key Takeaways
If you have more consumers than partitions in a single consumer group, the extra consumers will remain idle. To increase throughput, ensure your topic has enough partitions to distribute load across multiple consumer instances.