Migrate to Python Client 4.4

Python Client 4.4 Preview is a new release built on a Rust core. The confluent-kafka package name, the install command, and the PyPI listing are unchanged, but the client class names, import paths, and method signatures have changed to align with the Java Client. Plan to update imports and application code, not just configuration.

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.

Behavioral changes and defaults

Behavior

2.x

4.4

group.protocol

Optional. Default classic.

Required for the consumer, and must be consumer. Creating a consumer without it, or with classic, raises UnsupportedOperationError.

classic group protocol support

Supported

Not supported

Minimum Apache Kafka® / Confluent Platform for consumer

Kafka 0.8+

Kafka 4.0+ or Confluent Platform 8.0+ (required for consumer protocol)

Underlying implementation

librdkafka (C/C++ binding)

Rust core

Configuration property names

librdkafka names

Java Client names. Many 2.x names are also Java Client names and work in 4.4, some with a different default. Other 2.x names have a new name in 4.4 or no equivalent, and are ignored. See Configuration changes.

Versioning scheme

2.x incremental

Aligns with the Kafka major.minor version. Python Client 4.4 doesn’t have feature parity with Kafka 4.4.

Prebuilt wheel platforms

Linux x86_64, arm64, s390x; macOS x86_64, arm64; Windows x86_64

Linux x86_64, arm64; macOS x86_64, arm64. Windows isn’t supported.

Migrate from 2.x to 4.4

Before migrating from Python Client 2.x to 4.4, upgrade your Kafka cluster to Kafka 4.0 or later, Confluent Platform 8.0 or later, or use Confluent Cloud. The 4.4 consumer requires the consumer group protocol.

Follow these steps to migrate an application from Python Client 2.x to 4.4:

  1. Upgrade the package to Python Client 4.4 Preview:

    pip install "confluent-kafka==v4.4.0b1"
    
  2. Update imports, class names, and method calls as described in API changes.

  3. Update configuration properties as described in Configuration changes. To find a property you missed, run the application with the RUST_LOG environment variable set to info, and look for the log line These configurations '[...]' were supplied but are not used yet.

  4. Test your application with group.protocol set to consumer.

Configuration changes

Python Client 4.4 uses the Java Client property names. A 2.x property name that 4.4 doesn’t recognize isn’t an error. The Python Client accepts the property and ignores it. Check each property of a 2.x configuration against the following tables.

For the properties that work differently in 4.4 or aren’t supported, see Configure Python Client 4.4.

Renamed properties

Several Python Client 4.4 names already work in Python Client 2.x as aliases, such as bootstrap.servers, linger.ms, acks, retries, compression.type, and delivery.timeout.ms. If your configuration uses them, keep them.

2.x property

4.4 property

Notes

metadata.broker.list

bootstrap.servers

queue.buffering.max.ms

linger.ms

message.timeout.ms

delivery.timeout.ms

The default changes from 300000 to 120000.

request.required.acks

acks

message.send.max.retries

retries

compression.codec

compression.type

max.in.flight

max.in.flight.requests.per.connection

The default changes from 1000000 to 5.

message.max.bytes

max.request.size

The default changes from 1000000 to 1048576.

fetch.wait.max.ms

fetch.max.wait.ms

fetch.message.max.bytes

max.partition.fetch.bytes

socket.send.buffer.bytes, socket.receive.buffer.bytes

send.buffer.bytes, receive.buffer.bytes

For the operating system default, use -1 instead of 0.

topic.metadata.refresh.interval.ms

metadata.max.age.ms

The 2.x metadata.max.age.ms is a cache age, with a different meaning.

partitioner

partitioner.type

consistent_random, the 2.x default, maps to ConsistentRandomPartitioner, the 4.4 default, so a record with a key goes to the same partition as in 2.x. murmur2_random maps to Murmur2RandomPartitioner. The other 2.x partitioners have no equivalent.

sasl.mechanisms

sasl.mechanism

Only PLAIN is supported.

sasl.username, sasl.password

sasl.jaas.config

Use this format: org.apache.kafka.common.security.plain.PlainLoginModule required username="<key>" password="<secret>";

ssl.ca.location

ssl.truststore.location

A PEM file.

ssl.ca.pem

ssl.truststore.certificates

ssl.certificate.location, ssl.key.location

ssl.keystore.location

One PEM file that holds the private key and its certificate chain.

ssl.certificate.pem, ssl.key.pem

ssl.keystore.certificate.chain, ssl.keystore.key

Properties with a different default

Property

2.x default

4.4 default

enable.idempotence

false

true

batch.size

1000000

16384

check.crcs

false

true

allow.auto.create.topics

false

true

socket.connection.setup.timeout.ms

30000

10000

reconnect.backoff.ms

100

50

reconnect.backoff.max.ms

10000

1000

client.id

rdkafka

Generated, such as producer-1 or adminclient-1

The defaults of isolation.level (read_committed) and of partitioner.type (a CRC-32 key hash) are the same as in 2.x.

Consumer group properties

With group.protocol=consumer, the broker manages the session timeout, the heartbeat interval, and the partition assignment. Remove session.timeout.ms, heartbeat.interval.ms, and partition.assignment.strategy from the consumer configuration. If any of these properties is set, creating the consumer raises ConfigError. For example, session.timeout.ms cannot be set when group.protocol=CONSUMER.

Properties with no equivalent

The 4.4 client ignores the following 2.x properties. Use the equivalent 4.4 step instead.

2.x property

4.4 step

on_delivery

Pass the callback to send(): send(record=..., callback=...).

on_commit

Pass the callback to commit_nowait(callback=...).

error_cb

A failed operation raises an error or fails its future.

stats_cb, statistics.interval.ms

Read the metrics with metrics().

logger, debug

The client writes its log to standard error. Set the level with the RUST_LOG environment variable, such as RUST_LOG=debug.

oauth_cb

SASL/OAUTHBEARER isn’t supported.

enable.partition.eof

To detect the end of a partition, compare position() with end_offsets().

enable.auto.offset.store

Set enable.auto.commit=false, and commit the offsets you choose with commit(offsets=...).

queue.buffering.max.messages, queue.buffering.max.kbytes

buffer.memory limits the producer’s buffer, in bytes.

batch.num.messages

batch.size limits a batch, in bytes.

API changes

The Python Client 4.4 API is the Java Client API. The classes, methods, parameters, and behavior align with the Java Client. Python changes only the form:

  • Names are snake_case.

  • An exception class ends in Error instead of Exception.

  • Clients are context managers, and a ConsumerRecords batch is iterable.

Design choices

The following choices apply to every class in the package.

Imports are from submodules

In 2.x, you import most classes from confluent_kafka. In 4.4, each class is in a submodule, such as confluent_kafka.producer, confluent_kafka.consumer, confluent_kafka.admin, or confluent_kafka.common. For example, KafkaProducer is in confluent_kafka.producer, and TopicPartition is in confluent_kafka.common. The confluent_kafka package itself exports only Duration and a few general errors, such as IllegalArgumentError and ExecutionError.

Arguments are keyword-only

Every parameter of every method and constructor is keyword-only. A positional call raises TypeError:

consumer.seek(partition=tp, offset=42)  # 4.4
consumer.seek(tp, 42)                   # raises TypeError

The Java Client has overloads, which are methods with the same name and different parameters, such as seek(TopicPartition, long) and seek(TopicPartition, OffsetAndMetadata). Python has one method per name, so each set of Java Client overloads is one Python method that takes the parameters of all of them. The keywords you pass select the overload. If they match no Java Client overload, the method raises IllegalArgumentError with the accepted sets of keywords. For example:

commit_nowait() takes one of (), (callback), (offsets, callback); got (offsets)

Keywords also keep your code working when a later release adds a parameter or an overload.

Leaving out an argument isn’t the same as None

Leaving out an argument selects the overload without that parameter. Passing None counts as passing the argument, so it selects the overload that has the parameter. For example, the ProducerRecord overload that takes headers also takes a partition and a key, so pass them as None:

ProducerRecord(topic='my-topic', partition=None, key=None, value=b'v',
               headers=[('trace-id', b'42')])

Callbacks and serializers take keyword arguments

The client calls delivery callbacks, commit callbacks, serializers, and deserializers with keyword arguments. Each one must accept **kwargs:

def on_delivery(*, metadata, exception, **kwargs): ...
def on_commit(*, offsets, exception, **kwargs): ...
def serialize(*, topic, data, headers=None, **kwargs): ...

When a later release adds a parameter, your function gets it in **kwargs and keeps working. A function without **kwargs raises IllegalArgumentError when you pass it to the client. A ConsumerRebalanceListener is a class you subclass, and the client calls its methods with positional arguments.

Values are read with methods

In Python Client 2.x, TopicPartition had attributes, such as tp.topic and tp.offset. In Python Client 4.4, you read a value with a method, not an attribute: tp.topic(), record.offset(), metadata.partition(). Getters have no get prefix: the 2.x Uuid.get_most_significant_bits() is most_significant_bits() in 4.4.

Timeouts

In Python Client 4.4, a timeout is a Duration, which is seconds as a float or a datetime.timedelta. poll() requires a timeout, such as consumer.poll(timeout=1.0). The other consumer methods that wait, such as commit() and position(), take an optional timeout. Without it, default.api.timeout.ms applies.

Futures

send() and the admin operations return a KafkaFuture. Call get() to wait for the result. If the operation failed, get() raises ExecutionError, and the error that caused the failure is its __cause__.

Errors are classes

Each error has its own exception class, in a hierarchy, such as TopicAuthorizationError and its parent AuthorizationError in confluent_kafka.common.errors. Catch an error by its class, such as except RetriableError. There is no code() to compare. For examples, see Error handling.

Threads

  • The producer runs delivery callbacks on its own background thread, one at a time, in the order the records complete. In 2.x, they ran on the thread that called poll() or flush(). Make your delivery callback thread-safe and short.

  • The consumer runs rebalance listener methods and commit callbacks on your thread, inside a consumer call such as poll(), as in 2.x.

  • A KafkaConsumer is for one thread. A call from a second thread while another call is running raises ConcurrentModificationError. Only wakeup() and metrics() work from any thread. wakeup() makes the waiting call raise WakeupError.

  • KafkaProducer and the admin client are thread-safe.

Asyncio clients

Each client has an asyncio class in the same module: AsyncKafkaProducer, AsyncKafkaConsumer, and AsyncAdmin. They replace AIOProducer and AIOConsumer from the 2.x confluent_kafka.aio module. A method that waits, such as flush() or poll(), is async def. The other methods, such as assignment(), are plain methods. You await send() and the future it returns:

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

async def produce(conf):
    async with AsyncKafkaProducer(configs=conf, value_serializer=string_serializer()) as producer:
        future = await producer.send(record=ProducerRecord(topic='my-topic', value='v'))
        metadata = await future.get()

Mock clients for tests

Python Client 4.4 has mock clients for tests: MockProducer, MockConsumer, and MockAdminClient. AsyncMockProducer, AsyncMockConsumer, and AsyncMockAdminClient are their asyncio versions. These don’t need a broker, so you can test your application code with them.

Type hints

The package has type hints. The clients and records are generic in their key and value types, and a type checker infers the types from the serializers. For example, KafkaConsumer(configs=conf, value_deserializer=string_deserializer()) is a KafkaConsumer[bytes, str].

Producer

Import the 4.4 producer class KafkaProducer from confluent_kafka.producer. The key changes from 2.x are:

  • The import path changes from confluent_kafka to confluent_kafka.producer.

  • produce() is replaced by send(record=ProducerRecord(...)).

  • The constructor takes configs= as a keyword argument, and serializers in key_serializer and value_serializer. Without a serializer, the producer uses the bytes serializer, which takes bytes.

  • The delivery callback signature changes from (err, msg) to (*, metadata, exception, **kwargs), where exception is None on success and metadata carries the delivery result. The producer passes the arguments as keywords, and the callback must accept **kwargs. Otherwise, send() raises an IllegalArgumentError.

  • producer.poll(0) in the produce loop is no longer needed. The producer handles delivery on a background thread.

  • Always call close() to release resources.

Compare the revised Python Client 4.4 Preview code for the producer to comparable Python Client 2.16 code for the producer:

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

conf = {
    'bootstrap.servers': 'localhost:9092',
    'acks': 'all',
    'delivery.timeout.ms': 10000,
}

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()}]')

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

try:
    record = ProducerRecord(topic='my-topic', key='key', value='value')
    producer.send(record=record, callback=on_delivery)
    producer.flush()
finally:
    producer.close()
from confluent_kafka import Producer

conf = {
    'bootstrap.servers': 'localhost:9092',
    'acks': 'all',
    'delivery.timeout.ms': 10000,
}

def delivery_callback(err, msg):
    if err:
        print(f'Delivery failed: {err}')
    else:
        print(f'Delivered to {msg.topic()} [{msg.partition()}]')

producer = Producer(conf)

producer.produce('my-topic', key='key', value='value', callback=delivery_callback)
producer.poll(0)
producer.flush()

Other producer changes:

2.x

4.4

produce_batch()

Call send() for each record.

flush(timeout), which returns the number of messages still queued

flush(), which waits until every record sent before it completes.

produce() raises BufferError when the queue is full

send() waits for buffer space, up to max.block.ms.

len(producer), purge(), set_sasl_credentials()

No equivalent.

list_topics(topic)

partitions_for(topic=...)

cluster_id()

describe_cluster().cluster_id().get() on the admin client.

init_transactions(timeout), commit_transaction(timeout), abort_transaction(timeout)

The same methods without timeout. They wait up to max.block.ms.

send_offsets_to_transaction(positions, group_metadata)

send_offsets_to_transaction(offsets=..., group_metadata=...), where offsets is a dict of TopicPartition to OffsetAndMetadata.

Consumer

Import the Python Client 4.4 consumer class KafkaConsumer from confluent_kafka.consumer. The key changes from 2.x are:

  • Change import path from confluent_kafka to confluent_kafka.consumer.

  • The constructor takes configs= as a keyword argument, and deserializers in key_deserializer and value_deserializer. Without a deserializer, the consumer returns bytes.

  • subscribe() takes topics= as a keyword argument.

  • Rebalance callbacks are a ConsumerRebalanceListener subclass, passed as subscribe(topics=..., callback=listener), instead of the on_assign, on_revoke, and on_lost functions.

  • commit() waits for the broker to confirm the commit. In 2.x, commit() didn’t wait by default. For the 2.x behavior, call commit_nowait().

  • poll() now returns a ConsumerRecords batch that is always iterable. It never returns None. Replace the if msg is None: continue guard with a for msg in records: loop.

  • Set group.protocol to consumer. The classic protocol isn’t supported.

Compare the revised Python Client 4.4 Preview code for the consumer to comparable Python Client 2.16 code for the consumer:

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(msg.value())
finally:
    consumer.close()
from confluent_kafka import Consumer, KafkaException

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

consumer = Consumer(conf)
consumer.subscribe(['my-topic'])

try:
    while True:
        msg = consumer.poll(timeout=1.0)
        if msg is None:
            continue
        if msg.error():
            raise KafkaException(msg.error())
        print(msg.value())
finally:
    consumer.close()

Other consumer changes:

2.x

4.4

subscribe(['^regex'])

subscribe(pattern=SubscriptionPattern(pattern='regex')). The broker matches the pattern.

consume(num_messages, timeout)

poll(timeout=...). max.poll.records limits the number of records in a batch.

commit(message=msg)

commit(offsets={tp: OffsetAndMetadata(offset=record.offset() + 1)}), or commit(offsets=records.next_offsets()) for a whole batch.

commit(offsets=[TopicPartition(topic, partition, offset)])

commit(offsets={TopicPartition(topic=..., partition=...): OffsetAndMetadata(offset=...)})

store_offsets()

No equivalent. Set enable.auto.commit=false, and commit the offsets you choose.

incremental_assign(), incremental_unassign()

assign(partitions=...), with the full set of partitions.

unassign()

unsubscribe(), which also removes assigned partitions.

seek(TopicPartition(topic, partition, offset))

seek(partition=TopicPartition(...), offset=...)

position(partitions)

position(partition=...), for one partition.

get_watermark_offsets(partition)

beginning_offsets(partitions=...) and end_offsets(partitions=...)

offsets_for_times(partitions)

offsets_for_times(timestamps_to_search=...), a dict of TopicPartition to timestamp.

list_topics()

list_topics(), which returns a dict of topic name to a list of PartitionInfo, or partitions_for(topic=...).

consumer_group_metadata(), memberid()

group_metadata(), and group_metadata().member_id()

close()

close(), or close(option=CloseOptions(operation=...)) to choose whether the consumer leaves the group.

ShareConsumer

Not available.

Admin

Import the Python Client 4.4 admin class Admin from confluent_kafka.admin. The key changes from 2.x are:

  • AdminClient is replaced by Admin. Create the client with Admin.create(configs=...) instead of calling the constructor.

  • create_topics() takes new_topics= as a keyword argument, and NewTopic takes name= instead of a positional topic name.

  • Admin operations return a result object instead of a dict of futures. Call values() to get a future for each item, or all().get() to wait for every item to complete.

  • Call get() on each future instead of result(). A failed item raises ExecutionError, with the underlying error, such as TopicExistsError, as its __cause__. This replaces the KafkaException and KafkaError error code check from 2.x.

  • Use the admin client as a context manager so that it closes when the with block exits.

Compare the revised Python Client 4.4 Preview code for the admin client to comparable Python Client 2.16 code for the admin client:

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')
from confluent_kafka import KafkaError, KafkaException
from confluent_kafka.admin import AdminClient, NewTopic

admin = AdminClient({'bootstrap.servers': 'localhost:9092'})

topic = NewTopic('my-topic', num_partitions=3, replication_factor=1)
futures = admin.create_topics([topic])
for name, future in futures.items():
    try:
        future.result()
        print(f'Created topic {name}')
    except KafkaException as e:
        if e.args[0].code() != KafkaError.TOPIC_ALREADY_EXISTS:
            raise
        print(f'Topic {name} already exists')

Other admin changes:

2.x

4.4

Keyword arguments such as operation_timeout, request_timeout, and validate_only

An options object for each operation. For example, create_topics(new_topics=..., options=CreateTopicsOptions(timeout_ms=..., validate_only=...)).

list_topics(), which returns ClusterMetadata

list_topics(), which returns a ListTopicsResult. Call names().get() for the topic names.

list_consumer_groups()

list_groups()

Records and partitions

The following table maps the 2.x message and partition classes to 4.4:

2.x

4.4

Message

ConsumerRecord for a consumed record, and ProducerRecord for a record to send.

msg.timestamp(), which returns (type, timestamp)

record.timestamp() and record.timestamp_type()

msg.headers(), a list of (key, value) tuples

record.headers(), a Headers object. Iterating over it gives Header objects with key() and value(). A header value is a memoryview, or None when the header has no value. Call bytes(header.value()) for a copy.

msg.error()

No equivalent. poll() raises the error.

msg.latency(), msg.set_value() and the other setters

No equivalent.

TopicPartition(topic, partition, offset)

TopicPartition(topic=..., partition=...). A TopicPartition has no offset. Pass the offset as its own argument, or in an OffsetAndMetadata.

tp.topic, tp.partition

tp.topic(), tp.partition()

OFFSET_BEGINNING, OFFSET_END

seek_to_beginning(partitions=...), seek_to_end(partitions=...)

Serializers and deserializers

The following table maps the 2.x serializers and deserializers to 4.4:

2.x

4.4

SerializingProducer, DeserializingConsumer

KafkaProducer and KafkaConsumer, with the serializers or deserializers passed to the constructor.

StringSerializer, IntegerSerializer, DoubleSerializer, and their deserializers, from confluent_kafka.serialization

string_serializer(), int_serializer(), float_serializer(), and their deserializers, from confluent_kafka.common.serialization. There are also bytes, bool, uuid, and json serializers and deserializers.

A serializer called as serializer(obj, ctx), with a SerializationContext

A function called as serializer(topic=..., data=..., headers=..., **kwargs)

Schema Registry serializers, from confluent_kafka.schema_registry

Not provided. To use Schema Registry, call a Schema Registry client library from your own serializer and deserializer.

Error handling

In 4.4, poll() raises exceptions for errors rather than returning a message object with msg.error() set. Remove the if msg.error(): check from your consume loop. Use a try/except block to catch errors from poll().

The KafkaError error code matching pattern from 2.x doesn’t apply in 4.4. The Python Client 4.4 uses a typed exception hierarchy. Test any error handling code against Python Client 4.4 before deploying.

Compare the revised Python Client 4.4 Preview code for error handling to comparable Python Client 2.16 code for error handling:

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

consumer = KafkaConsumer(
    configs={
        'bootstrap.servers': 'localhost:9092',
        'group.id': 'my-group',
        'group.protocol': 'consumer',
    },
    value_deserializer=string_deserializer(),
)
consumer.subscribe(topics=['my-topic'])

try:
    while True:
        records = consumer.poll(timeout=1.0)
        for msg in records:
            print(msg.value())
except Exception as e:
    print(f'Consumer error: {e}')
finally:
    consumer.close()
from confluent_kafka import Consumer, KafkaException, KafkaError

consumer = Consumer({
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'my-group',
})
consumer.subscribe(['my-topic'])

try:
    while True:
        msg = consumer.poll(timeout=1.0)
        if msg is None:
            continue
        if msg.error():
            if msg.error().code() == KafkaError._PARTITION_EOF:
                continue
            raise KafkaException(msg.error())
        print(msg.value())
finally:
    consumer.close()