Sub topic 4
Declaring topics as beans
This chapter assumes you know Spring Boot basics (beans, @Configuration, application.yml), have the spring-kafka dependency on the classpath, and understand that a topic is split into partitions (covered in the first chapter). Here you will learn how Spring creates topics for you at startup, what the settings mean, and which mistakes cause trouble.
Why declare topics in code
Kafka brokers can create topics on demand, but relying on that is risky. A broker with auto.create.topics.enable=true creates a topic the first time someone produces to it or subscribes to it. The new topic gets the broker's default partition count and replication factor, and a typo in a topic name silently creates a new, empty topic.
Declaring topics as beans gives you three things:
- The partition count and replication factor live in your code and are reviewed like any other change.
- A fresh environment (a laptop, a CI job, a test cluster) gets the topics it needs without manual steps.
- Your application documents which topics it depends on.
How it works: KafkaAdmin and NewTopic
Spring Boot auto-configures a KafkaAdmin bean when spring-kafka is present. KafkaAdmin wraps the Kafka AdminClient. After the application context is initialized, KafkaAdmin collects every NewTopic bean in the context and asks the broker to create the ones that do not exist yet.
NewTopic is a Kafka class from org.apache.kafka.clients.admin. It holds a name, a partition count, a replication factor and optional configuration. Spring provides TopicBuilder so you do not have to call its constructors directly.
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();
}
}When the application starts, this creates the orders topic with three partitions if it is missing. The KafkaAdmin connection uses the same spring.kafka.bootstrap-servers property as your producer and consumer, so no extra configuration is needed.
Choosing partitions and replicas
The two numbers you set most often have different purposes.
| Setting | Controls | Practical guidance |
|---|---|---|
| `partitions` | Maximum consumer parallelism in one group, and the unit of ordering | Pick enough for the consumers you expect to run. Order is only guaranteed within one partition. |
| `replicas` | How many brokers hold a copy of each partition | Use 1 on a single local broker. Use 3 in production so one broker can fail without data loss. |
The replication factor cannot exceed the number of brokers. If you ask for replicas(3) against a single local broker, topic creation fails with an InvalidReplicationFactorException. This is the most common surprise when a configuration copied from production is run on a laptop.
A good habit is to keep these values in properties so each environment can set its own:
package com.example.orders;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;
@Configuration
public class ConfigurableTopicConfig {
@Bean
public NewTopic auditTopic(
@Value("${app.topics.audit.partitions:3}") int partitions,
@Value("${app.topics.audit.replicas:1}") int replicas) {
return TopicBuilder.name("audit")
.partitions(partitions)
.replicas(replicas)
.build();
}
}Set app.topics.audit.replicas: 3 in the production profile and leave the default of 1 for local work.
Topic-level configuration
TopicBuilder also accepts topic configuration entries through config. These are the same settings you would pass to kafka-topics.sh --config.
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 RetentionTopicConfig {
@Bean
public NewTopic shortLivedTopic() {
return TopicBuilder.name("orders.metrics")
.partitions(3)
.replicas(1)
.config(TopicConfig.RETENTION_MS_CONFIG, "86400000")
.config(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_DELETE)
.build();
}
}This topic keeps records for 24 hours (86,400,000 ms) and then deletes them. Configuration values are always strings, even when they are numbers. Using the constants from TopicConfig avoids typos in key names.
Declaring several topics at once
Spring Kafka 2.7 and later lets you return a KafkaAdmin.NewTopics object to declare a group of topics in one bean. This is useful when topics belong together, for example a main topic and its dead-letter topic (the dead-letter chapter explains why you need 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;
import org.springframework.kafka.core.KafkaAdmin;
@Configuration
public class OrderTopicsConfig {
@Bean
public KafkaAdmin.NewTopics orderTopics() {
return new KafkaAdmin.NewTopics(
TopicBuilder.name("orders").partitions(3).replicas(1).build(),
TopicBuilder.name("orders.DLT").partitions(3).replicas(1).build());
}
}Both approaches produce the same result, since KafkaAdmin handles NewTopic beans and NewTopics beans alike. Choose whichever reads better to you.
What happens when the topic already exists
KafkaAdmin is conservative, and its behavior is worth knowing precisely:
- If the topic does not exist, it is created.
- If the topic exists with the same or a larger partition count, nothing changes.
- If the topic exists with fewer partitions than the bean declares,
KafkaAdminadds partitions. Kafka can only increase partitions, never reduce them. - If the topic exists with more partitions than declared, the application logs a message and continues. It does not delete or shrink anything.
- Replication factor and topic config differences on an existing topic are not changed by default.
Startup behavior and failure modes
By default, if the broker is unreachable when the application starts, KafkaAdmin logs the failure and the application keeps starting. The topic is then not created, and the first send or subscribe may fail or, with broker auto-creation on, create a topic with default settings.
You can make startup stricter with these KafkaAdmin flags, exposed in Spring Boot through spring.kafka.admin.*:
spring:
kafka:
bootstrap-servers: localhost:9092
admin:
fail-fast: true
operation-timeout: 30sfail-fast: truestops the application if the broker cannot be reached, which surfaces a bad address immediately instead of at the first message.operation-timeoutlimits how long admin operations wait before failing.
Two other failure modes come up often:
- Missing permissions. On a secured cluster, the application's principal needs permission to create topics. If your organization creates topics through another process, do not declare
NewTopicbeans in that environment, or turn creation off, for example withspring.kafka.admin.auto-create: false. - Config drift. Because
KafkaAdmindoes not alter the settings of existing topics, changingretention.msin code does nothing on a cluster where the topic already exists. Alter it with the Kafka tools, or use a dedicated infrastructure tool for topic management.
Checking the result
After starting the application, confirm the topic exists with the Kafka command-line tools:
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic ordersThe output lists the partition count, the replication factor, and the leader and replicas of each partition. If you see the default partition count of 1 instead of 3, the topic was probably created earlier by auto-creation, before your bean ran.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Replicas greater than broker count | `InvalidReplicationFactorException` at startup | Lower `replicas` or add brokers |
| Topic name typo in listener or producer | Silent empty topic, or no messages received | Share the name through a constant or property |
| Expecting config changes to apply to an existing topic | Old settings remain | Alter the topic with Kafka tools |
| Expecting fewer partitions to take effect | Partition count stays the same | Create a new topic and migrate |
| Relying on broker auto-creation | Topics with default settings | Declare `NewTopic` beans |
Exercise
Your orders topic already exists with 3 partitions. You change the bean to partitions(6) and restart. A second teammate then changes it back to partitions(3) and restarts. What is the final partition count, and what side effect did the increase have on key-based ordering?
Show answer
The final count is 6. KafkaAdmin adds partitions when the declared count is higher than the existing count, and it cannot shrink a topic, so the later change to 3 has no effect. The increase changes the key-to-partition mapping, so records with the same key written after the change may go to a different partition than earlier records with that key, and ordering for that key is not guaranteed across the boundary.
Exercise
A topic bean declares .replicas(3), and the application fails at startup on a developer's machine running one local broker. Give two ways to fix this without removing the topic declaration.
Show answer
Read the replica count from a property (for example @Value("${app.topics.audit.replicas:1}")) and use 1 locally, or run a local cluster with at least three brokers. Either way, the replication factor must not exceed the number of available brokers.