Kafka 4 with Spring: Topics, Partitions, Offsets and Consumer Groups
Six ticket closes go to a Kafka topic with three partitions. The key picks the partition, so both ticket-1 records land in partition 1, at offsets 0 and 2. The notifications group splits the partitions over three threads; the audit group reads all three on one thread, and both end with lag 0.
What you will learn
- Run a single Kafka 4 broker in Docker and point Spring Boot at it
- Create a topic with three partitions from a NewTopic bean
- Send keyed records with KafkaTemplate and read back the partition and offset
- Explain how a consumer group shares partitions, and how a second group reads the same records again
- Read current offset, log end offset and lag for a group
Before you start
- Spring Application Events and the Transactional Outbox: Three Designs, Two Failures
- Docker Essentials
When a ticket is closed, Relay sends a CLOSED event to Kafka. Two other parts of the system care about it: notifications and audit. We'll send six events, watch which partition and offset each one gets, and see how two consumer groups read the same records without getting in each other's way.
One broker in Docker
services:
kafka:
image: apache/kafka:4.2.0
container_name: ticket-desk-kafka
ports:
- "9092:9092"
That's a whole single-node Kafka. Kafka 4 runs without ZooKeeper (it uses KRaft mode), so one container is enough for local work. The project uses two starters, spring-boot-starter-webmvc and spring-boot-starter-kafka, and three properties:
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.listener.concurrency=3
bootstrap-servers is where the broker is. auto-offset-reset=earliest means a brand-new group starts reading from the first record instead of only new ones. listener.concurrency=3 gives each listener three consumer threads (one listener below overrides that).
A topic with three partitions
@Configuration
public class KafkaTopics {
public static final String TICKET_EVENTS = "ticket-events";
@Bean
public NewTopic ticketEvents() {
return TopicBuilder.name(TICKET_EVENTS)
.partitions(3)
.replicas(1)
.build();
}
}
Spring Boot sees the NewTopic bean at startup and creates the topic on the broker if it doesn't exist yet. Running kafka-topics.sh --describe inside the container confirms it: PartitionCount 3, ReplicationFactor 1, and partitions 0, 1 and 2 each with leader, replica and in-sync replica all on broker 1. One replica is fine on a laptop with one broker; in production you'd want more.
A partition is its own append-only log. Each one numbers its records from offset 0.
Sending: the key picks the partition
@Service
public class TicketEventPublisher {
private static final Logger log = LoggerFactory.getLogger(TicketEventPublisher.class);
private final KafkaTemplate<String, String> kafka;
public TicketEventPublisher(KafkaTemplate<String, String> kafka) {
this.kafka = kafka;
}
public void ticketClosed(long ticketId) {
String key = "ticket-" + ticketId;
kafka.send(TICKET_EVENTS, key, "CLOSED")
.whenComplete((result, error) -> {
if (error != null) {
log.error("send failed for {}: {}", key, error.getMessage());
return;
}
log.info("sent {} to partition {} at offset {}", key,
result.getRecordMetadata().partition(),
result.getRecordMetadata().offset());
});
}
}
send(topic, key, value) returns right away with a future. The broker's answer comes later, and the whenComplete callback logs where the record landed. That log line is printed on the producer's network thread, not on the web thread that called ticketClosed. The controller answers POST /tickets/{id}/close with 202.
Six closes, for tickets 1, 2, 3, 4, 1 again and 5. All six answered 202, and the records landed here:
| Key | Partition | Offset |
|---|---|---|
| ticket-1 | 1 | 0 |
| ticket-2 | 2 | 0 |
| ticket-3 | 0 | 0 |
| ticket-4 | 1 | 1 |
| ticket-1 | 1 | 2 |
| ticket-5 | 0 | 1 |
Look at ticket-1. Both of its records went to partition 1, at offsets 0 and 2. The producer hashes the key to choose a partition, so the same key always lands in the same one. That's what gives you order per key: everything about ticket 1 is in one log, in the order it was sent. There's no order across partitions, though. Ticket-3 in partition 0 and ticket-1 in partition 1 have no "before" or "after" between them.
Every record now has an address: a partition and an offset. The second ticket-1 is partition 1, offset 2.
Receiving: two listeners, two groups
@Component
public class TicketEventListener {
private static final Logger log = LoggerFactory.getLogger(TicketEventListener.class);
@KafkaListener(id = "notifications", topics = KafkaTopics.TICKET_EVENTS)
public void onTicketEvent(ConsumerRecord<String, String> record) {
log.info("notifications got {} {} from partition {} at offset {}",
record.key(), record.value(), record.partition(), record.offset());
}
@KafkaListener(id = "audit", topics = KafkaTopics.TICKET_EVENTS, concurrency = "1")
public void audit(ConsumerRecord<String, String> record) {
log.info("audit saw {} {} at partition {} offset {}",
record.key(), record.value(), record.partition(), record.offset());
}
}
The listener id also becomes the consumer group name here, so this is two groups: notifications and audit. The method takes a ConsumerRecord, which carries the key, the value, and the partition and offset it came from.
A group shares the work
With concurrency 3, the notifications listener runs three consumer threads, named notifications-0-C-1, notifications-1-C-1 and notifications-2-C-1. Kafka gives each one partition. So ticket-1 arrives on notifications-1-C-1, from partition 1 at offset 0, and no other notifications thread ever sees it. Within a group, a partition has exactly one reader at a time, which keeps each key's records in order.
That also sets a ceiling: three partitions means at most three busy consumers in one group. A fourth thread would sit idle.
A second group reads everything again
The audit listener sets concurrency = "1", so it has one thread, audit-0-C-1, and that thread owns all three partitions. It's a different group, so it doesn't share anything with notifications. It reads every record itself. Ticket-1 at partition 1, offset 0 shows up once in notifications got and once in audit saw. Adding another reader of the same events is a new group, and the producer doesn't change.
Each group keeps its own place
The broker doesn't delete a record when a group reads it. Instead, each group stores how far it got in each partition: its current offset. The partition's log end offset is the offset the next record will get. The gap between them is the lag, the records the group hasn't processed yet.
After the six sends, kafka-consumer-groups.sh --describe showed the same table for both groups:
| Partition | Current offset | Log end offset | Lag |
|---|---|---|---|
| 0 | 2 | 2 | 0 |
| 1 | 3 | 3 | 0 |
| 2 | 1 | 1 | 0 |
Partition 1 holds three records (offsets 0, 1, 2), so its log end offset is 3, and both groups are at 3: they've handled everything. Lag is the number to watch in production. If it keeps growing, the consumers can't keep up.
A log or a queue
This is the real difference from a queue such as RabbitMQ. In a queue, a message goes to one worker and is removed once it's handled. In a Kafka topic, records stay in the log, and each group moves its own offset through them. So a log suits events that several groups read, and may read again later. A queue suits jobs where each message should be done once, by one worker. (The lecture only compares the two; RabbitMQ isn't run here. For a side-by-side with Redis, RabbitMQ and SQS, see Choosing a Message Broker.)
Common mistakes
- Sending without a key when order matters. Records for the same ticket can end up in different partitions, and their order is lost.
- More consumer threads than partitions. The extras get no partition and do nothing.
- Two services sharing one group id by accident. They split the records between them, and each one sees only part of the stream.
- Ignoring the send result.
sendreturns before the broker answers. Without the callback, a failed send is invisible.
Try it yourself
Close ticket 4 two more times. Which partition do the new records go to, and at which offsets? Then run kafka-consumer-groups.sh --describe for the audit group and check the log end offset for that partition.
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
