Video in progress

Strong Middle 📨 Kafka and messaging

How does creating topics in code (`NewTopic`, `TopicBuilder`) work in a Spring Boot application, and is it a good idea on prod?

If the context has NewTopic beans, KafkaAdmin creates the missing topics at startup, and even increases the partition count if it's too low. It's handy for dev and test, but on prod topics are usually managed through GitOps or by a platform team, and the application only checks.

📖 Answer

@Bean
NewTopic orders() {
    return TopicBuilder.name("orders")
            .partitions(12)
            .replicas(3)
            .config(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2")
            .config(TopicConfig.RETENTION_MS_CONFIG, String.valueOf(Duration.ofDays(7).toMillis()))
            .build();
}

Spring Boot creates KafkaAdmin automatically. When the application starts, it checks whether such a topic exists:

  • if not, it creates it;
  • if it exists but has fewer partitions, it adds partitions;
  • by default it doesn't touch other configs (it can reconcile them with setModifyTopicConfigs(true)).

The second point is dangerous. Someone changes partitions(12) to 24 in the code, deploys, and on a keyed topic the key-to-partition mapping changes and the ordering breaks. With no warning at all.

More problems:

  • the application needs permission to create topics (a Create ACL), and giving that to every service on prod is bad from a security point of view;
  • if several services declare the same topic with different settings, whoever starts first wins.

Here's what I do: the local and test profiles have NewTopic beans, while on prod topics come through Terraform/Strimzi KafkaTopic resources, with review. The application checks at startup that the required topics exist and stops with a clear error if they don't.

On prod I turn off the broker setting auto.create.topics.enable=true (the default); otherwise a single-letter typo in a name creates a brand-new 1-partition topic.