Sub topic 4
Declaring topics as beans
This chapter assumes you can run a Spring Boot application with spring-kafka on the classpath. It also assumes you have a local broker and know what a partition is. Here you will let the application create its own topics at startup instead of creating them by hand.
Why declare topics in code
A topic needs a name, a partition count and a replication factor. If you create topics with a command-line tool, the setup is not stored with your code. A new developer or a new environment can then start the app against a broker that has no orders topic.
Spring for Apache Kafka solves this with KafkaAdmin. Spring Boot auto-configures it when spring-kafka is present. At startup, KafkaAdmin finds every NewTopic bean in the context. It asks the broker to create each topic that does not exist yet.
The NewTopic bean
You declare a topic by exposing a NewTopic bean. TopicBuilder gives you a fluent way to build one.
package com.example.orders;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;
@Configuration
public class KafkaTopicConfig {
@Bean
public NewTopic ordersTopic() {
return TopicBuilder.name("orders")
.partitions(3)
.replicas(1)
.build();
}
}This declares a topic named orders with three partitions. The partition count sets the upper limit on parallel consumers in one group, as the earlier chapter on consumer groups explained. The replication factor is 1 because a local development broker has only one node.
What happens at startup
The sequence is short, and it is worth knowing because it explains most surprises.
Common errors and limits
- Replicas higher than the broker count. If you set
.replicas(3)against a one-node broker, creation fails with an invalid replication factor error. Match the replica count to your cluster. - Expecting changes to apply. If the topic exists,
KafkaAdmindoes not shrink it or reconfigure it. The one case it handles is the partition count. If you declare more partitions than the existing topic has, it adds partitions. You cannot reduce partitions in Kafka. - Adding partitions changes key routing. The partitioner picks a partition from the key hash and the partition count. After you add partitions, the same key can map to a different partition. Events for one order may then be split across the old and new partitions, so per-key ordering can break across that change.
- Failing to reach the broker. By default, a failed admin call at startup is logged and does not stop the application. If you want the application to refuse to start without the topics, call
setFatalIfBrokerNotAvailable(true)on theKafkaAdmin. Thespring.kafka.admin.fail-fast=trueproperty does the same. - Auto-creation by the broker. Some brokers create a topic on first use with default settings. Do not rely on this. Defaults often give one partition, which removes any parallelism.
Adding topic settings
TopicBuilder can also set topic-level configuration. For example, you can keep records for seven days:
package com.example.orders;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.config.TopicConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;
@Configuration
public class KafkaRetentionConfig {
@Bean
public NewTopic auditTopic() {
return TopicBuilder.name("audit")
.partitions(1)
.replicas(1)
.config(TopicConfig.RETENTION_MS_CONFIG, "604800000")
.build();
}
}The value 604800000 is seven days in milliseconds.
Exercise
Your orders topic already exists with three partitions. You change the bean to declare six partitions and restart the application. What happens, and what side effect should you check for?
Show answer
KafkaAdmin adds three partitions, so the topic ends with six. Because the key hash now maps over six partitions, a given order ID may land on a different partition than before. Check whether any consumer depends on per-key ordering across the change.
Exercise
A teammate sets .replicas(3) on a topic bean and starts the app against a single local broker. What is the likely result, and how do you fix it?
Show answer
Topic creation fails because the broker cannot satisfy a replication factor of 3 with one node. Set replicas to 1 for local development, or run a cluster with at least three brokers.