Python Client for Apache Kafka

The confluent-kafka Python 4.4 package is the Python client library for Apache Kafka®. Confluent develops and maintains the client. The client provides a producer, consumer, and admin client that are compatible with Kafka 4.0 and later, Confluent Platform 8.0 and later, and Confluent Cloud.

Unlike earlier versions of the Python Client, the Python client 4.4 is built on a Rust core instead of a binding top of librdkafka. This new implementation that aligns more closely with the Java Client.

Note

The 4.4 Python Client is a Preview release.

A Preview feature is a Python client component that is being introduced to gain early feedback from developers. Preview features can be used for evaluation and non-production testing purposes or to provide feedback to Confluent. The warranty, SLA, and Support Services provisions of your agreement with Confluent do not apply to Preview features. Confluent may discontinue providing preview releases of the Preview features at any time in Confluent’s’ sole discretion.

Versioning is aligned to Kafka: the MAJOR.MINOR version of the package tracks the Kafka version it targets. Patch releases are independent of Kafka. The package name, install command, and PyPI listing are unchanged from earlier versions.

The API mirrors the Java Client’s method surface.

For the source code and issue tracker, see the confluent-kafka-python repository on GitHub.

Requirements

  • Python 3.10 or later.

  • Kafka 4.0 or later, Confluent Platform 8.0 or later, or Confluent Cloud.

  • The consumer requires the consumer group protocol (KIP-848). The classic protocol is not supported. For more details, see KIP-848.

Installation

The Python Client package is available on PyPI. Because the 4.4 release is a Preview, pin the version to avoid unexpected upgrades. Install the 4.4 preview with pip:

pip install "confluent-kafka==v4.4.0b1"

Prebuilt wheels are available for Linux x86_64, Linux arm64, macOS x86_64, and macOS arm64.

Configuration

Configure a client with a dict of Java Client property names, such as bootstrap.servers, linger.ms, and delivery.timeout.ms. Most properties have the same default and meaning as in the Java Client. The main differences are:

  • The consumer requires group.protocol=consumer. Creating a consumer without the consumer group protocol or with the classic group protocol raises UnsupportedOperationError.

  • As in Python Client 2.x:

    • isolation.level defaults to read_committed.

    • The default partitioner hashes record keys with CRC-32.

  • Only supports SASL/PLAIN authentication and PEM keys and certificates.

  • A property the client doesn’t recognize, such as a librdkafka property, isn’t an error. The client ignores it.

For all the differences, see Configure Python Client 4.4.

Migrate from 2.x

Python Client 4.4 isn’t a drop-in replacement for 2.x. The package name and the install command are the same, but the API is aligned with the Java Client:

  • The clients are KafkaProducer, KafkaConsumer, and Admin, imported from confluent_kafka.producer, confluent_kafka.consumer, and confluent_kafka.admin.

  • Methods take keyword arguments.

  • send(record=ProducerRecord(...)) replaces produce().

  • poll() returns a batch of records instead of one message.

  • Errors are raised as typed exceptions, such as TopicExistsError, instead of KafkaError codes.

  • Configuration uses Java Client property names. librdkafka property names are ignored.

For the migration steps and examples, see Migrate to Python Client 4.4.

Quick start

The following examples show how to create a topic, produce messages, and consume messages. Each example is a complete script you can run against a local Kafka broker at localhost:9092.

Create a topic

Import Admin and NewTopic from confluent_kafka.admin. To create a topic, call Admin.create() to create an admin client, and then call create_topics(). Admin operations return a result object that holds a future for each item in the request. To wait for every item to complete, call all().get(). This example calls values() instead, to get the per-item futures and handle each result separately. A failed item raises ExecutionError when you call get(), with the underlying error as its __cause__. The example treats TopicExistsError as a non-fatal error so that you can run the script more than once. Use the admin client as a context manager so that it closes when the with block exits.

Confluent Cloud requires a replication factor of 3:

from confluent_kafka import ExecutionError
from confluent_kafka.admin import Admin, NewTopic
from confluent_kafka.common.errors import TopicExistsError

conf = {
    'bootstrap.servers': '<bootstrap_server>',
    'security.protocol': 'SASL_SSL',
    'sasl.mechanism': 'PLAIN',
    'sasl.jaas.config': (
        'org.apache.kafka.common.security.plain.PlainLoginModule required '
        'username="<cluster_api_key>" password="<cluster_api_secret>";'
    ),
}

with Admin.create(configs=conf) as admin:
    topic = NewTopic(name='my-topic', num_partitions=3, replication_factor=3)
    result = admin.create_topics(new_topics=[topic])
    for name, future in result.values().items():
        try:
            future.get()
            print(f'Created topic {name}')
        except ExecutionError as e:
            if not isinstance(e.__cause__, TopicExistsError):
                raise
            print(f'Topic {name} already exists')
from confluent_kafka import ExecutionError
from confluent_kafka.admin import Admin, NewTopic
from confluent_kafka.common.errors import TopicExistsError

with Admin.create(configs={'bootstrap.servers': 'localhost:9092'}) as admin:
    topic = NewTopic(name='my-topic', num_partitions=3, replication_factor=1)
    result = admin.create_topics(new_topics=[topic])
    for name, future in result.values().items():
        try:
            future.get()
            print(f'Created topic {name}')
        except ExecutionError as e:
            if not isinstance(e.__cause__, TopicExistsError):
                raise
            print(f'Topic {name} already exists')

Produce messages

Import KafkaProducer from confluent_kafka.producer. Each call to send() stores the record in a local buffer and returns immediately. The producer doesn’t wait for broker acknowledgment. The producer delivers records in the background and invokes the delivery callback when each record succeeds or fails permanently. The producer passes metadata and exception to the callback as keyword arguments, and the callback must accept **kwargs. Otherwise, send() raises an IllegalArgumentError. Call flush() to block until all pending records are delivered, and always call close() to release resources.

For Confluent Cloud connections, provide the cluster’s bootstrap server and an API key and secret:

from confluent_kafka.producer import KafkaProducer, ProducerRecord
from confluent_kafka.common.serialization import string_serializer

def on_delivery(*, metadata, exception, **kwargs):
    if exception is not None:
        print(f'Delivery failed: {exception}')
    else:
        print(f'Delivered to {metadata.topic()} [{metadata.partition()}] at offset {metadata.offset()}')

conf = {
    'bootstrap.servers': '<bootstrap_server>',
    'security.protocol': 'SASL_SSL',
    'sasl.mechanism': 'PLAIN',
    'sasl.jaas.config': (
        'org.apache.kafka.common.security.plain.PlainLoginModule required '
        'username="<cluster_api_key>" password="<cluster_api_secret>";'
    ),
}

producer = KafkaProducer(
    configs=conf,
    key_serializer=string_serializer(),
    value_serializer=string_serializer(),
)

try:
    for i in range(10):
        record = ProducerRecord(topic='my-topic', key=f'key-{i}', value=f'value-{i}')
        producer.send(record=record, callback=on_delivery)
    producer.flush()
finally:
    producer.close()

For a local or Confluent Platform cluster:

from confluent_kafka.producer import KafkaProducer, ProducerRecord
from confluent_kafka.common.serialization import string_serializer

def on_delivery(*, metadata, exception, **kwargs):
    if exception is not None:
        print(f'Delivery failed: {exception}')
    else:
        print(f'Delivered to {metadata.topic()} [{metadata.partition()}] at offset {metadata.offset()}')

producer = KafkaProducer(
    configs={'bootstrap.servers': 'localhost:9092'},
    key_serializer=string_serializer(),
    value_serializer=string_serializer(),
)

try:
    for i in range(10):
        record = ProducerRecord(topic='my-topic', key=f'key-{i}', value=f'value-{i}')
        producer.send(record=record, callback=on_delivery)
    producer.flush()
finally:
    producer.close()

Consume messages

Import KafkaConsumer from confluent_kafka.consumer. poll() returns a ConsumerRecords batch, which is always iterable and never returns None. Iterate over the batch with a for loop. By default, the consumer commits offsets automatically every 5 seconds, before a rebalance, and on close(). This is set with auto.commit.interval.ms. Processing the full batch before calling poll() again gives at-least-once delivery. Always call close() in a finally block to commit final offsets and immediately return the consumer’s partitions to the group.

from confluent_kafka.consumer import KafkaConsumer
from confluent_kafka.common.serialization import string_deserializer

conf = {
    'bootstrap.servers': '<bootstrap_server>',
    'security.protocol': 'SASL_SSL',
    'sasl.mechanism': 'PLAIN',
    'sasl.jaas.config': (
        'org.apache.kafka.common.security.plain.PlainLoginModule required '
        'username="<cluster_api_key>" password="<cluster_api_secret>";'
    ),
    'group.id': 'my-group',
    'group.protocol': 'consumer',
    'auto.offset.reset': 'earliest',
}

consumer = KafkaConsumer(
    configs=conf,
    key_deserializer=string_deserializer(),
    value_deserializer=string_deserializer(),
)
consumer.subscribe(topics=['my-topic'])

try:
    while True:
        records = consumer.poll(timeout=1.0)
        for msg in records:
            print(f'{msg.topic()} [{msg.partition()}] at offset {msg.offset()}: {msg.value()}')
finally:
    consumer.close()
from confluent_kafka.consumer import KafkaConsumer
from confluent_kafka.common.serialization import string_deserializer

conf = {
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'my-group',
    'group.protocol': 'consumer',
    'auto.offset.reset': 'earliest',
}

consumer = KafkaConsumer(
    configs=conf,
    key_deserializer=string_deserializer(),
    value_deserializer=string_deserializer(),
)
consumer.subscribe(topics=['my-topic'])

try:
    while True:
        records = consumer.poll(timeout=1.0)
        for msg in records:
            print(f'{msg.topic()} [{msg.partition()}] at offset {msg.offset()}: {msg.value()}')
finally:
    consumer.close()

API documentation

For the API reference, see the Python Client API documentation.

For the changes in each release, see Python Client for Apache Kafka Changelog.