PyKafka is a full-featured, pure-Python client for Apache Kafka, which optionally uses a C extension (librdkafka) for improved performance. It supports Kafka versions 0.8.2 and newer, providing Pythonic implementations of Kafka producers and consumers. The library aims to offer a similar abstraction level to the JVM Kafka client. PyKafka is actively maintained, with the current stable version being 2.8.0, and typically releases updates as needed.
pip install pykafkaVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize a PyKafka client, produce a few messages to a topic, and then consume them using a `SimpleConsumer`. It's configured to connect to a local Kafka instance and resets the consumer offset to the earliest available for demonstration purposes. Ensure `KAFKA_HOSTS`, `KAFKA_TOPIC`, and `KAFKA_CONSUMER_GROUP` environment variables are set or default to `localhost:9092` and `test-topic`, `my-consumer-group` respectively.
Ensure `consumer_group` and topic names are passed as `str` instead of `bytes`. Convert existing byte strings using `.decode('utf-8')` if necessary, or ensure they are defined as `str`.Implement a loop to regularly call `producer.get_delivery_report()` and process the returned reports to prevent memory leaks. This is often done in a separate thread or an asynchronous callback.
Carefully review the `Consumer Patterns` documentation regarding `auto_offset_reset` (`OffsetType.EARLIEST` or `OffsetType.LATEST`) and `reset_offset_on_start` to ensure the consumer starts at the intended offset, especially in production environments to avoid message loss or reprocessing.
Install `librdkafka` development packages on your system (e.g., `librdkafka-dev` on Debian/Ubuntu, `librdkafka-devel` on RHEL/CentOS) and then install pykafka using `RDKAFKA_INSTALL=system pip install pykafka`.