How do you create a topic in Kafka?

Creating a topic in Kafka means registering a new named log with a chosen number of partitions and replication factor, either via the kafka-topics.sh CLI, the AdminClient API, or auto-creation on first produce.

Key Points: • The --partitions flag controls how many parallel logs the topic is split into, which caps consumer parallelism within a group. • The --replication-factor flag controls how many broker copies of each partition exist, which determines fault tolerance. • Auto-creation of topics on first write is convenient in development but is usually disabled in production to avoid accidental or misconfigured topics. • Topic-level configs like retention.ms or cleanup.policy can be set at creation time with --config.

Example: Running the CLI command creates a topic named our_topic_name split into 3 partitions with a single replica, suitable for a local single-broker development setup but not for production, where replication factor should typically be at least 3.

Code Example:

kafka-topics.sh --create   --bootstrap-server server_address:9092   --replication-factor 1   --partitions 3   --topic our_topic_name

Interview Tip: A concise interview answer is:

"I create a topic with the kafka-topics.sh --create command, specifying the bootstrap server, the number of partitions for parallelism, and the replication factor for fault tolerance, or I do the same programmatically through Kafka's AdminClient when I need it done from application code."