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 |
|---|---|---|
|
Optional. Default |
Required for the consumer, and must be |
|
Supported |
Not supported |
Minimum Apache Kafka® / Confluent Platform for consumer |
Kafka 0.8+ |
Kafka 4.0+ or Confluent Platform 8.0+ (required for |
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 |
Prebuilt wheel platforms |
Linux |
Linux |
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:
Upgrade the package to Python Client 4.4 Preview:
pip install "confluent-kafka==v4.4.0b1"
Update imports, class names, and method calls as described in API changes.
Update configuration properties as described in Configuration changes. To find a property you missed, run the application with the
RUST_LOGenvironment variable set toinfo, and look for the log lineThese configurations '[...]' were supplied but are not used yet.Test your application with
group.protocolset toconsumer.
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 |
|---|---|---|
|
|
|
|
|
|
|
|
The default changes from |
|
|
|
|
|
|
|
|
|
|
|
The default changes from |
|
|
The default changes from |
|
|
|
|
|
|
|
|
For the operating system default, use |
|
|
The 2.x |
|
|
|
|
|
Only |
|
|
Use this format:
|
|
|
A PEM file. |
|
|
|
|
|
One PEM file that holds the private key and its certificate chain. |
|
|
Properties with a different default
Property |
2.x default |
4.4 default |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Generated, such as |
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 |
|---|---|
|
Pass the callback to |
|
Pass the callback to |
|
A failed operation raises an error or fails its future. |
|
Read the metrics with |
|
The client writes its log to standard error. Set the level with the
|
|
SASL/OAUTHBEARER isn’t supported. |
|
To detect the end of a partition, compare |
|
Set |
|
|
|
|
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
Errorinstead ofException.Clients are context managers, and a
ConsumerRecordsbatch 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()orflush(). 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
KafkaConsumeris for one thread. A call from a second thread while another call is running raisesConcurrentModificationError. Onlywakeup()andmetrics()work from any thread.wakeup()makes the waiting call raiseWakeupError.KafkaProducerand 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_kafkatoconfluent_kafka.producer.produce()is replaced bysend(record=ProducerRecord(...)).The constructor takes
configs=as a keyword argument, and serializers inkey_serializerandvalue_serializer. Without a serializer, the producer uses the bytes serializer, which takesbytes.The delivery callback signature changes from
(err, msg)to(*, metadata, exception, **kwargs), whereexceptionisNoneon success andmetadatacarries the delivery result. The producer passes the arguments as keywords, and the callback must accept**kwargs. Otherwise,send()raises anIllegalArgumentError.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 |
|---|---|
|
Call |
|
|
|
|
|
No equivalent. |
|
|
|
|
|
The same methods without |
|
|
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_kafkatoconfluent_kafka.consumer.The constructor takes
configs=as a keyword argument, and deserializers inkey_deserializerandvalue_deserializer. Without a deserializer, the consumer returnsbytes.subscribe()takestopics=as a keyword argument.Rebalance callbacks are a
ConsumerRebalanceListenersubclass, passed assubscribe(topics=..., callback=listener), instead of theon_assign,on_revoke, andon_lostfunctions.commit()waits for the broker to confirm the commit. In 2.x,commit()didn’t wait by default. For the 2.x behavior, callcommit_nowait().poll()now returns aConsumerRecordsbatch that is always iterable. It never returnsNone. Replace theif msg is None: continueguard with afor msg in records:loop.Set
group.protocoltoconsumer. Theclassicprotocol 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 |
|---|---|
|
|
|
|
|
|
|
|
|
No equivalent. Set |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Not available. |
Admin
Import the Python Client 4.4 admin class Admin from confluent_kafka.admin.
The key changes from 2.x are:
AdminClientis replaced byAdmin. Create the client withAdmin.create(configs=...)instead of calling the constructor.create_topics()takesnew_topics=as a keyword argument, andNewTopictakesname=instead of a positional topic name.Admin operations return a result object instead of a
dictof futures. Callvalues()to get a future for each item, orall().get()to wait for every item to complete.Call
get()on each future instead ofresult(). A failed item raisesExecutionError, with the underlying error, such asTopicExistsError, as its__cause__. This replaces theKafkaExceptionandKafkaErrorerror code check from 2.x.Use the admin client as a context manager so that it closes when the
withblock 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 |
An |
|
|
|
|
Records and partitions
The following table maps the 2.x message and partition classes to 4.4:
2.x |
4.4 |
|---|---|
|
|
|
|
|
|
|
No equivalent. |
|
No equivalent. |
|
|
|
|
|
|
Serializers and deserializers
The following table maps the 2.x serializers and deserializers to 4.4:
2.x |
4.4 |
|---|---|
|
|
|
|
A serializer called as |
A function called as |
Schema Registry serializers, from |
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()