Sub topic 1
How Kafka Organizes Data: Topics, Partitions, and Offsets
Prerequisites
Assume you know Java, basic Spring Boot beans and dependency injection, Maven or Gradle, and publish/subscribe messaging. You should also be able to run Kafka locally.
Topics, Partitions, and Offsets
A topic is a named stream of records, such as orders. Kafka divides each topic into partitions. A partition is an ordered, append-only sequence of records.
Each record receives an offset, which is its position within that partition. Offsets start at zero and increase independently in each partition. Kafka preserves order within one partition, but not across the whole topic.
A record key influences partition selection. Using the same key, such as an order ID, normally sends related records to the same partition:
orders
├── partition 0: offset 0, offset 1
├── partition 1: offset 0, offset 1, offset 2
└── partition 2: offset 0Consumer Groups and Assignment
A consumer group is a set of consumers that cooperate to read a topic. Kafka assigns each partition to only one consumer within a group. Therefore, a group can process at most one consumer per partition at a time.
Two consumers in different groups each receive the records. Two consumers in the same group share the partitions. This supports independent applications and horizontal scaling.
Setting Up Spring Boot
Add the spring-kafka dependency. Then configure the broker and a consumer group in application.yml:
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: order-service
auto-offset-reset: earliestbootstrap-servers identifies Kafka. The group ID identifies the cooperating consumers. earliest tells a new group to read from the beginning when no offset exists.
Declaring Topics as Beans
Spring Kafka can create a topic through a NewTopic bean:
@Configuration
public class KafkaTopicConfig {
@Bean
NewTopic ordersTopic() {
return TopicBuilder.name("orders")
.partitions(3)
.replicas(1)
.build();
}
}KafkaAdmin uses this declaration at startup. Existing topics are not recreated.
Exercise
A topic has four partitions and a consumer group has six consumers. How many consumers can actively receive records?
Show answer
Four consumers, because Kafka assigns each partition to at most one consumer in the group.