{"id":"d3ef4a8ae9844d21","repo":"apache/kafka","slug":"failed-to-construct-kafka-share-consumer-d3ef4a","errorCode":null,"errorMessage":"Failed to construct Kafka share consumer","messagePattern":"Failed to construct Kafka share consumer","errorType":"exception","errorClass":"KafkaException","httpStatus":null,"severity":"critical","filePath":"clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareConsumerImpl.java","lineNumber":355,"sourceCode":"                    logContext,\n                    metadata,\n                    subscriptions,\n                    new ShareFetchConfig(config),\n                    deserializers);\n\n            this.kafkaShareConsumerMetrics = new KafkaShareConsumerMetrics(metrics);\n\n            config.logUnused();\n            AppInfoParser.registerAppInfo(CONSUMER_JMX_PREFIX, clientId, metrics, time.milliseconds());\n            log.debug(\"Kafka share consumer initialized\");\n        } catch (Throwable t) {\n            // Call close methods if internal objects are already constructed; this is to prevent resource leak.\n            // We do not need to call `close` at all when `log` is null, which means no internal objects were initialized.\n            if (this.log != null) {\n                close(Duration.ZERO, true);\n            }\n            // Now propagate the exception\n            throw new KafkaException(\"Failed to construct Kafka share consumer\", t);\n        }\n    }\n\n    // Visible for testing\n    ShareConsumerImpl(final LogContext logContext,\n                      final String clientId,\n                      final String groupId,\n                      final ConsumerConfig config,\n                      final Deserializer<K> keyDeserializer,\n                      final Deserializer<V> valueDeserializer,\n                      final Time time,\n                      final KafkaClient client,\n                      final SubscriptionState subscriptions,\n                      final ShareConsumerMetadata metadata) {\n        this.clientId = clientId;\n        this.groupId = groupId;\n        this.log = logContext.logger(getClass());\n        this.time = time;","sourceCodeStart":337,"sourceCodeEnd":373,"githubUrl":"https://github.com/apache/kafka/blob/c31c9215e131f8c17e79f8901b48c13ee6aa8e7a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareConsumerImpl.java#L337-L373","documentation":"KafkaException thrown from the ShareConsumerImpl public constructor's outer try/catch when any Throwable escapes during initialization. Distinct from the delegate-creator wrapping: this is the construction site itself — it first attempts close(Duration.ZERO, true) on any partially-built internals (to prevent resource leaks when log is already assigned) and then wraps the cause. So a single failed construction can both clean up and surface a uniform error.","triggerScenarios":"Constructing ShareConsumerImpl directly (or via the delegate creator, which then re-wraps). Any step in the constructor body — metrics setup, deserializer wiring, NetworkClientDelegate/RequestManagers/ApplicationEventProcessor supplier builds, AppInfoParser.registerAppInfo, ShareFetchCollector construction — throws. The catch block closes already-built components and re-throws wrapped in KafkaException.","commonSituations":"Misconfigured metrics reporters (e.g. a reporter class that fails to initialize), JMX registration collision (AppInfoParser.registerAppInfo failing because another MBean with the same clientId is already registered), deserializer configuration errors, broker/bootstrap resolution failures surfacing during initial metadata, or running in a security-restricted environment where thread/selector creation fails. Most often the real cause is a ConfigException or a Reflection/ClassNotFoundException.","solutions":["Inspect the cause chain of the KafkaException; the root Throwable identifies the failing initialization step.","If JMX/MBean collision: use a unique client.id per consumer instance or disable JMX reporting in the container.","Verify all required ConsumerConfig keys are present and well-typed (bootstrap.servers, group.id, key/value deserializer, metrics reporters).","Check that deserializer and metrics-reporter classes are on the classpath and their constructors do not throw.","Reproduce in isolation with minimal config to confirm whether the failure is environment-specific (security manager, thread limits)."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"// Reduce the surface for init failures by validating config + deserializers first.\ntry {\n    ConsumerConfig cfg = new ConsumerConfig(props); // throws ConfigException for bad keys/values\n    keyDeserializer.configure(cfg.originals(Collections.singletonMap(\"key\", \"\")), true);\n    valueDeserializer.configure(cfg.originals(Collections.singletonMap(\"value\", \"\")), false);\n} catch (Exception e) {\n    throw new IllegalStateException(\"Share consumer preconditions failed\", e);\n}","typeGuard":null,"tryCatchPattern":"// The constructor closes partially-built state before rethrowing, so callers\n// only need to translate the wrapped KafkaException.\nimport org.apache.kafka.common.KafkaException;\n\nShareConsumer<K,V> consumer;\ntry {\n    consumer = new KafkaShareConsumer<>(props, keyDeser, valueDeser);\n} catch (KafkaException e) {\n    // 'Failed to construct Kafka share consumer' — examine getCause().\n    // Common causes: Deserializer instantiate error, SSL/TLS, Metrics, AppInfoParser JMX.\n    log.error(\"Share consumer init failed: {}\", e.getCause(), e);\n    throw e;\n}","preventionTips":["The constructor calls close(Duration.ZERO, true) on failure — do not also call close() yourself in the catch block.","Deserializer instantiation is the most common culprit; construct and configure them outside and reuse to isolate the failure.","Validate required configs (group.id, bootstrap.servers) before construction — missing required keys throw ConfigException which propagates as the cause.","Run with -Dcom.sun.management.jmxremote=false or unique client ids if AppInfoParser JMX registration clashes."],"tags":["kafka","share-consumer","initialization","construction","resource-leak"],"analyzedSha":"c31c9215e131f8c17e79f8901b48c13ee6aa8e7a","analyzedAt":"2026-08-03T12:34:05.770Z","schemaVersion":2}