- Creating a topic with multiple partitions
- Producing messages with a Python producer (
kafka-python) - Implementing a simple Python consumer that reads and prints messages
- Real-world considerations for running consumers in production
- A running Kafka broker reachable at
localhost:9092 - Kafka command-line tools available (usually in
~/kafka/binor/opt/kafka/bin) - Python 3 installed
- Basic familiarity with Kafka topics, partitions, and consumer groups
1) Create the topic
To consume messages you first need a topic and some messages in it. If you run the topic creation command from the wrong working directory, you may see an error like:kafka-topics.sh script is not found in the current folder. Kafka CLI tools live in the Kafka installation bin directory (for example ~/kafka/bin or /opt/kafka/bin). Change to that directory and run the command again:
If you are unsure where Kafka is installed, consult environment documentation or search for
kafka-topics.sh with find / -name kafka-topics.sh 2>/dev/null.2) Produce messages to the topic (Python producer)
Install a Python virtual environment and the Kafka client librarykafka-python:
kafka_producer_example.py) with the following content:
3) Write the Python consumer
Createkafka_consumer.py and add the following consumer code. This consumer subscribes to multi-partition-topic, reads from the earliest offset when there is no committed offset, and prints message contents with partition and offset metadata:
Run the consumer:
If you omit
group_id, Kafka treats the consumer as a new, distinct consumer; it may receive duplicates or begin from offsets determined by auto_offset_reset. Both bootstrap_servers and topic are required.4) Real-world considerations
The example prints messages to stdout for demonstration. In production you would typically:- Parse the message payload (JSON, Avro, Protobuf, etc.)
- Apply business logic and transformations
- Persist results to a database or forward processed events to another topic
- Add robust error handling, retries, backoff, and dead-letter queues
- Instrument metrics and tracing for monitoring and debugging
- Gracefully handle shutdown signals and rebalances to avoid duplicate processing
- Exactly-once vs at-least-once processing
- Partitioning and keys (how message keys affect partition assignment)
- Consumer rebalances and
max.poll.interval.ms - Offset committing strategies (automatic vs manual commits)
- Kafka documentation: https://kafka.apache.org/documentation/
- kafka-python (PyPI): https://pypi.org/project/kafka-python/
- Kafka consumer groups and partitioning: https://kafka.apache.org/documentation/#consumerapi
- Kubernetes for running consumers in production: https://learn.kodekloud.com/user/courses/kubernetes-for-the-absolute-beginners-hands-on-tutorial