v1.0.0
All notable changes to the confluent-kafka crate are documented in this file.
- First generally available (GA) release of the Rust client, version 1.0.0.
- Clients no longer log the preview warning at startup.
- Clippy runs with
avoid-breaking-exported-api = true(clippy.toml): it skips every lint whose fix would change an exported signature, so a lint fix never makes a breaking change to the public API.
- Breaking: the compression codecs, TLS and SCRAM credential salting are optional, each behind a default feature:
gzip,snappy,lz4,zstd,rustlsandaws-lc-rs(whichrustlsimplies). With default features on nothing changes. A build withdefault-features = falsekept all of them before and now has none, and it still compiles: addfeatures = ["gzip", "snappy", "lz4", "zstd", "webpki-roots"]to keep the previous behaviour (webpki-rootsenablesrustls). With one off, the client fails with an explicit error where it would need it: a disabledcompression.typefails the producer's configuration, a fetched batch in a disabled codec fails withInvalidRecordError,SSLandSASL_SSLfail the client's construction, and a SCRAM upsertion fails its user's future withLocalUnsupportedOperationError. See "Cargo features" inREADME.md.serdeandserde_jsonare no longer dependencies of the library. - Breaking: Mozilla's root certificates, trusted without
ssl.truststore.locationorssl.truststore.certificates, now come from the default featurewebpki-roots. With default features on nothing changes. A build withdefault-features = falsemust addfeatures = ["webpki-roots"]; without it the build stops with "confluent-kafka needs a default trust store", since no other default trust store exists yet. A later one is then a feature of its own, anddefault-features = falseselects it without the bundle. - Breaking:
Uuid::from_stringapplies Java'sBase64.getUrlDecoder()rules to=padding: a=that starts a 4-character unit, a single=after two characters, or anything after the padding is anIllegalArgumentErrorwith Java's message, where it was accepted or reported as a wrong decoded length. A one-character input and a last unit of one character also report Java's messages (#269).
- Breaking:
Consumer::committed/committed_with_timeoutreturnHashMap<TopicPartition, Option<OffsetAndMetadata>>: every queried partition is a key,Nonefor one with no committed offset, as Java maps it tonull. It was absent from the map before. - Breaking:
Consumer::offsets_for_times/offsets_for_times_with_timeoutreturnHashMap<TopicPartition, Option<OffsetAndTimestamp>>: every queried partition is a key,Nonefor one without an offset for its timestamp, as in Java. A zero timeout maps every queried partition toNone, as Java'semptyResults(). The same holds forConsumerHandle. - Breaking:
Deserializer::deserialize_with_headersanddeserialize_with_headers_bytestake the record's headers as&mut RecordHeaders, so a deserializer can change them, as Java's can. Update the parameter type in your implementations. ConsumerHandlerefuses a closed consumer as the consumer does: onceclose()has returned, its async operations returnIllegalStateError("This consumer has already been closed.") instead ofConcurrentModificationError, andassignment,pausedandgroup_metadatapanic with that message instead of returning stale data. A listener thatclose()runs still calls back in;wakeupstays callable.
- Behaviour change: a retriable error during
close(timeout)no longer fails the call at once: until the deadline the call is retried, as Java'sclosedoes, andclosereturns once it completes. New calls are still rejected as soon ascloseis called. - Breaking: an explicit
default.api.timeout.msbelowrequest.timeout.msfails client creation with Java'sThe specified value of default.api.timeout.ms must be no smaller than the value of request.timeout.ms., wrapped inFailed to create new KafkaAdminClient. Whendefault.api.timeout.msis not set andrequest.timeout.msis above the API timeout's 60000 ms default, the API timeout is raised to the request timeout, with a WARN, as Java'sconfigureDefaultApiTimeoutMsdoes. - A negative per-call
timeout_msis treated as0, as Java'scalcDeadlineMsdoes: the call is sent once instead of timing out before it was sent. Admin::list_transactions()without options sends no duration filter (-1), as Java's does;ListTransactionsOptions::default()now equalsListTransactionsOptions::new().- The admin client's
NetworkClientallows one in-flight request per connection and has Java's one-hour default request timeout, asKafkaAdminClient.createInternalbuilds it. A broker that answers theApiVersionshandshake afterrequest.timeout.msis waited for instead of being disconnected, and a node with a request in flight is no longer picked as the least-loaded node. - New public
EndpointType, Java'sorg.apache.kafka.clients.admin.EndpointType(KIP-919):Unknown,BrokerandController, withid()andfrom_id(i8), which answersUnknownfor an id it does not know. bootstrap.controllers(KIP-919) is defined again (Rust, C API, Python), andAdminClientConfig::BOOTSTRAP_CONTROLLERS_CONFIGis back: aLIST, empty by default, validated as Java'sAdminClientConfigvalidates it, and read by the client whichever list it bootstraps from, so it is no longer listed among the unused configurations. A client configured with it alone bootstraps from the KRaft controller quorum, as Java's does: it refreshes its metadata withDescribeClusterfor the CONTROLLER endpoint, sends the calls the controllers serve (describing the cluster, the configs and the features, altering configs, ACLs, partition reassignments, updating the features, unregistering a controller) to the active controller or the node they name, and fails every other call at once withUnsupportedEndpointTypeError.- Breaking: setting neither
bootstrap.serversnorbootstrap.controllersfails client creation, still wrapped inFailed to create new KafkaAdminClient, with Java'sKafkaAdminClient.determineBootstrapTypeConfigErrorYou must set either bootstrap.servers or bootstrap.controllers, where it wasClientUtils'sNo resolvable bootstrap urls given in bootstrap.servers; setting both fails withYou cannot set both bootstrap.servers and bootstrap.controllers. - Breaking (Rust, Python): a config entry can have no type, as Java's
ConfigEntry.type()can benull.ConfigEntry::r#type()returnsOption<ConfigType>andConfigEntryOptionsBuilder::set_config_typetakes one. The entries of acreateTopicsresult have no type (KafkaAdminClient.java:1992-2002): they reportedConfigType::Unknownand printedtype=UNKNOWN, and now reportNone, printtype=nulland differ from an entry whose type isUnknown. In PythonConfigEntry.type()returnsNonefor them. - Breaking:
GroupState::name(),ClassicGroupState::name()andGroupType::name()return Java'sEnum.name(), the constant name (PREPARING_REBALANCE,CONSUMER), instead of thetoString()text (PreparingRebalance,Consumer), whichDisplaystill prints andparsestill reads. - Breaking:
Admin::delete_topicsandAdmin::delete_topics_with_optionsare renameddelete_topics_with_topic_collectionanddelete_topics_with_topic_collection_options, and Java's two overloads taking topic names are added asdelete_topics_with_string_sliceanddelete_topics_with_string_slice_options. Java names the parameter of all fourtopics, so each is named after its parameter's type (CLAUDE.md §2). - Breaking:
ClassicGroupDescription::newis Java's six-argument constructor, which gives the description an empty set of authorized operations; the seven-argument constructor is nowClassicGroupDescription::with_authorized_operations. - Breaking:
CreateDelegationTokenOptions::set_ownerandRemoveMembersFromConsumerGroupOptions::set_reasontake anOption, soNoneclears a value set earlier, as Java'sowner(null)andreason(null)do. - Breaking:
NewTopic::set_configstakes anOption<BTreeMap<String, String>>:Noneclears configs set earlier, as Java'sconfigs(null)does. A config value cannot be null: the broker rejects a null config value of a new topic withINVALID_CONFIG. In Python,create_topicsraisesTypeError("new_topics must not contain a NewTopic with a None config value")for one. NewTopic'sDisplayprints Java'stoString(), the maps as{k=v}and a missing map or value asnull, instead of Rust's debug syntax.AclOperation::values()andAclPermissionType::values()return the constants in declaration order, as Java'svalues()does.MockAdminClientstores a config value of null as null, as Java's mock does: aNewTopicconfig given tocreateTopicswith aNonevalue, or aSETwith aNonevalue throughincrementalAlterConfigs, reads back fromdescribe_configsasNoneinstead ofSome(""). A group config set to null reads back as its default when it has one, as Java'sputIfAbsentoverlay replaces a null value; the PythonMockAdminClientnow does the same.
- Breaking:
Sensor::record,record_with_valueandrecord_with_value_time_msreturnResult<(), Error>and check the sensor's quotas, as Java's do: a violated quota returnsQuotaViolationErrorand stops the parent sensors from recording. Newrecord_with_value_time_ms_check_quotastranslates Java'srecord(double, long, boolean). - Breaking:
GroupAuthorizationError::group_idreturnsOption<&str>,Nonewhere Java'sgroupId()isnull.GroupAuthorizationError::newtakes the message only, as Java's(String message);with_group_id(group_id, message)takes the pair. - Breaking:
Serializer::configure/closeandDeserializer::configure/closereturn a future ofResult<(), Error>, so a serde can report a failure. The producer and the consumer close both serdes and return the first failure as the cause ofFailed to close kafka producer/Failed to close kafka consumer, as Java'scloseQuietly. ReturnOk(())from your implementations. KafkaFuture::then_applyruns its function once, when this future completes (insidethen_applywhen it already has), and completes the returned future with its result, as Java does. It ran on everygetof the returned future before, and never when nobody awaited it.KafkaFuture::all_ofcompletes once every future has, with the error of the first failed one in the list, as Java'sallOf; it returned the first failure in list order without waiting for the others before.- Breaking:
Producer::metrics,Consumer::metricsandMetrics::metricsreturn aMetricsView, a live read-only view of the registry, as Java'sCollections.unmodifiableMap(metrics.metrics()): a metric registered or removed after the call shows in it. It returned a snapshotHashMapbefore.MetricsView::snapshotgives the whole map as it is now, without copying it;MetricsView::from(HashMap)builds a standalone view for a test double. - The minimum rustls version is now 0.23.46, which fixes RUSTSEC-2026-0346: the
Debugoutput of rustls's client session values exposed TLS session secrets. The client never formats those values, but the C and Python bindings were built with the affected 0.23.45. - The minimum webpki-roots version is now 1.0.10, which stops trusting the emSign (eMudhra) intermediate CAs whose private keys leaked (RUSTSEC-2026-0381). A Rust application should also update rustls-webpki to 0.103.16 (RUSTSEC-2026-0382) in its lockfile.
- Breaking:
kafka_consumer_Consumer_committed*andkafka_consumer_Consumer_offsets_for_times*(and theConsumerHandleones) keep every queried partition in the returned map, with aNULLvalue for one with no offset. - Breaking:
kafka_common_metrics_Sensor_record,_record_with_valueand_record_with_value_time_mstake a trailingout_err; newkafka_common_metrics_Sensor_record_with_value_time_ms_check_quotas. - Breaking:
kafka_common_GroupAuthorizationError_newtakes the message only,kafka_common_GroupAuthorizationError_with_group_idthe pair, andkafka_common_GroupAuthorizationError_group_idreturnsNULLwhen the group is unknown. - Breaking: a C deserializer receives the record's own headers as a mutable
kafka_common_header_internals_RecordHeaders_t *and may change them, as Java's may:Deserializer_deserialize_with_headers,Deserializer_deserialize_with_headers_bytes, their_cbtwins and thedeserialize_with_headers_async_fn_t/deserialize_with_headers_bytes_async_fn_tfunction-pointer types dropconst. kafka_common_KafkaFuture_then_applyruns the C function once, when the source future completes, and completes the returned future with its result: inside the call when the source is already complete, else from the client's__execute_callbacks, where it is queued on completion. It ran on the firstgetof the returned future before.- Breaking:
kafka_common_serialization_{Serializer,Deserializer}_configureand_closetake a trailingkafka_common_Error_t **out_err, and their_configure_cb_t/_close_cb_tcompletions receive akafka_common_Error_t *(NULLon success) beforeopaque. An error a C serde reports through__set_callback_resultreaches the caller instead of being logged. - Breaking:
kafka_producer_Producer_metrics,kafka_consumer_Consumer_metricsandkafka_common_metrics_Metrics_metricsreturn a livekafka_common_metrics_MetricsView_t *(_len,_is_empty,_contains_key,_get,_iterator,_destroy) instead of a snapshotkafka_Map_t *. - New
kafka_Iterator_t(kafka_Iterator_has_next,_next,_destroy), Java'sjava.util.Iterator, andkafka_Map_Entry_t(kafka_Map_Entry_key,_value), Java'sMap.Entry, its elements when iterating a map. kafka_admin_EndpointType_t, Java'sEndpointType: the singletonskafka_admin_EndpointType_unknown,_brokerand_controller, the C enumkafka_admin_EndpointType_eread withkafka_admin_EndpointType__enum, and_id,_from_idand_to_string.- Breaking (C API):
kafka_admin_ConfigEntry_typereturnsNULLfor an entry without a type, such as the entries ofkafka_admin_CreateTopicsResult_config, so a caller must check it beforekafka_admin_ConfigEntry_ConfigType__enum, andkafka_admin_ConfigEntryOptionsBuilder_set_config_typetakesNULLfor Java'snulltype. - Breaking (C API):
kafka_common_GroupState_name,kafka_common_ClassicGroupState_nameandkafka_common_GroupType_namereturn the constant name (PREPARING_REBALANCE), as Java'sEnum.name()does. The text_parsereads (PreparingRebalance) is what the_to_stringfunctions return. - Breaking (C API):
kafka_admin_Admin_delete_topicsandkafka_admin_Admin_delete_topics_with_optionsare renamedkafka_admin_Admin_delete_topics_with_topic_collectionandkafka_admin_Admin_delete_topics_with_topic_collection_options. The newkafka_admin_Admin_delete_topics_with_string_sliceandkafka_admin_Admin_delete_topics_with_string_slice_optionstake the topic names as akafka_List_tofconst char *. - Breaking (C API):
kafka_admin_ClassicGroupDescription_newtakes the six arguments of Java's short constructor; the seven-argument form iskafka_admin_ClassicGroupDescription_with_authorized_operations. - Breaking (C API):
kafka_admin_RemoveMembersFromConsumerGroupOptions_set_reasonwithNULLclears the reason instead of setting an empty one, andkafka_admin_CreateDelegationTokenOptions_set_ownerwithNULLclears the owner, as Java'sreason(null)andowner(null)do. - Breaking (C API): a config value passed to
kafka_admin_NewTopic_set_configsmust not beNULL, a value the broker rejects for a new topic; it used to be sent as an empty string. ANULLvalue panics and leaves the configs unchanged, whichkafka_admin_NewTopic_set_configs_errreports as anIllegalStateError. ANULLmap clears the configs, as Java'sconfigs(null)does, where it used to set an empty map. kafka_common_acl_AclOperation_valuesandkafka_common_acl_AclPermissionType_valuesreturn an owned list of the borrowed singletons in declaration order.
- Breaking:
KafkaProducer::newtakes its serializers asimpl Serializer<K> + 'static/impl Serializer<V> + 'staticand boxes them itself: passStringSerializer::new()whereBox::new(StringSerializer::new())was passed.MockProducerOptionsBuilder::set_key_serializer/set_value_serializerlikewise takeimpl Serializer<K> + 'staticinstead ofOption<Box<dyn DynSerializer<K>>>; leaving a setter uncalled is Java'snull, which the mock's no-argument constructor passes. - Breaking:
Serializer::serialize_with_headerstakes the record's headers as&mut RecordHeaders, so a serializer can add or remove headers, as Java's can. The record carries what the headers hold once the value serializer returns; they become read-only after serialization. Update the parameter type in your implementations. Serializergains Java'sconfigure(configs, is_key)andclose(), as async default methods that do nothing, so existing implementations compile unchanged.KafkaProducer::close/close_with_timeoutnow close the key serializer, then the value serializer, once each; a failure is returned as "Failed to close kafka producer". AKafkaProducerwhose constructor fails closes the serializers it was given.- A closed
KafkaProduceris freed: reference cycles in the metrics registry kept it alive afterclose. - Breaking:
ProducerConfig::newparses and validates every key with Java'sConfigDef(ProducerConfig.java), so a value Java rejects fails with Java'sConfigErrormessage,Invalid value <v> for configuration <key>: <reason>, and a value of the wrong type with Java'sparseTypemessage.partitioner.typekeeps its message for an unsupported value, and its value is now trimmed, as everySTRINGkey is. compression.gzip.level,compression.lz4.levelandcompression.zstd.levelare honoured, with Java's ranges and defaults: the producer used to compress every codec at its default level.ProducerConfiganswers Java'sAbstractConfiggetters:get_short,get_int,get_long,get_double,get_boolean,get_string,get_list(eachResult<Option<T>, Error>,Nonefor Java'snull),unused,ignore,log_unused, and the staticconfig_names. ItsPartialEq/Hashcompare the properties it was built from, as Java'sequals/hashCodedo.get_string("acks")answers the numberparseAcksmade of it (-1forall).- New
ProducerConfigconstants for keys Java'sProducerConfignames:COMPRESSION_GZIP_LEVEL_CONFIG,COMPRESSION_LZ4_LEVEL_CONFIG,COMPRESSION_ZSTD_LEVEL_CONFIG,SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIGandSOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG. - The producer logs its configuration values at INFO when it is built, as Java's does, and then, in one INFO line, the supplied keys it did not use:
These configurations '[a, b]' were supplied but are not used yet.This replaces the warning logged per unknown key and thessl.*warnings logged whensecurity.protocoldoes not use them; thessl.*/sasl.*keys are listed in the line instead.key.serializer,value.serializer,partitioner.class,interceptor.classes,metric.reportersandsecurity.providersare not producer configs here (the config takes no class), so they are listed too. KafkaProducer,MockProducer,MockProducerOptions,MockProducerOptionsBuilder,ProducerRecordOptionsBuilderandRoundRobinPartitionerimplementDebug.KafkaProducerprints its client id only, never its configuration;MockProducerits flags and how many records it sent; the mock's options whether a partitioner and serializers are set.
- Breaking:
ConsumerConfigis no longerClone: a configuration holder belongs to the client built from it, as Java'sKafkaConsumerbuilds its ownConsumerConfigfrom the properties. Build another one withConsumerConfig::new(&props)for a second consumer. - Breaking:
ConsumerRecord,ConsumerRecords,CloseOptionsandConsumerPartitionAssignor'sSubscriptionandAssignmentno longer implementPartialEqandEq: Java's classes do not overrideequals, so a field added to them later cannot break a promise of equality. Compare the getters instead. - Breaking:
KafkaConsumer::newtakes its deserializers asimpl Deserializer<K>/impl Deserializer<V>and boxes them itself: passStringDeserializer::new()whereBox::new(StringDeserializer::new())was passed. - A
KafkaConsumerwhose constructor fails closes the deserializers it was given. pollmoves the consumed positions only after the last deserializer call of the batch has finished. A cancelledpollleaves the positions where they were, and auto-commit can no longer commit records that were never returned.StringDeserializerdecodes the fetched buffer in place.- A closed consumer is freed: the rebalance listener (which can capture a
ConsumerHandle) is released onclose,MockConsumerreleases it on drop, and the metrics registry no longer keeps the consumer alive. - Breaking:
ConsumerConfig::get_stringanswers everySTRINGkey, includingsecurity.protocol,client.dns.lookup,sasl.mechanismand thessl.*location and type keys. A known key of another type now returns anIllegalArgumentError("Configuration '' is of type , not STRING") instead of a value; an unknown key is still aConfigError. - Breaking:
ConsumerHandle::group_metadatanow panics likeKafkaConsumer::group_metadataon a consumer withoutgroup.idinstead of returning a group-less value. - Breaking:
isolation.leveldefaults toread_committed, as in librdkafka, instead of Java'sread_uncommitted: a consumer no longer returns records of aborted or still open transactions, and reads only up to the last stable offset. The newConsumerConfig::DEFAULT_ISOLATION_LEVELholds the default. Setisolation.level=read_uncommittedfor the previous behaviour. - Breaking:
ConsumerConfig::SECURITY_PROVIDERS_CONFIGis removed.security.providersandpartition.assignment.strategyare no longer consumer configs: nothing read them (JSSE providers and client-side assignors have no counterpart here). Setting either now lists it in the unused-config INFO line, andget_stringon them returns aConfigError. - Breaking:
ConsumerConfig::newparses and validates every key with Java'sConfigDef(ConsumerConfig.java), so values Java rejects now fail with Java'sConfigErrormessage,Invalid value <v> for configuration <key>: <reason>: a negativeauto.commit.interval.ms,fetch.min.bytes,fetch.max.bytes,fetch.max.wait.ms,max.partition.fetch.bytes,metadata.max.age.ms,request.timeout.ms,default.api.timeout.ms, thereconnect.backoff.*/retry.backoff.*keys ormetrics.sample.window.ms;max.poll.interval.ms,max.poll.recordsormetrics.num.samplesbelow1;send.buffer.bytes/receive.buffer.bytesbelow-1; and anisolation.levelother thanread_committed/read_uncommitted(the check is case-sensitive, as Java's), which used to be accepted as given. - Breaking: as in Java,
enable.auto.commit=truewithoutgroup.idfails with anInvalidConfigurationError("enable.auto.commit cannot be set to true when default group id (null) is used."), andenable.auto.commitdefaults tofalsewithout agroup.id. - Breaking: as in Java, the keys the chosen
group.protocoldoes not support are rejected with aConfigError:group.remote.assignorwithclassic,session.timeout.msandheartbeat.interval.mswithconsumer(andshare.acknowledgement.mode/share.acquire.modewith either), e.g. "session.timeout.ms cannot be set when group.protocol=CONSUMER". An invalidgroup.protocolreports Java's message,String must be one of (case insensitive): CONSUMER, CLASSIC. - Breaking: as in Java, a blank or unknown
share.acquire.mode/share.acknowledgement.modefails with the message of Java'sShareAcquireMode.Validator/ShareAcknowledgementMode.Validator, e.g. "Invalid value `` for configuration share.acquire.mode. The value must either be 'batch_optimized' or 'record_limit'."; a blank value used to be accepted.share.acquire.modedefaults to Java's `BATCH_OPTIMIZED`, which `get_string` returns, instead of `batch_optimized`. ConsumerConfiganswers Java'sAbstractConfiggetters:get_short,get_int,get_long,get_double,get_boolean,get_string,get_list(eachResult<Option<T>, Error>,Nonefor Java'snull),unused,ignore,log_unused, and the staticconfig_names. ItsPartialEq/Hashcompare the properties it was built from, as Java'sequals/hashCodedo.- The consumer logs its configuration values at INFO when it is built, as Java's does, and then, in one INFO line, the supplied keys it did not use:
These configurations '[a, b]' were supplied but are not used yet.This replaces the warning logged per unknown key. - Breaking (Rust, C API, Python): a consumer whose channel builder cannot be created (for example an unreadable
ssl.truststore.location) now failsKafkaConsumer::newwith aConfigErrorcause, Java'sConfigException, as the producer and the admin client already did, instead ofLocalIllegalArgumentError; the outer "Failed to construct kafka consumer" error is unchanged. MockConsumerisSendbut notSyncby declaration, asKafkaConsumeris, rather than through one of its fields: a future field cannot make itSyncby accident.GroupProtocolandCloseOptions'GroupMembershipOperationimplementPartialOrdandOrd, ordering their values as Java'sEnum.compareTo, by declaration.GroupMembershipOperationimplementsDisplay, printing the Java constant's name (LEAVE_GROUP), as Java'sEnum.toString()does.ConsumerPartitionAssignor'sSubscriptionandAssignmentimplementDisplayin the format of Java'stoString(): lists print as[a, b], an absent group instance id or rack id asnull, and the user data, when set (even empty), only as its size.KafkaConsumer,MockConsumer,ConsumerHandle,ConsumerRecordOptions,ConsumerRecordOptionsBuilderandSubscriptionOptionsBuilderimplementDebug.KafkaConsumerprints its client id and group id only, never its configuration;MockConsumerwhether it is closed.
- Breaking:
DeletedRecords,RecordsToDelete,FeatureUpdate,FinalizedVersionRange,SupportedVersionRange,OffsetSpecand itsTimestampSpecare no longerCopy: a public struct is neverCopy, so a field added to it later (aString, a collection) cannot break the promise. They stayClone; write.clone()where a value was copied implicitly. - Breaking: the admin
*Optionstypes,DeletedRecords,ListOffsetsResultInfo,NewPartitionReassignment,NewPartitions,OffsetSpecand itsTimestampSpec,PartitionProducerState,PartitionReassignment,ReplicaInfo,ReplicaLogDirInfoandTopicListingno longer implementPartialEqandEq: Java's classes do not overrideequals. Compare the getters instead. - Breaking:
AdminClientConfig::newparses and validates every key with Java'sConfigDef(AdminClientConfig.java), so values Java rejects now fail with Java'sConfigErrormessage,Invalid value <v> for configuration <key>: <reason>: a negativemetadata.max.age.ms,reconnect.backoff.ms,reconnect.backoff.max.ms,retry.backoff.ms,retry.backoff.max.ms,request.timeout.ms,retries,default.api.timeout.ms,metrics.sample.window.msormetadata.recovery.rebootstrap.trigger.ms;send.buffer.bytes/receive.buffer.bytesbelow-1;metrics.num.samplesbelow1; and ametrics.recording.levelormetadata.recovery.strategyoutside Java's values. - Breaking (Rust, C API, Python):
bootstrap.controllersis no longer defined, andAdminClientConfig::BOOTSTRAP_CONTROLLERS_CONFIGis removed. Bootstrapping through the controllers (KIP-919) is not implemented, so the key stays undefined until it is: a value set for it is listed among the unused configurations, whereAdminClientConfig::newused to fail. Withoutbootstrap.serversthe configuration now builds, as Java's does, and the client's constructor fails, whateverbootstrap.resolve.timeout.msis, withFailed to create new KafkaAdminClientcaused byClientUtils'sConfigErrorNo resolvable bootstrap urls given in bootstrap.servers, the producer's and the consumer's message, whereAdminClientConfig::newused to fail with Java'sKafkaAdminClient.determineBootstrapTypemessageYou must set either bootstrap.servers or bootstrap.controllers. - Breaking (Rust, C API, Python):
enable.metrics.pushis no longer defined onProducerConfig,ConsumerConfigorAdminClientConfig, andConsumerConfig::ENABLE_METRICS_PUSH_CONFIG, released since 0.1.0, is removed (ProducerConfig::ENABLE_METRICS_PUSH_CONFIGwas never released). Client telemetry (KIP-714) is not implemented, so the key stays undefined until it is: a value set for it is listed among the unused configurations instead of being parsed and ignored, its typed getters answerUnknown configuration 'enable.metrics.push', and a value that is not a boolean no longer fails the configuration. AdminClientConfiganswers Java'sAbstractConfiggetters:get_short,get_int,get_long,get_double,get_boolean,get_string,get_list(eachResult<Option<T>, Error>,Nonefor Java'snull),unused,ignore,log_unused, and the staticconfig_names. ItsPartialEq/Hashcompare the properties it was built from, as Java'sequals/hashCodedo.- The admin client logs its configuration values at INFO when it is built, as Java's
Admin.createdoes, and then, in one INFO line, the supplied keys it did not use:These configurations '[a, b]' were supplied but are not used yet.It used to log neither. The line also lists keys Java reads and this client does not yet (themetrics.*keys), and thessl.*/sasl.*keys whensecurity.protocoldoes not use them. - Behaviour change: the admin client follows
metadata.recovery.strategy, whose default is Java'srebootstrap, where it always ran asnone. Once bootstrapped, it goes back to thebootstrap.serversaddresses when no known broker is available or ready, when a metadata update has gone unanswered formetadata.recovery.rebootstrap.trigger.ms(300000 ms by default), and at once on aREBOOTSTRAP_REQUIREDmetadata response. Setmetadata.recovery.strategy=nonefor the previous behaviour. send.buffer.bytes(default 128 KiB) andreceive.buffer.bytes(64 KiB) size the admin client's sockets; it used the operating system's defaults. These two keys and themetadata.recovery.*keys are no longer listed among the unused configurations.socket.connection.setup.timeout.max.msis honoured; the admin client usedsocket.connection.setup.timeout.msfor both bounds.- The admin types whose Java class overrides
hashCode()implementHash, so they can key aHashMapor fill aHashSetas in Java:AbortTransactionSpec,AlterConfigOp,ClassicGroupDescription,Config,ConfigEntry,ConfigSynonym,ConsumerGroupDescription,FeatureMetadata,ListConsumerGroupOffsetsSpec,MemberAssignment,MemberDescription,NewTopic,DescribeProducersOptions,ListTopicsOptions,ListTransactionsOptions,TopicDescription(without its topic id, as its equality),TransactionDescriptionandUserScramCredentialsDescription. A set or map field hashes independently of its order, as Java'sSet.hashCode()andMap.hashCode()do. - The admin enums
OpType,ConfigSource,ConfigType,UpgradeType,ScramMechanismandTransactionStateimplementPartialOrdandOrd, ordering their values as Java'sEnum.compareTo, by declaration. FeatureUpdate'sUpgradeTypeandScramMechanismimplementDisplay, printing the Java constant's name (SAFE_DOWNGRADE,SCRAM_SHA_256), as Java'sEnum.toString()does.ConsumerGroupDescription,ClassicGroupDescription,AbortTransactionOptions,DescribeProducersOptions,DescribeTransactionsOptions,FenceProducersOptions,TerminateTransactionOptionsandListTransactionsOptionsimplementDisplayin the format of Java'stoString(). An absent value prints asnull, and a set as[a, b].ListTransactionsOptionsprints its states in declaration order and its producer ids in ascending order.KafkaAdminClient,AlterConfigsResult,AlterReplicaLogDirsResult,DescribeClusterResult,DescribeConfigsResult,DescribeLogDirsResult,DescribeReplicaLogDirsResult,ListConfigResourcesResultandConfigEntryOptionsBuilderimplementDebug.KafkaAdminClientprints its client id only, never its configuration.
-
Breaking:
SslConfigsandSaslConfigsare no longerClone, like the client configurations that hold them. -
Breaking:
Quotais no longerCopy, andMetricConfig::quota()returnsOption<&Quota>instead of a copy.QuotastaysClone; writeconfig.quota().cloned()where an owned quota is needed. -
Breaking:
TopicCollectionand itsTopicIdCollectionandTopicNameCollection,ClientQuotaAlteration,SslConfigsandSaslConfigsno longer implementPartialEq(andEq): Java's classes do not overrideequals.ClientQuotaAlteration'sOpkeeps its equality, as Java'sOp.equals. Compare the getters instead. -
Breaking:
ProducerConfig,ConsumerConfigandAdminClientConfigno longer implementDefault. Build them with::new(&configs)from aHashMap<String, String>(an empty map gives the defaults). -
New
CommonClientConfigs::DEFAULT_SECURITY_PROTOCOL. -
SslConfigs::DEFAULT_SSL_KEYSTORE_TYPEandDEFAULT_SSL_TRUSTSTORE_TYPEare"PEM", the default the clients already used, instead of Java's"JKS", which the SSL factory rejects. -
New error class
LocalUnsupportedOperationError(Java'sUnsupportedOperationException), withError::local_unsupported_operationand theis_local_unsupported_operation_errorpredicate. In C it iskafka_common_Error_LOCAL_UNSUPPORTED_OPERATION(-31), built withkafka_common_Error_local_unsupported_operation. In Python it is the root classconfluent_kafka.UnsupportedOperationError, aNotImplementedError. -
Breaking (Rust, C API, Python): the calls that fail where Java throws
UnsupportedOperationException, or that this client does not support, now fail withLocalUnsupportedOperationErrorinstead ofUnsupportedVersionError(code 35):KafkaConsumer::newwithgroup.protocol=classic, the default, so every consumer that does not set the key;KafkaProducer::newwith the incrementalbuffer.memoryallocation strategy and a compression type;- the
MockAdminClientmethods Java's mock leaves "Not implemented yet", andincremental_alter_configsfor a resource type the mock does not handle; MockConsumer::offsets_for_times, and the async operations of aConsumerHandletaken from aMockConsumer;- in Python also the pure-Python
MockAdminClient/AsyncMockAdminClientandMockConsumer, completing aKafkaFuture.to_completion_stage()future from user code, andsend_offsets_to_transactionwith a mock consumer's group metadata.
For these,
is_unsupported_version_error,is_api_errorandis_kafka_errornow answerfalse; match them withis_local_unsupported_operation_error(). In Ckafka_common_Error__enumreturnskafka_common_Error_LOCAL_UNSUPPORTED_OPERATION(-31) instead ofkafka_common_Error_UNSUPPORTED_VERSION. In Python the class is not aKafkaError, soexcept UnsupportedVersionError,except ApiErrorandexcept KafkaErrorno longer catch them: useexcept UnsupportedOperationErrororexcept NotImplementedError.unregister_controller/unregister_brokeron the mock, where Java throwsUnsupportedVersionException, and every failure caused by the broker's version keepUnsupportedVersionError. -
Java's
ConfigDef(types, defaults, theparsechecks and messages, and theRange,ValidList,ValidString,CaseInsensitiveValidString,NonEmptyString,NonNullValidator,CompositeValidatorandListSizevalidators) and thessl.*/sasl.*key definitions are translated as crate-internal code, for the client configs to be built on. Deferred to later work, because each needs a new public type: a publicConfigDef, its validators,ConfigValueandLambdaValidator;get_password(a publicPassword);type_of(a publicConfigDef.Type);originals*()/values*()(Java returns aRecordingMap, and a plainHashMapnow would fix the wrong return type);documentation_of(the keys' documentation strings are not kept, as only it and Java's documentation renderers read them); how Java'sObjectconfig values are typed; and, in C, an__as_AbstractConfigview. The class-valued keys (ssl.engine.factory.class, thesasl.*.classkeys) stay undefined, as configurations never take a class.config.providersstays undefined too until config providers are translated, so a value set for it is listed as unused instead of being accepted and ignored. -
Breaking:
DynSerializer,DynDeserializerandInlineFutureare no longer public. They are the crate's own way of holding a serde behind one type without a heap allocation per record; since the clients now take serdes asimpl Serializer<K>/impl Deserializer<K>and never hand one out, no caller needs to name them, and keeping them private leaves the dispatch free to change. Code that held aBox<dyn DynSerializer<K>>passes the serializer itself to the constructor; code that implementedSerializerorDeserializeris unaffected. -
Breaking (Rust, C API, Python): under a SASL
security.protocol(SASL_PLAINTEXT,SASL_SSL), asasl.mechanismother thanPLAIN, the one mechanism this client implements, now failsProducerConfig::new,ConsumerConfig::newandAdminClientConfig::new(and so the clients' constructors) withConfigErrorInvalid value <m> for configuration sasl.mechanism: only PLAIN is supported by this client, instead of failing at authentication. For SCRAM overSASL_PLAINTEXTthe old path sent the password in cleartext as a PLAIN token before the broker rejected it.sasl.mechanismkeeps Java'sGSSAPIdefault, so a SASL configuration that leaves it unset now fails at construction with this clear error, namingGSSAPI, instead of a misleading "requires a username" or a broker-side handshake failure: setsasl.mechanism=PLAIN. An empty mechanism keeps Java's ownConfigErrormessage. -
Breaking (Rust, C API, Python):
ssl.keystore.password,ssl.truststore.passwordandssl.key.passwordare no longer defined, andSslConfigs::SSL_KEYSTORE_PASSWORD_CONFIG,SSL_TRUSTSTORE_PASSWORD_CONFIGandSSL_KEY_PASSWORD_CONFIGare removed. None of them can work in this client: PEM is the only store format, and Java rejects a store password with PEM stores; and encrypted PEM private keys, which Java decrypts with the key password, are not supported. A value set for one of them is now listed among the unused configurations instead of being accepted and ignored, and reading one throughget_stringfails withUnknown configuration. An encrypted PEM private key (ENCRYPTED PRIVATE KEY, or a legacy block withProc-Type: 4,ENCRYPTED) now fails the clients' constructors with aConfigErrorcause,Failed to create channel builder: Encrypted PEM private keys are not supported by this client; provide an unencrypted PKCS#8 key, where it used to fail withNo private key found in inline keystore key,No private key found in keystore file '<path>'or a PEM parse error; the outer error ("Failed to construct kafka producer", "Failed to construct kafka consumer", "Failed to create new KafkaAdminClient") is unchanged. -
Breaking (Rust, C API, Python):
ssl.cipher.suitesis honoured. The clients offer the configured suites, named as in Java and IANA (TLS_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384), in the configured order; an empty list keeps the TLS provider's defaults, asssl.protocolrestricts them (below). Every suite of the aws-lc-rs provider is accepted. The key used to be read only to log a warning and then ignored. An unknown name fails the clients' constructors with aConfigErrorcause,Failed to create channel builder: Unsupported CipherSuite: <name>, where Java fails the first connection with the same message. -
Breaking (Rust, C API, Python):
ssl.protocolis honoured as JSSE honours it. It used to be defined and ignored. It selects Java'sSSLContext.getInstance(protocol), which supplies only the default lists: its default protocols, used whenssl.enabled.protocolsis empty, and its default cipher suites (the provider's suites usable with those protocols), used whenssl.cipher.suitesis empty; a protocol is used only when an enabled suite can be used with it. So withTLSv1.2and the default suites the clients do not use TLS 1.3 even when it is enabled, while a TLS 1.3 suite inssl.cipher.suitesallows it, as in Java.TLSv1.3(the default),TLSandSSLdefault to TLS 1.3 and TLS 1.2.TLSv1.1,TLSv1andSSLv3default to versions this client does not implement (nor does the JDK enable them), so with an emptyssl.cipher.suitesthey fail the clients' constructors (No cipher suite is enabled: ssl.cipher.suites is empty and none of the TLS provider's cipher suites can be used with the protocols of ssl.protocol = TLSv1.1 (this client implements TLS 1.2 and TLS 1.3 only)), and with a list they use it. Names match ignoring case. Another value (Default, a DTLS context, an unknown name) fails the constructors (Unsupported TLS protocol: '<value>'. Supported protocols: TLSv1.3, TLSv1.2, TLSv1.1, TLSv1, SSLv3, TLS, SSL), and so do enabled protocols none of which an enabled suite can be used with (No TLS protocol of ssl.enabled.protocols = [TLSv1.3] can be used with the enabled cipher suites (ssl.protocol = TLSv1.2, ssl.cipher.suites = [])). Java reports these two at the handshake instead (No appropriate protocol). -
client.dns.lookup=resolve_canonical_bootstrap_servers_onlynow resolves each bootstrap address to its canonical host name as Java'sInetAddress.getCanonicalHostName()does: a reverse (PTR) lookup through the system resolver, confirmed by a forward lookup that must return the address, with the textual IP as the fallback (new dependencydns-lookup). Where PTR records exist the bootstrap node's host is the FQDN, so TLS hostname verification checks it as in Java, where it used to be the textual IP; an empty canonical name becomeslocalhost, Java's node host for it. The warning these configurations logged for this mode with TLS is removed. -
TopicPartitionInfo,MetricNameTemplate,ClientQuotaFilter,Quota,SslClientAuth,RecordingLevelandDeserializationErrorOriginimplementHash, as their Java classes overridehashCode(). -
ClientQuotaAlteration'sOpimplementsEqandHash. Its value is compared as Java'sDouble.equalscompares it: everyNaNequals every other, and0.0differs from-0.0. -
Quotacompares its bound the same way. Java compares it with the primitive==, under whichNaNdiffers from itself, which anEqcannot express. ANaNquota now equals itself, and an upper bound of0.0no longer equals one of-0.0; every other bound compares as before. -
Every enum translating a Java enum implements
PartialOrdandOrd, ordering its values as Java'sEnum.compareTo, by declaration. New here:ClassicGroupState,ConfigResource'sType,SslClientAuth,ElectionType,DeserializationErrorOrigin,GroupState,GroupType,IsolationLevel,RecordingLevel,TimestampTypeandSecurityProtocol. -
ConfigResource'sType,ElectionType,RecordingLevelandDeserializationErrorOriginimplementDisplay, printing the Java constant's name (BROKER_LOGGER,UNCLEAN), as Java'sEnum.toString()does. -
The metric stats implement
Displayin the format of Java'stoString(), doubles printed as Java'sDouble.toString.SampledStatand itsSampleprint their own format, andAvg,Max,Min,WindowedCountandWindowedSumprint theSampledStatthey inherit it from, as in Java.CumulativeCountprints asCumulativeSum,SimpleRateasRate, andMeterprints its rate, total and the two metric names. -
Metrics,Sensor,KafkaMetric,NamedMeasurable,ClosureMeasurable,SensorOptions,SensorOptionsBuilderand the metric stats (SampledStat,Avg,Max,Min,WindowedCount,WindowedSum,Rate,SimpleRate,Meter) implementDebug.Metricsprints how many sensors and metrics it holds,Sensorits name, andKafkaMetricwhat itsDisplayprints.
- Breaking (C API):
kafka_common_metrics_MetricConfig_quotareturns a borrowedconst kafka_common_metrics_Quota_t *, valid until the config handle is destroyed or one of its setters runs, instead of an owned copy: do not pass it tokafka_common_metrics_Quota_destroy. - Breaking (C API): serializers and deserializers are registered only through
kafka_common_serialization_Serializer_new_async/kafka_common_serialization_Deserializer_new_async. The synchronousSerializer_new/Deserializer_newconstructors, their_errtwins and the synchronous_fn_ttypedefs are removed. - Breaking (C API): the parameters of the published constructor
kafka_common_serialization_Serializer_new_asyncchanged: it takes two more nullable function pointers,configureandclose, after the serialize pointers (NULLkeeps Java's no-op default). Existing calls must pass them. - Breaking (C API): a C serializer receives the record's own headers as a mutable
kafka_common_header_internals_RecordHeaders_t *and may change them:Serializer_serialize_with_headers, its_cbtwin and theserialize_with_headersfunction-pointer type dropconst. A deserializer still gets them read-only, without a copy.RecordHeaders__as_Headersnow takes aconsthandle, andByteArraySerializer__as_Serializer/StringSerializer__as_Serializerreturn a non-constview. kafka_common_serialization_Serializer__is_async/Deserializer__is_asyncanswer 1 for a C implementation and 0 for a built-in class's view.- Breaking (C API):
current_lagreturns Java'sOptionalLongas a presence flag:kafka_consumer_Consumer_current_lagandkafka_consumer_ConsumerHandle_current_lagreturnint8_t(1 when a lag is known) and write the lag to anint64_t *out_lag; the_cbcompletion type gains a leadingint8_t presentargument. kafka_producer_Producer_send_with_callbackdocuments that the callback handle is consumed by the call.kafka_admin_AdminClientConfig_tanswersAbstractConfig's getters:kafka_admin_AdminClientConfig_get_short,_get_int,_get_long,_get_doubleand_get_booleanreturn1with the value in*out_valueand0for Java'snull;_get_stringreturns a string borrowed from the handle;_get_list,_unusedand_config_namesreturn an ownedkafka_List_t; plus_ignoreand_log_unused. A client created from the handle keeps its own record of the keys it used.kafka_consumer_ConsumerConfig_tanswers the same getters:kafka_consumer_ConsumerConfig_get_short,_get_int,_get_long,_get_double,_get_boolean,_get_list,_unused,_ignore,_log_unusedand_config_names, beside the existing_get_string. A consumer created from the handle keeps its own record of the keys it used, and runs under the handle'sclient.id, the one_get_stringanswers: the consumers of one handle share it, as Java's consumers given oneConsumerConfigdo.kafka_producer_ProducerConfig_tanswers the same getters:kafka_producer_ProducerConfig_get_short,_get_int,_get_long,_get_double,_get_boolean,_get_string,_get_list,_unused,_ignore,_log_unusedand_config_names. A producer created from the handle keeps its own record of the keys it used, and runs under the handle'sclient.id, the one_get_stringanswers: the producers of one handle share it, as Java's producers given oneProducerConfigdo. A generated id used to take a second number from theproducer-<n>sequence, so the handle'sproducer-1built aproducer-2.- Each configuration warning of the C config handles (
kafka_consumer_ConsumerConfig_t,kafka_producer_ProducerConfig_t,kafka_admin_AdminClientConfig_t) is logged once per handle, when_newbuilds it, not again for every client created from it, as Java's one config object per client logs it once._newsets up the default stderr logger first, as creating a client does, so the warnings are not lost when the handle is created before any client. - New
_to_stringexports, each returning an owned string freed withkafka_string_destroy, for the enums that gainedDisplay:kafka_admin_FeatureUpdate_UpgradeType_to_string,kafka_admin_ScramMechanism_to_string,kafka_common_ElectionType_to_string,kafka_common_config_ConfigResource_Type_to_string,kafka_common_metrics_Sensor_RecordingLevel_to_string,kafka_common_RecordDeserializationError_DeserializationErrorOrigin_to_stringandkafka_consumer_CloseOptions_GroupMembershipOperation_to_string. - New
_to_stringexports for the admin types that gainedDisplay:kafka_admin_ConsumerGroupDescription_to_string,kafka_admin_ClassicGroupDescription_to_string,kafka_admin_AbortTransactionOptions_to_string,kafka_admin_DescribeProducersOptions_to_string,kafka_admin_DescribeTransactionsOptions_to_string,kafka_admin_FenceProducersOptions_to_string,kafka_admin_TerminateTransactionOptions_to_stringandkafka_admin_ListTransactionsOptions_to_string. Each returns an owned string freed withkafka_string_destroy. - New
_to_stringexports for the stats and assignor types that gainedDisplay:kafka_common_metrics_stats_SampledStat_to_string,kafka_common_metrics_stats_SampledStat_Sample_to_string,kafka_common_metrics_stats_Avg_to_string,kafka_common_metrics_stats_Max_to_string,kafka_common_metrics_stats_Min_to_string,kafka_common_metrics_stats_WindowedCount_to_string,kafka_common_metrics_stats_WindowedSum_to_string,kafka_common_metrics_stats_CumulativeSum_to_string,kafka_common_metrics_stats_CumulativeCount_to_string,kafka_common_metrics_stats_Rate_to_string,kafka_common_metrics_stats_SimpleRate_to_string,kafka_common_metrics_stats_Meter_to_string,kafka_consumer_ConsumerPartitionAssignor_Subscription_to_stringandkafka_consumer_ConsumerPartitionAssignor_Assignment_to_string. Each returns an owned string freed withkafka_string_destroy.
Second preview release. The client now follows Apache Kafka 4.4, the C API was rewritten to one uniform set of conventions, and serializers and deserializers became async traits. There are many breaking changes; the entries below say what to change.
- Breaking:
Serializeris an async trait (its methods returnimpl Future + Send) and hasSend + Syncsupertraits, so it is no longer dyn-compatible. Hold serializers asBox<dyn DynSerializer<K>>;Box::new(StringSerializer::new())coerces to it.serializereturnsOption<Cow<'_, [u8]>>, so a serializer can hand back bytes it already owns.serialize_headersandserialize_owned_headersare removed (useserialize_with_headers/serialize_owned_with_headers). Calls throughDynSerializerstore the future inline (256 bytes) instead of boxing it. - Breaking: the producer
Callbackis a trait instead of a boxed closure type; build one from a closure withcallback::new. - Breaking: constants that are not Java's on these classes were removed from
ProducerConfig,ConsumerConfigandAdminClientConfig(SECURITY_PROTOCOL_CONFIG,SASL_MECHANISM_CONFIG,SASL_JAAS_CONFIG,METADATA_MAX_AGE_MS_CONFIG,METADATA_RECOVERY_*, ...); use the keys fromCommonClientConfigsandSaslConfigs, as in Java.RecordMetadata::INVALID_OFFSETis no longer public. - Breaking:
ProducerRecord::headers_mut/into_parts,RecordMetadata::topic_partitionandMockProducer::committed_offsetare removed.MockProduceris no longerUnwindSafe/RefUnwindSafe. - Kafka 4.4: rack-aware partitioning (KIP-1123,
partitioner.rack.awarewith the producer'sclient.rack), andTxnOffsetCommitv6 with topic ids (KIP-1319) when the broker supports it. - Transaction latency metrics are recorded;
acksandtransactional.idare validated as in Java;group.instance.idis sent in transactional offset commits; boolean configuration values are case-insensitive.
- Breaking:
KafkaConsumeris now a concrete type,KafkaConsumer<K, V>, andKafkaConsumer::newreturns it instead of aBox<dyn Consumer<K, V>>. Calling aConsumermethod on it, or through generic code takingC: Consumer<K, V>, no longer boxes the returned future.KafkaConsumerisSendbut notSync, matching Java's single-threaded consumer; to reach it from another task (for example to callwakeup) useconsumer.handle(). - Breaking: the asynchronous methods of the
Consumertrait returnimpl Future + Sendinstead of using#[async_trait], so the trait is no longer dyn-compatible. Implementations can still be written withasync fn. - New
DynConsumertrait for dynamic dispatch (Box<dyn DynConsumer<K, V>>), implemented automatically for everyConsumer, asDynProduceris forProducer. ReplaceBox<dyn Consumer<K, V>>withBox<dyn DynConsumer<K, V>>; with onlyConsumerimported, method calls on it keep working unchanged. - Breaking:
assignment,subscription,paused,group_metadataandcurrent_lagtake&mut self, following Java's guard on these methods.client_idis removed from the trait (it is not on Java'sConsumer). - Breaking:
ConsumerHandlekeeps only the methods of KIP-1306's callback view:subscription,assignandcommit_async_offsetsare removed. Its calls are accepted only from inside a rebalance listener or commit callback; elsewhere they fail with a concurrent-modification error. - Breaking:
Deserializeris an async trait, held asBox<dyn DynDeserializer<V>>.deserialize_with_headerstakes&RecordHeaders;deserialize_headers,deserialize_from_sharedanddeserialize_from_shared_headersare replaced by KIP-863'sdeserialize_with_headers_bytes(topic, headers, &Bytes), which receives the record's slice of the fetch buffer.configureandcloseare async. The consumer closes its deserializers inclose(failures reported as "Failed to close deserializers"); dropping it no longer does. - Breaking:
ConsumerConfiglost its typed getters and setters (bootstrap_servers,set_*, ...); read values by key, for example withget_string.CloseOptions::DEFAULT_CLOSE_TIMEOUT_MSis removed. - Breaking: renames to Java's names under the overload rules:
CloseOptions::new_timeout→new_with_timeout,CloseOptions::new_group_membership_operation→with_operation,ConsumerNoOffsetForPartitionError::for_partitions→with_partitions,ConsumerRecords::records_partition/records_topic→records_with_partition/records_with_topic. - Kafka 4.4:
MockConsumer::lose_partitions, and every consumer sensor is removed on close. wakeupfollows Java'sWakeupTrigger: a result that is already ready wins over a later wakeup, and a wakeup is checked even when no time is left. AnOffsetCommitCallbackerror propagates as in Java.- The fetch path is cancel-safe. Offset retries wake the background task,
closepasses the remaining time on, andbeginning_offsets/end_offsets/offsets_for_timesno longer wait about 5 seconds. - Fixed:
client.rackwas never sent in KIP-848 heartbeats; offset fetches used the member epoch from request creation; aREBOOTSTRAP_REQUIREDdisconnect could panicpoll; a zero-timeoutpollnever yielded; a closed consumer was never freed.
- Breaking:
DescribeTopicsResultandDeleteTopicsResultare structs instead of enums, keyed by topic name or topic id. - Breaking:
AdminClientConfigis no longerCloneand lost its typed getters (bootstrap_servers,client_id,ssl_config, ...). - Breaking:
MockAdminClient::create()returns aMockAdminClient.Builderas in Java (MockAdminClient::new(),with_brokers_controller,set_controller,set_fetches_remaining_until_visiblewere added;set_feature_levelsandset_broker_log_dirsare removed). - Breaking: renames to Java's names:
group_type,config_typeandresource_typegetters →r#type,ClientQuotaFilterComponent::match_spec→r#match,ListConsumerGroupOffsetsResult::partitions_to_offset_and_metadata_for_group→partitions_to_offset_and_metadata_with_group_id,RecordsToDelete::before_offset_with_offset→with_offset,NewPartitions::increase_to_new_assignments→increase_to_with_new_assignments.RemoveMembersFromConsumerGroupOptions::newtakes no arguments (with_memberstakes the members).DelegationToken::token_info_mutis removed andGroupOffsetsis no longer public. - New
Admin::unregister_controller(Kafka 4.4), with its options and result. describe_topicsby name usesDescribeTopicPartitions, as Java does.TopicPartitionInfo::elr/last_known_elrreturn lists.- Fixed: calls made before
closecomplete; calls after it fail with "Cannot accept new calls when AdminClient is closing."; a zero topic id no longer panics; lookup retries honourretries;DeleteTopicsthrottling starts at v2.
- Up to Apache Kafka 4.4: KIP-909 optional asynchronous bootstrap DNS resolution (
bootstrap.resolve.timeout.ms, default 0 keeps the previous behaviour), KIP-1242 cluster-id checks (metadata.cluster.check.enable, default true), error codes 134–136,BootstrapResolutionError, andUnsupportedProtocolFieldwith theis_unsupported_version_errorpredicate. - Every Java exception class has its own predicate on
Error(is_<class>_error, meaning Java'sinstanceof); classify errors with them rather than by matching variants. - Breaking: functional interfaces are traits with factory functions:
KafkaFuture'sBaseFunction(kafka_future::BaseFunction_new) andMetricValueProvider(an enum before, now a trait withnew/with_*factories).GaugeextendsMetricValueProviderand lostvalue;ClosureGaugeis removed. - Breaking:
Metrics,SensorandMetricConfigkeep only Java's public methods: themetric_name_*,sensor_*,add_metric_*andmetric_instance_*variants were renamed or removed, as wereSensor::record_value*,expire_sensorsandMetricConfig::set_time_window_ms. - Breaking:
Headers::add_header/add_key_value→add_with_header/add_with_key_value. - Breaking:
Uuid::zero()→Uuid::ZERO_UUID;most_sig_bits/least_sig_bits→most_significant_bits/least_significant_bits;to_base64_stringis removed (useDisplay).KafkaFuture::completed→completed_future;join_map,join_map_resultsandthen_apply_tryare removed.TopicPartition::topic_arcandSaslConfigs::resolve_username/resolve_passwordare removed;PatternType::VALUESandResourceType::VALUESare removed. - Public enum variants that carry data wrap a crate type (for example
TopicCollection,OffsetSpec), so the payload can grow without a breaking change. - Password configuration values are a
Passwordtype shown as[hidden];ProducerConfig'sDebugprints keys only. - Hardening against malformed or hostile input: bounded allocations when decoding arrays, strings, tagged fields and compressed data; compressed batches are decompressed one record at a time; a record above 2147483639 bytes is refused; a snappy block is capped at 512 MiB; a negative string length inside an array is rejected.
metadata.recovery.strategyis honoured by the producer and the consumer.- Fixed: a read readiness could be stranded for about 30 seconds in the selector.
- Breaking (C API): the C API was rewritten to one set of conventions. Code written against 0.1.1 needs porting; the main changes are:
- Headers.
confluent_kafka.his the full API; language bindings includeconfluent_kafka_bindings.h, where every non-fallible function appears as its_errtwin. Every export catches Rust panics and reports them as anIllegalStateError. - Errors. Fallible functions take a trailing
kafka_common_Error_t **out_err.kafka_common_Error_codeandkafka_common_Error_neware removed:kafka_common_Error__enumgives the class id, each class has its own constructor (kafka_common_Error_local_illegal_argument,kafka_common_Error_local_callback, ...), payload views expose extra fields, and the predicates (kafka_common_Error_is_retriable_error, ...) returnint8_t. - Configuration and clients. The
*Propertiesbuilders (kafka_producer_ProducerProperties_*,kafka_consumer_ConsumerProperties_*,kafka_admin_AdminClientProperties_*) are replaced bykafka_producer_ProducerConfig_new,kafka_consumer_ConsumerConfig_newandkafka_admin_AdminClientConfig_new.kafka_producer_KafkaProducer_newandkafka_consumer_KafkaConsumer_newreturn owned class handles, freed with their_destroy; thekafka_producer_Producer_*/kafka_consumer_Consumer_*operations take the borrowed__as_Producer/__as_Consumerview.kafka_producer_Producer_destroyandkafka_consumer_Consumer_destroyare removed. - Asynchronous calls. The
_asyncfunctions and their*_callback_ttypedefs are replaced by_cbtwins. Completions are queued on the client and run by<Client>__execute_callbacks;<Client>__set_callbacks_notifysays when there is work. There is no dispatcher thread, and_destroyruns what is still pending. A record's future completes only after its delivery callback has run. - Interfaces. Traits (serializers, listeners, callbacks) are built with
<Interface>_new(self, fn pointers...), aNULLpointer meaning Java's default; classes give a borrowed<Class>__as_<Interface>view. An async method reports through<Client>__set_callback_result. - Admin.
kafka_admin_AdminClient_*becomeskafka_admin_Admin_*(created withkafka_admin_AdminClient_create); each RPC returns a<Rpc>Result_tholding onekafka_common_KafkaFuture_tper key, and takes a<Rpc>Options_tin its_with_optionsform.kafka_admin_MockAdminClient_createreturns a builder. - Collections. The per-type list and map helpers (
StringList,TopicPartitionList,OffsetAndMetadataMap,MetricMap, ...) and the indexed accessors (*_count,TopicPartitionInfo_replica,ConsumerRecord_header_*) are replaced bykafka_List_t/kafka_Map_treturning accessors (TopicPartitionInfo_replicas,_isr,_elr). - Types. Booleans are
int8_t; enums are handles with a C_eenum and__enum()(for exampleConfigEntry_sourcereturns akafka_admin_ConfigEntry_ConfigSource_t *); optional values such as leader and group epochs are returned directly with-1for none instead of through an out-parameter;kafka_consumer_ConsumerRecord_valuereturns the deserializedvoid *.
- Headers.
v0.1.1
First preview release of the Rust Kafka client: a translation of the Apache Kafka Java client (4.3.1) that keeps its architecture, names and behavior, adapted to Rust conventions and to async Rust on Tokio.
Preview: not yet recommended for production use. The public API is not stable before the 1.0 GA release and may change. We welcome your feedback while the design is still open.
KafkaProducerbehind theProducertrait, plusDynProducerfor dynamic dispatch (Box<dyn DynProducer<K, V>>).sendandsend_with_callback, returning a future that resolves to the record'sRecordMetadata;flush,partitions_for,metrics,closeandclose_with_timeout.- Idempotent producer, with the Java client's sequence tracking, epoch bump and recovery.
- Transactions:
init_transactions,begin_transaction,send_offsets_to_transaction,commit_transactionandabort_transaction. - Built-in sticky partitioner,
RoundRobinPartitioner, and custom partitioners through thePartitionertrait. - Producer interceptors.
- Batching, linger, retries with exponential backoff, delivery timeout and in-flight request limits, as in the Java client.
- Zero-copy send path: keys, values and headers are written straight into the batch buffer, and requests go out with vectored I/O.
MockProducerandMockPartitionerfor tests.
KafkaConsumer::newreturns aBox<dyn Consumer<K, V>>backed by the KIP-848 consumer group protocol (group.protocol=consumer).- Subscription by topic list or by
SubscriptionPattern(a regular expression evaluated by the broker), with or without aConsumerRebalanceListener; manual assignment withassign;unsubscribe. poll, returningConsumerRecordstogether with the next offset to consume for each partition.- Offset management:
commit_syncandcommit_async(with or without explicit offsets and anOffsetCommitCallback),committed,position,seek_*,seek_to_beginningandseek_to_end. - Offset lookups:
beginning_offsets,end_offsets,offsets_for_timesandcurrent_lag. pause/resume,partitions_for,list_topics,group_metadata,metrics,enforce_rebalance.- Rebalance listeners run on the caller's task during
poll, and can call back into the consumer through aConsumerHandle(for example tocommit_syncon revocation). wakeupto interrupt a blocking call, andclose/close_with_optionsusingCloseOptions.read_committedandread_uncommittedisolation levels.- Consumer interceptors.
- Zero-copy receive path: deserializers borrow from the fetched buffer.
MockConsumerfor tests.
AdminClient::createreturns aBox<dyn Admin>. Every operation returns immediately with a result holding oneKafkaFutureper key, as in Java, and has a_with_optionsvariant.- Topics and partitions:
create_topics,delete_topics,list_topics,describe_topics_*,create_partitions,delete_records,list_offsets,elect_leaders,alter_partition_reassignments,list_partition_reassignments. - Cluster and configuration:
describe_cluster,describe_configs,incremental_alter_configs,list_config_resources,describe_features,update_features. - Log directories:
describe_log_dirs,alter_replica_log_dirs,describe_replica_log_dirs. - Groups:
list_groups,describe_consumer_groups,describe_classic_groups,list_consumer_group_offsets_*,alter_consumer_group_offsets,delete_consumer_group_offsets,delete_consumer_groups. - Transactions and producers:
describe_producers,describe_transactions,list_transactions,abort_transaction,fence_producers,force_terminate_transaction. - Security:
create_acls,describe_acls,delete_acls,describe_client_quotas,alter_client_quotas,describe_user_scram_credentials,alter_user_scram_credentials, and delegation tokens (create,renew,expire,describe). MockAdminClientfor tests, mirroring the Java mock.
- Networking on Tokio non-blocking I/O, with one selector multiplexing all broker connections, as in the Java client.
- Wire protocol generated from the official Kafka JSON message definitions, including flexible versions and tagged fields.
- TLS through rustls with the aws-lc-rs crypto provider, including mutual TLS and hostname verification. Keys and certificates are PEM, either as files or inline in the configuration.
- SASL/PLAIN authentication over
SASL_PLAINTEXTandSASL_SSL. - Compression: gzip, snappy, lz4 and zstd.
- Serializers and deserializers for strings and byte arrays, a deserializer for
Bytes, plus custom ones through theSerializer/Deserializertraits. - A single
Errortype for every fallible API, with predicates that rebuild the Java exception hierarchy (is_retriable_error,is_api_error,is_authorization_error, ...). - Client metrics and configuration keys use the Java client's names.
- Every client logs a preview warning at startup through the
logcrate.
- Classic consumer group protocol (
group.protocol=classic) and client-side partition assignors are not supported. - Share groups (KIP-932) and the share consumer are not included.
- Of the SASL mechanisms, only
PLAINis supported (no SCRAM, GSSAPI or OAUTHBEARER). - JKS and PKCS12 keystores and truststores are not supported; convert them to PEM.