Current state: Under discussion
Discussion thread: here
JIRA: here TBD
Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).
Being able to centrally monitor and troubleshoot problems with Kafka clients is becoming increasingly important as the use of Kafka is expanding within organizations as well as for hosted Kafka services. The typical Kafka client user is now an application owner with little experience in operating Kafka clients, while the cluster operator has profound Kafka knowledge but little insight in the client application.
Troubleshooting Kafka problems is currently an organisationally complex issue, with different teams or even organisations running the client applications and the brokers. While some organisations may already have custom collection of existing client metrics in place, most do not and metrics are typically not available when the problem needs to be analysed. Enabling metrics after-the-fact may not be possible without code change to the application, or at least a restart, which typically means the required metrics data is lost.
While the broker already tracks request-level metrics for connected clients, there is a gap in the end-to-end monitoring when it comes to visibility of client internals, be it queue sizes, internal latencies, error counts, application behaviour (such as message processing rate), etc. These are Kafka client metrics, and not application metrics.
This proposal aims to provide a generic and standardised interface through which a cluster operator or an external system may request and a client can push client-side metrics to the broker, a plugin interface for how those metrics are handled by the broker, and a minimum set of standard pre-defined metrics that a Kafka client should expose through this interface. A supporting client should have metrics enabled by default and not require any extra configuration, and will provide at least the standardised metrics as outlined later in this proposal.
One of the key goals of this KIP is to have the proposed metrics and telemetry interface generally available and enabled by default in all of the mainstream Kafka clients, allowing troubleshooting and monitoring as needed without interaction from cluster end-users. While metrics are to be enabled by default on the clients, the brokers still need to be configured with a metrics plugin, and metrics subscriptions must be configured on the cluster before any metrics are sent and collected.
User privacy is an important concern and extra care is taken in this proposal to not expose any information that may compromise the privacy of the client user.
This KIP introduces the following new public interfaces:
- New PushTelemetryRequest protocol request type.
- Updated metrics receiver interface in the broker to accustom for the new semantics and format.
- A new CLIENT_METRICS ConfigEntry resource type for configuring metrics subscriptions.
- kafka-client-metrics.sh CLI script to configure and list client metrics subscriptions.
The metric collection is opt-in on the broker and opt-out on the client.
For metrics to be collected a MetricsPlugin (see below) must be configured on the brokers, and at least one metrics subscription must be configured through the Admin API. Only then will metrics subscriptions be propagated to clients, and only then will clients push metrics to the broker. It is thus up to the cluster operator to explicitly enable client metrics collection.
The metrics format for PushTelemetryRequestV0 is OpenTelemetry Protobuf protocol definitions version 0.11.
Future versions of PushTelemetryRequest and GetTelemetrySubscriptionsRequest may include a content-type field to allow for updated OTLP format versions (or additional formats), but this field is currently not included since only one format is specified by this proposal.
The SubscriptionId is a unique identifier for a client instance's subscription set, the id is generated by calculating a CRC32 of the configured metrics subscriptions matching the given client including the PushIntervalMs, XORed with the ClientInstanceId. This SubscriptionId is returned to the client in the GetTelemetrySubscriptionsResponse and the client passes that SubscriptionId in each subsequent PushTelemetryRequest for those received metrics. If the configured subscriptions are updated and resulting in a change for a client instance, the SubscriptionId is recalculated. Upon the next PushTelemetryRequest using the previous SubscriptionId, the broker will find that the received and expected SubscriptionIds differ and it will return UnknownSubscriptionId back to the client. When a client receives this error code it will immediately send a GetTelemetrySubscriptionsRequest to retrieve the new subcription set along with a new SubscriptionId.
This mechanism provides a way for the broker to propagate an updated subscription set to the client and is similar to the use of Epochs in other parts of the protocol, but simplified in that no state needs to be persisted - the configured subscription set + client instance id is the identifier itself.
Broker metrics receiver
The broker will expose a plugin interface for client telemetry to be forwarded to or collected by external systems. In particular, since we already collect data in OpenTelemetry format, one goal is to make it possible for a plugin to forward metrics directly to an OpenTelemetry collector.
The existing MetricsReporter plugin interface was built for plugins to pull metrics from the broker, but does not lend itself to the model where the broker pushes metric samples to plugins.
In order to minimize the complexity of additional configuration mechanisms, we are proposing to reuse the existing metrics reporter configuration mechanisms, but allow plugins to implement a new interface (trait) to indicate if they support receiving client telemetry.
This also allows a plugin to reuse the existing labels passed through the MetricsContext (e.g. broker, cluster id, and configured labels) and add them to the OpenTelemetry resource labels as needed.
Retrieve broker-generated client instance id, may be used by application to assist in mapping the client instance id to the application instance through log messages or other means.
The following method should be added to the Producer, Consumer, and Admin client interfaces;
If the client has not yet requested a client instance id from the broker this call will block up to the timeout. If no client instance id can be retrieved within the timeout an error is returned/raised (timeout, feature not supported by broker, auth failure, etc).
enable.metrics.push=true|false (default: true) -Allows disabling the functionality outlined in this proposal which should be enabled by default.
New error codes
UnknownSubscriptionId - See Error handling chapter.
This feature is made up of the following components:
- GetTelemetrySubscriptionsRequest|Response - protocol request used by the client to acquire its initial Client instance ID and to continually retrieve updated metrics subscriptions.
- PushTelemetryRequest|Response - protocol request used by the client to send metrics to any broker it is connected to.
- Standardised metrics - a set of standardised metrics that all supporting clients should provide.
- AdminAPI config - the AdminAPI configuration interface with a new CLIENT_METRICS resource type is used to manage metrics subscriptions.
- Client metrics plugin / extending the MetricsReporter interface - a broker plugin interface that performs something meaningful with the metrics. This plugin will typically forward the metrics to a time series database. It is recommended that any broker-side processing is kept to a minimum for scalability and performance reasons.
Client identification (CLIENT_INSTANCE_ID)
The value of metrics collection is limited if the metrics can’t be tied to an entity, in this case a client instance. While aggregate metrics do provide some value in trends and superficial monitoring, for metrics to be truly useful there needs to be a way to identify a particular client instance, where it runs, by who, etc.
While Kafka has a per-request client.id (which most Kafka clients allow to be optionally configured), it is in no way unique and can’t be used, despite its name, to identify a single client instance.
Other seemingly unique identifiers such as authentication principals, client IP source address and port, etc, are either not guaranteed to be unique (there may not be authentication involved or not specific to a single client instance), or not a singleton (a client will have multiple connections to the cluster each connection with its own unique address+port combination).
Since this KIP intends to have metrics enabled by default in supporting clients we can’t rely on the client.id being properly set by the application owner, so we have to resort to some other mechanism for a client instance to uniquely identify itself. There are ideally two entities that we would like to identify in metrics:
- Client instance - a single instance of a producer, consumer, Admin client, etc.
- Application process instance - a single application runtime, which may contain multiple client instances. E.g. a Kafka Streams application with a mix of Admin, producer and consumer instances.
This proposal suggests that as part of the initial metrics handshake the broker generates a unique client instance id UUID4 and returns it to the client. The client must use the returned client instance id for the remaining lifetime of the client instance regardless of which broker it communicates with.
The client should provide an API for the application to read the generated client instance id as to assist in mapping and identification of the client based on the collected metrics. As an alternative or complement the client may log its client instance id as soon as it has acquired it from the cluster. This allows live and post-mortem correlation between collected metrics and a client instance.
As it is not feasible for a Kafka client instance to automatically generate or acquire a unique identity for the application process it runs in, and as we can’t rely on the user to configure one, we treat the application instance id as an optional future nice-to-have that may be included as a metrics label if it has been set by the user. This allows a more direct mapping of client instance to application instance and vice versa. However, due to these constraints and the need for zero-configuration on the client, adding an application instance id configuration property is outside the scope of this proposal.
Kafka Streams applications have an
application.id configured and this identity should be included as the
application_id metrics label.
Mapping the client instance id to an actual application instance running on a (virtual) machine can be done by inspecting the metrics resource labels, such as the client source address and source port, or security principal, all of which are added by the receiving broker. This will allow the operator together with the user to identify the actual application instance.
Metrics naming and format
The OpenTelemetry specification will be used as the metrics serialization format as well as to define how metrics are constructed when it comes to naming, metric type, semantics, etc.
See the OpenTelemetry metrics specification for more information.
While future protocol-level request could allow for other metrics formats, Kafka will only ship with OpenTelemetry and it is required for a client that claims support of this KIP to use the OpenTelemetry v0.11 protobuf format.
Metric payloads are encoded as OpenTelemetry MetricsData protobuf objects.
Metrics will be named in a hierarchical format:
The metric namespace is org.apache.kafka for the standard metrics, vendor/implementation specific metrics may be added in separate namespaces, e.g:
The Apache Kafka Java client will provide implementation specific metrics in something akin to:
Metrics may hold any number of key=value labels which provide the multi-dimensionality of metrics, e.g., the per-partition queue bytes metric described above would have (at least) the following labels:
To keep metrics volume down it is recommended that a client only sends metrics with a recorded value.
Metric aggregation temporality
Metrics are to be sent as either DELTA or CUMULATIVE values, depending on the value of DeltaTemporality in the GetTelemetrySubscriptionsResponse.
CUMULATIVE metrics allow for missed/dropped transmits without loss of precision at the cost of increased processing and complexity required in upstream systems.
While clients must support both temporalities, the broker will initially only send GetTelemetrySubscriptionsResponse.DeltaTemporality=True. Configuration properties or extensions to the Metrics plugin interface on the broker to change the temporality is outside the scope of this KIP and may be addressed at a later time as the need arises.
See OTLP specification for more information on temporality.
As an example, the serialized size prior to compression of all producer and standard metrics defined in this KIP for a producer producing to 50 partitions gives approximately 100 kB.
As metric names and labels are highly repetitive it is recommended that the serialized metrics are compressed prior to sending them to the broker if the serialized uncompressed size exceeds 1000 bytes.
The broker will return a prioritized list of supported compression types in the GetTelemetrySubscriptionsResponse.AcceptedCompressionTypes array, the client is free to pick any supported compression type but should pick the first mutually supported type in the returned list. If the AcceptedCompressionTypes array is empty the client must send metrics uncompressed. The default compression types list as returned from the broker should be: ZStd, LZ4, GZip, Snappy.
The PushTelemtryRequest.CompressionType must then be set to the corresponding compression type value as defined for MessageV2.
Preliminary tests indicate that a compression ratio up to 10x is possible for the standard metrics using ZStd.
Decompression of the metrics data will be performed by the broker prior to passing the data to the metrics plugin.
A client that supports this metric interface and identifies a supportive broker (through detecting at least GetTelemetrySubscriptionsRequestV0 in the ApiVersionResponse) will start off by sending a GetTelemetrySubscriptionsRequest with the ClientInstanceId field set to Null to one randomly selected connected broker to gather its client instance id, the subscribed metrics, the push interval, accepted compression types, etc. This handshake with a Null ClientInstanceId is only performed once for a client instance's lifetime. Sub-sequent GetTelemetrySubscriptionsRequests must include the ClientInstanceId returned in the first response, regardless of broker.
Upon receiving the GetTelemetrySubscriptionsResponse the client shall update its internal metrics collection to match the received subscription (absolute update) and update its push interval timer according to the returned PushIntervalMs. The first metrics push should be randomized between 0.5 * PushIntervalMs and 1.5 * PushIntervalMs, this is to ensure that not all clients start pushing metrics at the same time after a cluster comes back up after some downtime.
If GetTelemetrySubscriptionsResponse.RequestedMetrics indicates that no metrics are desired (RequestedMetrics is Null) the client should send a new GetTelemetrySubscriptionsResponse after the PushIntervalMs has expired.
If GetTelemetrySubscriptionsResponse.RequestedMetrics is non-empty but does not match any metrics the client provides then the client should PushTelemetryRequests at the indicated PushIntervalMs interval with an empty metrics blob. This is needed so that a broker side metrics plugin can differentiate between non-responsive or buggy clients and clients that don't have metrics matching the subscription set.
The client will re-use the existing threads that are used for network communication. The existing logic in the
poll method of the
NetworkClient class issues internal network requests for metadata when needed. The
NetworkClient class has been augmented to now also issue internal network requests for telemetry based on the poll interval in the subscription.
The threads that invoke the
poll method are:
KafkaAdminClient: the "admin client runnable" thread
KafkaAdminClientcreates a dedicated thread to execute the
processRequestsmethod loops, polling for network requests via
KafkaConsumer: both the "heart beat" and application threads
ConsumerNetworkClient(which wraps a
NetworkClient) for network communication
KafkaConsumeralso creates a
ConsumerCoordinatorto manage consumer group members
ConsumerCoordinatoris provided with a reference to the
ConsumerNetworkClientinstance from the
AbstractCoordinatorsuperclass) maintains an inner thread class named
runmethod loops and invokes the
pollmethod, invoked by the caller on an application thread, also invokes the
- Thus when either the heartbeat thread runs or the application thread polls for new records, the internal
pollmethod is invoked
- Synchronization is performed by the
ConsumerNetworkClientto make sure two threads don't access the inner
- Synchronization is performed by the
KafkaProducer: the "sender" thread
Senderto run in a dedicated thread to manage produce requests
Senderis provided with a reference to the
NetworkClientinstance from the
runmethod loops, calling a method named
runOncein each pass
runOncemethod polls for network requests via
The client may send telemetry requests to any broker, but shall prefer using an already available connection rather than creating a new connection - to keep the number of cluster connections down.
It should also keep using the same broker connection for telemetry requests until the connection goes down, at which time it may choose to reconnect and continue using the same broker, or switch over to another broker connection. Using a persistent connection for PushTelemetryRequests is important so that metrics throttling can be properly performed by the receiving broker, and also avoids maintaining metrics state for the client instance id on multiple brokers.
When a client is being shut down it should send its final metrics regardless of the PushIntervalMs time, and only if the client has an active metrics subscription.
To avoid the receiving broker’s metrics rate-limiter to discard this out-of-profile push the PushTelemetryRequest.Terminating field must be set to true. A broker must only allow one such consecutive digression and otherwise throttle the client as if this field was not set.
The metrics should contain the reason for the client termination by including the client.terminating metric with the label “reason” set to a human readable explanation why the client is being shut down, such as “Fatal error: Static consumer fenced by newer instance”, or “Consumer closed by application”.
Actions to be taken by the client if the GetTelemetrySubscriptionsResponse.Error or PushTelemetryResponse.ErrorCode is set to a non-zero value.
Broker failed to decode or validate the client’s encoded metrics.
Log a warning to the application and schedule the next GetTelemetrySubscriptionsRequest to 5 minutes.
|UnknownSubscriptionId||Client sent a PushTelemetryRequest with an invalid or outdated SubscriptionId, the configured subscriptions have changed.||Send a GetTelemetrySubscriptionRequest to update the client's subscriptions.|
Client’s compression type is not supported by the broker.
Send a GetTelemetrySubscriptionRequest to get an up to date list of the broker's supported compression types (and any subscription changes).
The 5 and 30 minute retries are to eventually trigger a retry and avoid having to restart clients if the cluster metrics configuration is disabled temporarily, e.g., by operator error, rolling upgrades, etc.
Retries should preferably be attempted on the same broker connection, in particular for UnknownSubscriptionId, but another broker connection may be utilized at the discretion of the client.
How error and warnings are propagated to the application is client and language specific, simply logging the error is sufficient.
Client metrics should be enabled by default in the client but a user may disable the metrics functionality by setting the enable.metrics.push property to false.
Although metrics are enabled in a client, the client will only push metrics that have been configured/subscribed in the cluster.
Also see the Privacy chapter below.
Java client dependencies
The OpenTelemetry metrics serialization is used as metrics payload the payload of the telemetry metrics sent to the broker. This will require us to include the Java Bindings for the OpenTelemetry Protocol (OTLP) as a dependency for the Java client.
The OTLP Java bindings library is a minimal dependency and itself requires only the Google Protobuf serialization library:
This will allow us to build up Java objects in memory that reflect that specification and easily serialize them to the required transport wire format.
The Gradle build process will be updated to shadow the OTLP Java bindings library and its dependencies to avoid in-JVM versioning conflicts.
Receiving broker behaviour
We allow clients to send the GetTelemetrySubscriptions and PushTelemetry requests to any connected broker that reports support for both these APIs in its ApiVersionResponse.
If GetTelemetrySubscriptionsRequest.ClientInstanceId is Null the broker will generate a unique id for the client and return it in the response. Sub-sequent requests from the client to any broker must have the ClientInstanceId set to this returned value.
The broker should add additional metrics labels to help identify the client instance before forwarding the metrics to an external system. These are labels such as the namespace, cluster id, client principal, client source address and port, etc. As the metrics plugin may need to add additional metrics on top of this the generic metrics receiver in the broker will not add these labels but rely on the plugins to do so, this avoids deserializing and serializing the received metrics multiple times in the broker.
See Broker added labels below for the list of labels that should be added by the plugin.
If there is no client metrics receiver plugin configured on the broker it will respond to GetTelemetrySubscriptionsRequests with RequestedMetrics set to Null and a -1 SubscriptionId. The client should send a new GetTelemetrySubscriptionsRequest after the PushIntervalMs has expired. This allows the metrics receiver to be enabled or disabled without having to restart the broker or reset the client connection.
Validation of the encoded metrics is the task of the ClientMetricsReceiver, if the compression type is unsupported the response will be returned with ErrorCode set to UnsupportedCompressionType. Should decoding or validation of the binary metrics blob fail the ErrorCode will be set to InvalidRecord.
Throttling and rate-limiting
There are two mechanisms at play to protect brokers from rogue or buggy clients that:
- Standard request throttling - will mute the client connection if user quotas (size and/or request rate) are exceeded.
- Metrics PushIntervalMs rate-limiting - ensures the client does not push telemetry more often than the configured PushIntervalMs (subscription interval). As this rate-limiting state is maintained by each broker the client is sending telemetry requests to it is possible for the client to send at most one accepted out-of-profile per connection before the rate-limiter kicks in. The metrics plugin itself may also put constraints on the maximum allowed metrics payload.
The receiving broker’s standard quota-based throttling should operate as usual for PushTelemetryRequest, but in addition to that the PushTelemetryRequest is also subject to rate-limiting based on the calculated next desired PushIntervalMs interval derived from the configured metrics subscriptions. Should the client send a push request prior to expiry of the previously calculated PushIntervalMs the broker will discard the metrics and return a PushTelemetryResponse with the ErrorCode set to THROTTLING_QUOTA_EXCEEDED.
The one exception to this rule is when the client sets the PushTelemetryRequest.Terminating field to true indicating that the client is terminating, in this case the metrics should be accepted by the broker, but a consecutive request must ignore the Terminating field and apply rate-limiting as if the field was not set. The Terminating flag may be reused upon the next expiry of PushIntervalMs.
In case the cluster load induced from metrics requests becomes unmanageable the remedy is to temporarily remove or limit configured metrics subscriptions.
Metrics subscriptions are configured through the standard Kafka Admin API configuration interface with the new resource-type CLIENT_METRICS, the resource-name is any string - it does not have significance to the metrics system other than to group metrics subscriptions in the configuration interface. The configuration is made up of the following ConfigEntry names:
name- Optional human-readable name of the metric subscription. If one is not provided by the user, the admin client will first auto-generate a type-4 UUID to be used as the name before sending the request to the broker.
metrics- a comma-separated list of metric name prefixes, e.g.,
"client.producer.partition., client.io.wait". Whitespaces are ignored.
interval- metrics push interval in milliseconds. Defaults to 5 minutes if not specified.
match_<selector>- Client matching selector that is evaluated as an anchored regexp (i.e., "something.*" is treated as "^something.*$"). Any client that matches all of the
match_..selectors will be eligible for this metrics subscription. Initially supported selectors:
client_instance_id- CLIENT_INSTANCE_ID UUID string representation.
client_id- client's reported client.id in the GetTelemetrySubscriptionsRequest.
client_software_name- client software implementation name.
client_software_version- client software implementation version.
client_source_address- client connection's source address from the broker's point of view.
client_source_port- client connection's source port from the broker's point of view.
Example using the standard kafka-configs.sh tool:
Or using the dedicated tool (preferred):
As the assumption is that the number of CLIENT_METRICS configuration entries will be relatively small (<100), all brokers with a configured metrics plugin will monitor and cache the configuration entries for the CLIENT_METRICS resource type.
As a GetTelemetrySubscriptionsRequest is received for a previously unknown client instance id the CLIENT_METRICS config cache is scanned for any configured metric subscriptions whose match selectors match that of the client. The resulting matching configuration entries are compiled into a list of subscribed metrics which is returned in GetTelemetrySubscriptionsResponse.RequestedMetrics along with the minimum configured collection interval (this can be improved in future versions by including a per-metric interval so that each subscribed metric is collected with its configured interval, but in its current form longer-interval metrics are included “for free” if there are shorter-interval metrics in the subscription set). The CRC32 checksum is also calculated based on the compiled metrics and is returned as the SubscriptionId in the response, as well as stored in the per-client-instance cache on the broker to track configuration changes.
This client instance specific state is maintained in broker memory up to MAX(60*1000, PushIntervalMs * 3) milliseconds and is used to enforce the push interval rate-limiting. There is no persistence of client instance metrics state across broker restarts or between brokers.
New broker metrics
The following new broker metrics should be added:
version: broker's software version
Current number of client metric instances being managed by the broker. E.g., the number of unique CLIENT_INSTANCE_IDs with an empty or non-empty subscription set.
version: broker's software version
Total number of GetTelemetrySubscriptionsRequests received by this broker.
client version: client's software version
Total number of metrics requests GetTelemetrySubscriptionsRequests with unknown CLIENT_INSTANCE_IDs.
Total number of throttled PushTelemetryRequests due to a higher PushTelemetryRequest rate than the allowed PushIntervalMs.
The total number of metrics requests being pushed to metrics plugins, e.g., the number of exportMetrics() calls.
The total number of exceptions raised from plugin's exportMetrics().
|ClientMetricsPluginExportTime||Histogram||ClientMetrics||client_instance_id||Amount of time broker spends in invoking plugin exportMetrics call|
Client metrics and metric labels
Defining a standard metrics set makes monitoring and troubleshooting easier, as the operator can combine the same metric from multiple client types in the same graph, e.g., request latencies, and it also makes setting up metrics subscriptions easier. Care has been taken to make these standard metrics as generic as possible, and should fit most Kafka client implementations. We try to avoid metrics that are available or derivable from existing broker metrics.
All standard metrics are prefixed with the “org.apache.kafka.” namespace , this prefix is omitted from the following tables for brevity.
Clients that support this KIP should provide at least a subset of the following standard metrics, given that the metrics are relevant to that client implementation.
Client implementations may also provide additional metrics that are specific to that implementation, these custom metrics must reside in their own namespace by prefixing the metric name with their own namespace. The official Apache Kafka Java clients resides in the official org.apache.kafka namespace.
The default metrics collection on the client must take extra care not to expose any information about the application and system it runs on as they may identify internal projects, infrastructure, etc, that the user may not want to expose to the Kafka infrastructure owner. This includes information such as hostname, operating system, credentials, runtime environment, etc. None of the metrics defined in this proposal expose any such information.
OpenTelemetry specifies a range of relevant metrics:
Private or host metrics are outside the scope of this specification.
The metric types in the following tables correspond to the OpenTelemetry v1 metrics protobuf message types. A short summary:
- Sum - Monotonic total count meter (Counter). Suitable for total number of X counters, e.g., total number of bytes sent.
- Gauge - Non-monotonic current value meter (UpDownCounter). Suitable for current value of Y, e.g., current queue count.
- Histogram - Value distribution meter (ValueRecorder). Suitable for latency values, etc.
For simplicy a client implementation may choose to provide an average value as Gauge instead of a Histogram. These averages should be using the original Histogram metric name + ".avg", e.g., "client.request.rtt.avg".
Client instance-level metrics
Total number of broker connections made.
Current number of broker connections.
Total number of broker connection failures. Label ‘reason’ indicates the reason:
disconnect - remote peer closed the connection.
auth - authentication failure.
TLS - TLS failure.
timeout - client request timeout.
close - client closed the connection.
Average request latency / round-trip-time to broker and back.
request_type is the protocol request type CamelCase name as specified in the Kafka protocol definition.
Average request queue latency waiting for request to be sent to broker.
Number of requests in queue waiting to be sent to broker.
Number of successful requests to broker, that is where a response is received without no request-level error (but there may be per-sub-resource errors, e.g., errors for certain partitions within an OffsetCommitResponse).
Number of failed requests.
Label ‘reason’ indicates the reason:
timeout - client timed out the request,
disconnect - broker connection was closed before response could be received,
error - request-level protocol error.
Amount of time waiting for socket I/O writability (POLLOUT). A high number indicates socket send buffer congestion.
As the client will not know the broker id of its bootstrap servers the broker_id label should be set to to the negative index of the broker in the client's bootstrap.servers list, starting at -1.
Client instance-level Producer metrics
Current amount of memory used in producer record queues.
Total amount of queue/buffer memory allowed on the producer queue(s).
Current number of records on the producer queue(s).
Maximum amount of records allowed on the producer queue(s).
Client instance-level Consumer metrics
The interval at which the application calls poll(), in seconds.
The number of seconds since the last poll() invocation.
The time it takes poll() to return a new message to the application
Number of commit requests sent.
Number of currently assigned partitions to this consumer by the group leader.
Number of currently assigned partitions to this consumer, either through the group protocol or through assign().
Number of group rebalances.
|client.consumer.group.error.count||Sum||reason||Consumer group error counts. The reason label depicts the reason for rebalance., "MaxPollExceeded", "HeartbeatTimeout", "RebalanceInProgress" (remote), etc.|
Number of records in consumer pre-fetch queue.
Amount of record memory in consumer pre-fetch queue. This may also include per-record overhead.
Number of records consumed by application.
Memory of records consumed by application.
Client topic-level Producer metrics
Number of bytes queued on partition queue.
Number of records queued on partition queue.
Total produce record latency, from application calling send()/produce() to ack received from broker.
Time between send()/produce() and record being sent to broker.
Number of ProduceRequest retries.
Number of records that permanently failed delivery. Reason is a short string representation of the reason, which is typically the name of a Kafka protocol error code, e.g., “RequestTimedOut”.
Number of records that have been successfully produced.
The “partition” label should be -1 for not yet partitioned messages, as they are not yet assigned to a partition queue.
Host process metrics (optional)
These metrics provide runtime information about the operating system process the client runs in.
Current process/runtime memory usage (RSS, not virtual).
User CPU time used (seconds).
System CPU time used (seconds).
The process id. Can be used, in conjunction with the client host name to map multiple client instances to the same process.
Standard client resource labels
client.rack (if configured)
Group member id (if any, consumer)
The following labels should be added by the broker plugin as metrics are received
|The generated CLIENT_INSTANCE_ID.|
|client_id||client.id as reported in the Kafka protocol header.|
The client’s implementation name as reported in ApiVersionRequest.
|The client’s version as reported in ApiVersionRequest.|
The client connection’s source address.
The client connection’s source port.
Client’s security principal. Content depends on authentication method.
Receiving broker’s node-id.
Since client metric subscriptions are primarily aimed at the infrastructure operator that is managing the Kafka cluster it should be sufficient to limit the config control operations to the CLUSTER resource.
There will be no permission checks on the PushTelemetryRequest itself.
See the Private metrics chapter above for privacy/integrity.
kafka-client-metrics.sh is a wrapper tool around
kafka-configs.sh that makes it easier to set up metric subscriptions.
Note: Internally, blocking is performed by setting the push interval to 0, which nulls all other matching subscriptions.
Example workflows showcasing how this feature may be used for proactive and reactive purposes.
The Kafka cluster is configured to collect all standard metrics pushed by the client at an interval of 60 seconds, the metrics plugin forwards the collected metrics to an imaginary system that monitors a set of well known metrics and triggers alarms when trends go out of profile.
The monitoring system detects an anomaly for CLIENT_INSTANCE_ID=4e6fb54c-b8e6-4517-889b-e15b99c09c20’s metric org.apache.kafka.client.producer.partition.queue.latency which for more than 180 seconds has exceeded the threshold of 5000 milliseconds.
Before sending the alert to the incident management system the monitoring system collects a set of labels that are associated with this CLIENT_INSTANCE_ID, such as:
- client_source_address and client_source_port on broker id X (1 or more such mappings based on how many connections the client has used to push metrics).
- client_software_name and client_software_version
- In case of consumer: group_id, group_instance_id (if configured) and the latest known group_member_id.
- In case of transactional producer: transactional_id
This collection of information, along with the triggered metric, is sent to the incident management system for further investigation or aggregation, and provides enough information to identify who and where the client is run. Further action might be to contact the organization or team that matches the principal, transactional.id, source address, etc, for further investigation.
The Kafka cluster configuration for metrics collection (i.e., metrics subscriptions) is irrelevant to this use-case, given that a metrics plugin is enabled on the brokers. The metrics plugin is configured to write metrics to a topic. A support system with an interactive interface is reading from this metrics topic, and has an Admin client to configure the cluster with desired metrics subscriptions.
The application owner reports a lagging consumer that is not able to keep up with the incoming message rate and asks for the Kafka operator to help troubleshoot. The application owner, who unfortunately does not know the client instance id of the consumer, provides the client.id, userid, and source address.
The Kafka operator adds a metrics subscription for metrics matching prefix “org.apache.kafka.client.consumer.” and with the client_source_address and client_id as matching selector. Since this is a live troubleshooting case the metrics push interval is set to a low 10 seconds.
The metrics subscription propagates through configuration change notifications to all brokers which update their local metrics subscription config cache and regenerates the SubscriptionId.
Upon the next intervalled PushTelemetryRequest or GetTelemetrySubscriptionsRequest from the clients matching the given source address and client_id the receiving broker sees that the SubscriptionId no longer matches its metrics subscription cache, the client retrieves the new metrics subscription and schedules its next metrics push to a random value between PushIntervalMs * 0.5 .. PushIntervalMs * 1.5.
Upon the next PushTelemetryRequest, which now includes metrics for the subscribed metrics, the metrics are written to the output topic and the PushIntervalMs is adjusted to the configured interval of 10 seconds. This repeats until the metrics subscription configuration is changed.
Multiple consumers from the same source address and using the same client_id may now be pushing metrics to the cluster. The support system starts receiving the metrics and displays the matching client metrics to the operator. If the operator is able to further narrow down the client instance through other information in the metrics it may alter the metrics subscription to match on that client's client_instance_id. But in either case the metrics matching the given client.id are displayed to the operator.
The operator identifies an increasing trend in client.consumer.processing.time which indicates slow per-message processing in the application and reports this back to the application owner, ruling out the client and Kafka cluster from the problem space.
The operator removes the metrics subscription which causes the next PushTelemetryResponse to return an error indicating that the metrics subscription has changed, causing the client to get its new subscription which is now back to empty.
Tracing and logging are outside the scope of this proposal but the use of OpenTelemetry allows for those additional two methods within the same semantics and nomenclature outlined by this proposal.
Compatibility, Deprecation, and Migration Plan
What impact (if any) will there be on existing users?
Short of the configuration property to disable telemetry (enable.metrics.push=false - enabled by default) there are no user-facing changes to client users.
Depending on metrics subscription intervals there might be increased CPU and network load, but for modestly set subscription intervals this should be negligible.
The Kafka admin needs to explicitly configure a Metrics reporter plugin that supports the new push-based telemtry interface. If no such plugin is configured the telemetry collection is disabled and there will be no user-facing changes.
Depending on the metrics subscription patterns and intervals there is likely to be increased CPU and network load as brokers will receive, decompress and forward pushed client telemetry to the metrics plugin.
If we are changing behavior how will we phase out the older behavior?
No behavioural changes.
If we need special migration tools, describe them here.
When will we remove the existing behavior?
Send metrics out-of-band directly to collector or to separate metric cluster
There are plenty of existing solutions that allows a client implementation to send metrics directly to a collector, but it falls short to meet the enabled-by-default requirements of this KIP:
- will require additional client-side configuration: endpoints, authentication, etc.
- may require additional network filtering and our routing configuration to allow the client host to reach the collector endpoints. By using the Kafka protocol we already have a usable connection.
- adds another network protocol the client needs to handle and its runtime dependencies (libraries..).
- makes correlation between client instances and connections on the broker harder - which makes correlating client side and broker side metrics harder.
- more points of failure: what if the collector is down but the cluster is up?
- zero conf is an absolute must for KIP-714 to provide value: It is already possible today to send metrics out-of-band, but people don't and they still won't if any extra configuration is needed.
An alternative approach is to send metrics to a different Kafka cluster, the idea is that having metrics go through the same cluster may mean client metrics may be unavailable if the original cluster is unavailable, and this suggestion would solve that by sending metrics to a different cluster that is not affected by original cluster problems.
This however has the same problems as described above, and requires an additional client instance to connect to the metrics cluster for each client instance connecting to the original cluster, which adds more complexity. Also, it is not clear how the metrics client itself is monitored.
Produce metrics data directly to a topic
Instead of using a dedicated PushTelemetryRequest, the suggestion is to use the existing ProduceRequest to send telemetry to a predefined topic on the cluster. While this has benefits in that it provides an existing method for sending compressed data to the cluster, there are more issues:
- While an existing producer instance could also produce to this topic, a consumer would need to instantiate a new producer instance for sending these metrics. In an application with many consumers, which is not uncommon, this would double the number of connections to the cluster, and increase the resource usage (memory, cpu, threads) of the application.
- A separate producer instance makes the mapping between original connection and client instance id more complex.
- What observes/collect metrics for the metrics producer instance?
- Lack of abstraction. We don't do this for any other parts of the protocol (i.e., OffsetCommitRequest could be a ProduceRequest, so could the transactional requests. FindCoordinator could be done through local hashing and metadata, etc, etc,). Makes future improvements, changes, a lot more problematic: How do we add functionality that is not covered by the produce API?
- More points of failure by introducing an additional client instance and additional connections.
- Requires metric to (at least temporarily) to be stored in a topic. Operators may want to push metrics upstream directly.
Dedicated Metrics coordinator based on client instance id
An earlier version of this proposal had the notion of metrics coordinator which was selected based on the client instance id. This metrics coordinator would be responsible for rate-limiting pushed metrics per client instance. To avoid each client to have a connection to its metric coordinator the proposal suggested using the impersonation/request-forwarding functionality suggested in a contemporary design by Jason G.
Since this made the broker-side implementation more complex and did not provide fool-proof control of misbehaving clients (a rogue client could simply generate new instance ids on each request) it was decided that the value of this functionality was not in par with the implementation cost and thus removed from the proposal.
Scales poorly, Java-specific, commonly mistaken for a trick bike.
Combine with Dynamic client configuration
The Push interface is well suited for propagating client configuration to clients, but to keep scope down we leave that out of this proposal. It should be straightforward to extend and repurpose the interface described in this proposal to also support dynamic client configuration, log/event retrieval, etc, at a later time.
Use native Kafka protocol framing for metrics
The Kafka protocol has flexible fields that would allow us to construct the metrics serialization with pure Kafka protocol fields, but this would duplicate the efforts of the OpenTelemetry specification where Kafka would have to maintain its own specification. On the broker side the native Kafka protocol metrics would need to be converted to OpenTelemetry (or other) format anyway.
The OpenTelemetry serialization format is all Protobufs and should thus be generally available across all client implementation languages.